forked from sackmotion/motion
-
Notifications
You must be signed in to change notification settings - Fork 5
/
netcam.c
2916 lines (2517 loc) · 102 KB
/
netcam.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
/*
* netcam.c
*
* Module for handling network cameras.
*
* This code was inspired by the original netcam.c module
* written by Jeroen Vreeken and enhanced by several Motion
* project contributors, particularly Angel Carpintero and
* Christopher Price.
*
* Copyright 2005, William M. Brack
* This software is distributed under the GNU Public license
* Version 2. See also the file 'COPYING'.
*
*
* When a netcam has been configured, instead of using the routines
* within video.c (which handle a CCTV-type camera) the routines
* within this module are used. There are only four entry points -
* one for "starting up" the camera (netcam_start), for "fetching a
* picture" from it (netcam_next), one for cleanup at the end of a
* run (netcam_cleanup), and a utility routine for receiving data
* from the camera (netcam_recv).
*
* Two quite different types of netcams are handled. The simplest
* one is the type which supplies a single JPEG frame each time it
* is accessed. The other type is one which supplies an mjpeg
* stream of data.
*
* For each of these cameras, the routine taking care of the netcam
* will start up a completely separate thread (which I call the "camera
* handler thread" within subsequent comments). For a streaming camera,
* this handler will receive the mjpeg stream of data from the camera,
* and save the latest complete image when it begins to work on the next
* one. For the non-streaming version, this handler will be "triggered"
* (signalled) whenever the main motion-loop asks for a new image, and
* will start to fetch the next image at that time. For either type,
* the most recent image received from the camera will be returned to
* motion.
*/
#include "motion.h"
#include <netdb.h>
#include <netinet/in.h>
#include <regex.h> /* For parsing of the URL */
#include <sys/socket.h>
#include "netcam_ftp.h"
#include "netcam_rtsp.h"
#define CONNECT_TIMEOUT 10 /* Timeout on remote connection attempt */
#define READ_TIMEOUT 5 /* Default timeout on recv requests */
#define POLLING_TIMEOUT READ_TIMEOUT /* File polling timeout [s] */
#define POLLING_TIME 500*1000*1000 /* File polling time quantum [ns] (500ms) */
#define MAX_HEADER_RETRIES 5 /* Max tries to find a header record */
#define MINVAL(x, y) ((x) < (y) ? (x) : (y))
tfile_context *file_new_context(void);
void file_free_context(tfile_context* ctxt);
/* These strings are used for the HTTP connection. */
static const char *connect_req;
static const char *connect_req_http10 = "GET %s HTTP/1.0\r\n"
"Host: %s\r\n"
"User-Agent: Motion-netcam/" VERSION "\r\n";
static const char *connect_req_http11 = "GET %s HTTP/1.1\r\n"
"Host: %s\r\n"
"User-Agent: Motion-netcam/" VERSION "\r\n";
static const char *connect_req_close = "Connection: close\r\n";
static const char *connect_req_keepalive = "Connection: Keep-Alive\r\n";
static const char *connect_auth_req = "Authorization: Basic %s\r\n";
/*
* The following three routines (netcam_url_match, netcam_url_parse and
* netcam_url_free are for 'parsing' (i.e. separating into the relevant
* components) the URL provided by the user. They make use of regular
* expressions (which is outside the scope of this module, so detailed
* comments are not provided). netcam_url_parse is called from netcam_start,
* and puts the "broken-up" components of the URL into the "url" element of
* the netcam_context structure.
*
* Note that the routines are not "very clever", but they work sufficiently
* well for the limited requirements of this module. The expression:
* (http)://(((.*):(.*))@)?([^/:]|[-.a-z0-9]+)(:([0-9]+))?($|(/[^:]*))
* requires
* 1) a string which begins with 'http', followed by '://'
* 2) optionally a '@' which is preceded by two strings
* (with 0 or more characters each) separated by a ':'
* [this is for an optional username:password]
* 3) a string comprising alpha-numerics, '-' and '.' characters
* [this is for the hostname]
* 4) optionally a ':' followed by one or more numeric characters
* [this is for an optional port number]
* 5) finally, either an end of line or a series of segments,
* each of which begins with a '/', and contains anything
* except a ':'
*/
/**
* netcam_url_match
*
* Finds the matched part of a regular expression
*
* Parameters:
*
* m A structure containing the regular expression to be used
* input The input string
*
* Returns: The string which was matched
*
*/
static char *netcam_url_match(regmatch_t m, const char *input)
{
char *match = NULL;
int len;
if (m.rm_so != -1) {
len = m.rm_eo - m.rm_so;
if ((match = (char *) mymalloc(len + 1)) != NULL) {
strncpy(match, input + m.rm_so, len);
match[len] = '\0';
}
}
return match;
}
/**
* netcam_url_parse
*
* parses a string containing a URL into it's components
*
* Parameters:
* parse_url A structure which will receive the results
* of the parsing
* text_url The input string containing the URL
*
* Returns: Nothing
*
*/
static void netcam_url_parse(struct url_t *parse_url, const char *text_url)
{
char *s;
int i;
const char *re = "(http|ftp|mjpg|rtsp)://(((.*):(.*))@)?"
"([^/:]|[-.a-z0-9]+)(:([0-9]+))?($|(/[^:]*))";
regex_t pattbuf;
regmatch_t matches[10];
if (!strncmp(text_url, "file", 4))
re = "(file)://(((.*):(.*))@)?"
"([^/:]|[-.a-z0-9]*)(:([0-9]*))?($|(/[^:][/-_.a-z0-9]+))";
MOTION_LOG(DBG, TYPE_NETCAM, NO_ERRNO, "%s: Entry netcam_url_parse data %s",
text_url);
memset(parse_url, 0, sizeof(struct url_t));
/*
* regcomp compiles regular expressions into a form that is
* suitable for regexec searches
* regexec matches the URL string against the regular expression
* and returns an array of pointers to strings matching each match
* within (). The results that we need are finally placed in parse_url.
*/
if (!regcomp(&pattbuf, re, REG_EXTENDED | REG_ICASE)) {
if (regexec(&pattbuf, text_url, 10, matches, 0) != REG_NOMATCH) {
for (i = 0; i < 10; i++) {
if ((s = netcam_url_match(matches[i], text_url)) != NULL) {
MOTION_LOG(DBG, TYPE_NETCAM, NO_ERRNO, "%s: Parse case %d"
" data %s", i, s);
switch (i) {
case 1:
parse_url->service = s;
break;
case 3:
parse_url->userpass = s;
break;
case 6:
parse_url->host = s;
break;
case 8:
parse_url->port = atoi(s);
free(s);
break;
case 9:
parse_url->path = s;
break;
/* Other components ignored */
default:
free(s);
break;
}
}
}
}
}
if ((!parse_url->port) && (parse_url->service)) {
if (!strcmp(parse_url->service, "http"))
parse_url->port = 80;
else if (!strcmp(parse_url->service, "ftp"))
parse_url->port = 21;
else if (!strcmp(parse_url->service, "rtsp") && parse_url->port == 0)
parse_url->port = 554;
}
regfree(&pattbuf);
}
/**
* netcam_url_free
*
* General cleanup of the URL structure, called from netcam_cleanup.
*
* Parameters:
*
* parse_url Structure containing the parsed data.
*
* Returns: Nothing
*
*/
static void netcam_url_free(struct url_t *parse_url)
{
if (parse_url->service) {
free(parse_url->service);
parse_url->service = NULL;
}
if (parse_url->userpass) {
free(parse_url->userpass);
parse_url->userpass = NULL;
}
if (parse_url->host) {
free(parse_url->host);
parse_url->host = NULL;
}
if (parse_url->path) {
free(parse_url->path);
parse_url->path = NULL;
}
}
/**
* check_quote
*
* Checks a string to see if it's quoted, and if so removes the
* quotes.
*
* Parameters:
*
* str Pointer to a string.
*
* Returns: Nothing, but updates the target if necessary.
*
*/
static void check_quote(char *str)
{
int len;
char ch;
ch = *str;
if ((ch == '"') || (ch == '\'')) {
len = strlen(str) - 1;
if (str[len] == ch) {
memmove(str, str+1, len-1);
str[len-1] = 0;
}
}
}
/**
* netcam_check_content_length
*
* Analyse an HTTP-header line to see if it is a Content-length.
*
* Parameters:
*
* header Pointer to a string containing the header line.
*
* Returns:
* -1 Not a Content-length line.
* >=0 Value of Content-length field.
*
*/
static long netcam_check_content_length(char *header)
{
long length = -1; /* Note this is a long, not an int. */
if (!header_process(header, "Content-Length", header_extract_number, &length)) {
/*
* Some netcams deliver some bad-format data, but if
* we were able to recognize the header section and the
* number we might as well try to use it.
*/
if (length > 0)
MOTION_LOG(WRN, TYPE_NETCAM, NO_ERRNO, "%s: malformed token"
" Content-Length but value %ld", length);
}
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Content-Length %ld",
length);
return length;
}
/**
* netcam_check_keepalive
*
* Analyse an HTTP-header line to see if it is a Keep-Alive.
*
* Parameters:
*
* header Pointer to a string containing the header line.
*
* Returns:
* -1 Not a Keep-Alive line.
* 1 Is a Keep-Alive line.
*
*/
static int netcam_check_keepalive(char *header)
{
char *content_type = NULL;
if (!header_process(header, "Keep-Alive", http_process_type, &content_type))
return -1;
/* We do not detect the second field or other case mixes at present. */
if (content_type)
free(content_type);
return 1;
}
/**
* netcam_check_close
*
* Analyse an HTTP-header line to see if it is a Connection: close.
*
* Parameters:
*
* header Pointer to a string containing the header line.
*
* Returns:
* -1 Not a Connection: close.
* 1 Is a Connection: close.
*
*/
static int netcam_check_close(char *header)
{
char *type = NULL;
int ret = -1;
if (!header_process(header, "Connection", http_process_type, &type))
return -1;
if (!strcmp(type, "close")) /* strcmp returns 0 for match. */
ret = 1;
if (type)
free(type);
return ret;
}
/**
* netcam_check_content_type
*
* Analyse an HTTP-header line to see if it is a Content-type.
*
* Parameters:
*
* header Pointer to a string containing the header line.
*
* Returns:
* -1 Not a Content-type line
* 0 Content-type not recognized
* 1 image/jpeg
* 2 multipart/x-mixed-replace or multipart/mixed
* 3 application/octet-stream (used by WVC200 Linksys IP Camera)
*
*/
static int netcam_check_content_type(char *header)
{
char *content_type = NULL;
int ret;
if (!header_process(header, "Content-type", http_process_type, &content_type))
return -1;
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Content-type %s",
content_type);
if (!strcmp(content_type, "image/jpeg")) {
ret = 1;
} else if (!strcmp(content_type, "multipart/x-mixed-replace") ||
!strcmp(content_type, "multipart/mixed")) {
ret = 2;
} else if (!strcmp(content_type, "application/octet-stream")) {
ret = 3;
} else {
ret = 0;
}
if (content_type)
free(content_type);
return ret;
}
/**
* netcam_read_next_header
*
* Read the next header record from the camera.
*
* Parameters
*
* netcam pointer to a netcam_context.
*
* Returns: 0 for success, -1 if any error.
*
*/
static int netcam_read_next_header(netcam_context_ptr netcam)
{
int retval;
char *header;
/* Return if not connected */
if (netcam->sock == -1)
return -1;
/*
* We are expecting a header which *must* contain a mime-type of
* image/jpeg, and *might* contain a Content-Length.
*
* If this is a "streaming" camera, the header *must* be preceded
* by a "boundary" string.
*
*/
netcam->caps.content_length = 0;
/*
* If this is a "streaming" camera, the stream header must be
* preceded by a "boundary" string.
*/
if (netcam->caps.streaming == NCS_MULTIPART) {
while (1) {
retval = header_get(netcam, &header, HG_NONE);
if (retval != HG_OK) {
/* Header reported as not-OK, check to see if it's null. */
if (strlen(header) == 0) {
MOTION_LOG(WRN, TYPE_NETCAM, NO_ERRNO, "%s: Error reading image header, "
"streaming mode (1). Null header.");
} else {
/* Header is not null. Output it in case it's a new camera with unknown headers. */
MOTION_LOG(WRN, TYPE_NETCAM, NO_ERRNO, "%s: Error reading image header, "
"streaming mode (1). Unknown header '%s'",
header);
}
free(header);
return -1;
}
retval = (strstr(header, netcam->boundary) == NULL);
free(header);
if (!retval)
break;
}
}
while (1) {
retval = header_get(netcam, &header, HG_NONE);
if (retval != HG_OK) {
MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Error reading image header (2)");
free(header);
return -1;
}
if (*header == 0)
break;
if ((retval = netcam_check_content_type(header)) >= 0) {
if (retval != 1) {
MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Header not JPEG");
free(header);
return -1;
}
}
if ((retval = (int) netcam_check_content_length(header)) >= 0) {
if (retval > 0) {
netcam->caps.content_length = 1; /* Set flag */
netcam->receiving->content_length = retval;
} else {
netcam->receiving->content_length = 0;
MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Content-Length 0");
free(header);
return -1;
}
}
free(header);
}
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Found image header record");
free(header);
return 0;
}
/**
* netcam_read_first_header
*
* This routine attempts to read a header record from the netcam. If
* successful, it analyses the header to determine whether the camera is
* a "streaming" type. If it is, the routine looks for the Boundary-string;
* if found, it positions just past the string so that the image header can
* be read. It then reads the image header and continues processing that
* header as well.
*
* If the camera does not appear to be a streaming type, it is assumed that the
* header just read was the image header. It is processed to determine whether
* a Content-length is present.
*
* After this processing, the routine returns to the caller.
*
* Parameters:
* netcam Pointer to the netcam_context structure.
*
* Returns: Content-type code if successful, -1 if not
* -2 if Content-length = 0
*/
static int netcam_read_first_header(netcam_context_ptr netcam)
{
int retval = -3; /* "Unknown err" */
int ret;
int firstflag = 1;
int aliveflag = 0; /* If we have seen a Keep-Alive header from cam. */
int closeflag = 0; /* If we have seen a Connection: close header from cam. */
char *header;
char *boundary;
/* Send the initial command to the camera. */
if (send(netcam->sock, netcam->connect_request,
strlen(netcam->connect_request), 0) < 0) {
MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "%s: Error sending"
" 'connect' request");
return -1;
}
/*
* We expect to get back an HTTP header from the camera.
* Successive calls to header_get will return each line
* of the header received. We will continue reading until
* a blank line is received.
*
* As we process the header, we are looking for either of
* header lines Content-type or Content-length. Content-type
* is used to determine whether the camera is "streaming" or
* "non-streaming", and Content-length will be used to determine
* whether future reads of images will be controlled by the
* length specified before the image, or by a boundary string.
*
* The Content-length will only be present "just before" an
* image is sent (if it is present at all). That means that, if
* this is a "streaming" camera, it will not be present in the
* "first header", but will occur later (after a boundary-string).
* For a non-streaming camera, however, there is no boundary-string,
* and the first header is, in fact, the only header. In this case,
* there may be a Content-length.
*
*/
while (1) { /* 'Do forever' */
ret = header_get(netcam, &header, HG_NONE);
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Received first header ('%s')",
header);
if (ret != HG_OK) {
MOTION_LOG(WRN, TYPE_NETCAM, NO_ERRNO, "%s: Error reading first header (%s)",
header);
free(header);
return -1;
}
if (firstflag) {
if ((ret = http_result_code(header)) != 200) {
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: HTTP Result code %d",
ret);
free(header);
if (netcam->connect_keepalive) {
/*
* Cannot unset netcam->cnt->conf.netcam_keepalive as it is assigned const
* But we do unset the netcam keepalive flag which was set in netcam_start
* This message is logged as Information as it would be useful to know
* if your netcam often returns bad HTTP result codes.
*/
netcam->connect_keepalive = FALSE;
free((void *)netcam->cnt->conf.netcam_keepalive);
netcam->cnt->conf.netcam_keepalive = strdup("off");
MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Removed netcam Keep-Alive flag"
"due to apparent closed HTTP connection.");
}
return ret;
}
firstflag = 0;
free(header);
continue;
}
if (*header == 0) /* Blank line received */
break;
/* Check if this line is the content type. */
if ((ret = netcam_check_content_type(header)) >= 0) {
retval = ret;
/*
* We are expecting to find one of three types:
* 'multipart/x-mixed-replace', 'multipart/mixed'
* or 'image/jpeg'. The first two will be received
* from a streaming camera, and the third from a
* camera which provides a single frame only.
*/
switch (ret) {
case 1: /* Not streaming */
if (netcam->connect_keepalive)
MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Non-streaming camera "
"(keep-alive set)");
else
MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Non-streaming camera "
"(keep-alive not set)");
netcam->caps.streaming = NCS_UNSUPPORTED;
break;
case 2: /* Streaming */
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Streaming camera");
netcam->caps.streaming = NCS_MULTIPART;
if ((boundary = strstr(header, "boundary="))) {
/* On error recovery this may already be set. */
if (netcam->boundary)
free(netcam->boundary);
netcam->boundary = mystrdup(boundary + 9);
/*
* HTTP protocol apparently permits the boundary string
* to be quoted (the Lumenera does this, which caused
* trouble) so we need to get rid of any surrounding
* quotes.
*/
check_quote(netcam->boundary);
netcam->boundary_length = strlen(netcam->boundary);
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Boundary string [%s]",
netcam->boundary);
}
break;
case 3: /* MJPG-Block style streaming. */
MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Streaming camera probably using MJPG-blocks,"
" consider using mjpg:// netcam_url.");
break;
default:
/* Error */
MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Unrecognized content type");
free(header);
return -1;
}
} else if ((ret = (int) netcam_check_content_length(header)) >= 0) {
MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Content-length present");
if (ret > 0) {
netcam->caps.content_length = 1; /* Set flag */
netcam->receiving->content_length = ret;
} else {
netcam->receiving->content_length = 0;
MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: Content-length 0");
retval = -2;
}
} else if (netcam_check_keepalive(header) == TRUE) {
/* Note that we have received a Keep-Alive header, and thus the socket can be left open. */
aliveflag = TRUE;
netcam->keepalive_thisconn = TRUE;
/*
* This flag will not be set when a Streaming cam is in use, but that
* does not matter as the test below looks at Streaming state also.
*/
} else if (netcam_check_close(header) == TRUE) {
/* Note that we have received a Connection: close header. */
closeflag = TRUE;
/*
* This flag is acted upon below.
* Changed criterion and moved up from below to catch headers that cause returns.
*/
MOTION_LOG(NTC, TYPE_NETCAM, NO_ERRNO, "%s: Found Conn: close header ('%s')",
header);
}
free(header);
}
free(header);
if (netcam->caps.streaming == NCS_UNSUPPORTED && netcam->connect_keepalive) {
/* If we are a non-streaming (ie. Jpeg) netcam and keepalive is configured. */
if (aliveflag) {
if (closeflag) {
netcam->warning_count++;
if (netcam->warning_count > 3) {
netcam->warning_count = 0;
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Both 'Connection: Keep-Alive' and "
"'Connection: close' header received. Motion removes keepalive.");
netcam->connect_keepalive = FALSE;
free((void *)netcam->cnt->conf.netcam_keepalive);
netcam->cnt->conf.netcam_keepalive = strdup("off");
} else {
/*
* If not a streaming cam, and keepalive is set, and the flag shows we
* did not see a Keep-Alive field returned from netcam and a Close field.
* Not quite sure what the correct course of action is here. In for testing.
*/
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Both 'Connection: Keep-Alive' and "
"'Connection: close' header received. Motion continues unchanged.");
}
} else {
/*
* aliveflag && !closeflag
*
* If not a streaming cam, and keepalive is set, and the flag shows we
* just got a Keep-Alive field returned from netcam and no Close field.
* No action, as this is the normal case. In debug we print a notification.
*/
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Received a Keep-Alive field in this"
"set of headers.");
}
} else { /* !aliveflag */
if (!closeflag) {
netcam->warning_count++;
if (netcam->warning_count > 3) {
netcam->warning_count = 0;
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: No 'Connection: Keep-Alive' nor 'Connection: close'"
" header received.\n Motion removes keepalive.");
netcam->connect_keepalive = FALSE;
free((void *)netcam->cnt->conf.netcam_keepalive);
netcam->cnt->conf.netcam_keepalive = strdup("off");
} else {
/*
* If not a streaming cam, and keepalive is set, and the flag shows we
* did not see a Keep-Alive field returned from netcam nor a Close field.
* Not quite sure what the correct course of action is here. In for testing.
*/
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: No 'Connection: Keep-Alive' nor 'Connection: close'"
" header received.\n Motion continues unchanged.");
}
} else {
/*
* !aliveflag & closeflag
* If not a streaming cam, and keepalive is set, and the flag shows we
* received a 'Connection: close' field returned from netcam. It is not likely
* we will get a Keep-Alive and Close header together - this is picked up by
* the test code above.
* If we receive a Close header, then we want to cease keep-alive for this cam.
* This situation will occur in 2 situations:
* (a) in HTTP 1.1 when the client wants to stop the keep-alive
* (and in this case it would be correct to close connection and then
* make a new one, with keep-alive set again).
* (b) in HTTP 1.0 with keepalive, when the client does not support it.
* In this case we should not attempt to re-start Keep-Alive.
* Due to that, we accept a Connection: close header in HTTP 1.0 & 1.1 modes
*
* To tell between the sitation where a camera has been in Keep-Alive mode and
* is now finishing (and will want to be re-started in Keep-Alive) and the other
* case when a cam does not support it, we have a flag which says if the netcam
* has returned a Keep-Alive flag during this connection. If that's set, we
* set ourselves up to re-connect with Keep-Alive after the socket is closed.
* If it's not set, then we will not try again to use Keep-Alive.
*/
if (!netcam->keepalive_thisconn) {
netcam->connect_keepalive = FALSE; /* No further attempts at keep-alive */
free((void *)netcam->cnt->conf.netcam_keepalive);
netcam->cnt->conf.netcam_keepalive = strdup("off");
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: Removed netcam Keep-Alive flag because"
" 'Connection: close' header received.\n Netcam does not support "
"Keep-Alive. Motion continues in non-Keep-Alive.");
} else {
netcam->keepalive_timeup = TRUE; /* We will close and re-open keep-alive */
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "Keep-Alive has reached end of valid period.\n"
"Motion will close netcam, then resume Keep-Alive with a new socket.");
}
}
}
}
return retval;
}
/**
* netcam_disconnect
*
* Disconnect from the network camera.
*
* Parameters:
*
* netcam pointer to netcam context
*
* Returns: Nothing
*
*/
static void netcam_disconnect(netcam_context_ptr netcam)
{
if (netcam->sock > 0) {
if (close(netcam->sock) < 0)
MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "%s: netcam_disconnect");
netcam->sock = -1;
}
}
/**
* netcam_connect
*
* Attempt to open the network camera as a stream device.
* Keep-alive is supported, ie. if netcam->connect_keepalive is TRUE, we
* re-use netcam->sock unless it has value -1, meaning it is invalid.
*
* Parameters:
*
* netcam pointer to netcam_context structure
* err_flag flag to suppress error printout (1 => suppress)
* Note that errors which indicate something other than
* a network connection problem are not suppressed.
*
* Returns: 0 for success, -1 for error
*
*/
static int netcam_connect(netcam_context_ptr netcam, int err_flag)
{
struct sockaddr_in server; /* For connect */
struct addrinfo *res; /* For getaddrinfo */
int ret;
int saveflags;
int back_err;
int optval;
socklen_t optlen = sizeof(optval);
socklen_t len;
fd_set fd_w;
struct timeval selecttime;
/* Assure any previous connection has been closed - IF we are not in keepalive. */
if (!netcam->connect_keepalive) {
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: disconnecting netcam "
"since keep-alive not set.");
netcam_disconnect(netcam);
/* Create a new socket. */
if ((netcam->sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
MOTION_LOG(WRN, TYPE_NETCAM, SHOW_ERRNO, "%s: with no keepalive, attempt "
"to create socket failed.");
return -1;
}
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: with no keepalive, "
"new socket created fd %d", netcam->sock);
} else if (netcam->sock == -1) { /* We are in keepalive mode, check for invalid socket. */
/* Must be first time, or closed, create a new socket. */
if ((netcam->sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
MOTION_LOG(WRN, TYPE_NETCAM, SHOW_ERRNO, "%s: with keepalive set, invalid socket."
"This could be the first time. Creating a new one failed.");
return -1;
}
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: with keepalive set, invalid socket."
"This could be first time, created a new one with fd %d",
netcam->sock);
/* Record that this connection has not yet received a Keep-Alive header. */
netcam->keepalive_thisconn = FALSE;
/* Check the socket status for the keepalive option. */
if (getsockopt(netcam->sock, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen) < 0) {
MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "%s: getsockopt()");
return -1;
}
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: SO_KEEPALIVE is %s",
optval ? "ON":"OFF");
/* Set the option active. */
optval = 1;
optlen = sizeof(optval);
if (setsockopt(netcam->sock, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) {
MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "%s: setsockopt()");
return -1;
}
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: SO_KEEPALIVE set on socket.");
}
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: re-using socket %d since keepalive is set.",
netcam->sock);
/* Lookup the hostname given in the netcam URL. */
if ((ret = getaddrinfo(netcam->connect_host, NULL, NULL, &res)) != 0) {
if (!err_flag)
MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: getaddrinfo() failed (%s): %s",
netcam->connect_host, gai_strerror(ret));
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: disconnecting netcam (1)");
netcam_disconnect(netcam);
return -1;
}
/*
* Fill the hostname details into the 'server' structure and
* attempt to connect to the remote server.
*/
memset(&server, 0, sizeof(server));
memcpy(&server, res->ai_addr, sizeof(server));
freeaddrinfo(res);
server.sin_family = AF_INET;
server.sin_port = htons(netcam->connect_port);
/*
* We set the socket non-blocking and then use a 'select'
* system call to control the timeout.
*/
if ((saveflags = fcntl(netcam->sock, F_GETFL, 0)) < 0) {
MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "%s: fcntl(1) on socket");
netcam_disconnect(netcam);
return -1;
}
/* Set the socket non-blocking. */
if (fcntl(netcam->sock, F_SETFL, saveflags | O_NONBLOCK) < 0) {
MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "%s: fcntl(2) on socket");
netcam_disconnect(netcam);
return -1;
}
/* Now the connect call will return immediately. */
ret = connect(netcam->sock, (struct sockaddr *) &server,
sizeof(server));
back_err = errno; /* Save the errno from connect */
/* If the connect failed with anything except EINPROGRESS, error. */
if ((ret < 0) && (back_err != EINPROGRESS)) {
if (!err_flag)
MOTION_LOG(ERR, TYPE_NETCAM, SHOW_ERRNO, "%s: connect() failed (%d)",
back_err);
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: disconnecting netcam (4)");
netcam_disconnect(netcam);
return -1;
}
/* Now we do a 'select' with timeout to wait for the connect. */
FD_ZERO(&fd_w);
FD_SET(netcam->sock, &fd_w);
selecttime.tv_sec = CONNECT_TIMEOUT;
selecttime.tv_usec = 0;
ret = select(FD_SETSIZE, NULL, &fd_w, NULL, &selecttime);
if (ret == 0) { /* 0 means timeout. */
if (!err_flag)
MOTION_LOG(ERR, TYPE_NETCAM, NO_ERRNO, "%s: timeout on connect()");
MOTION_LOG(INF, TYPE_NETCAM, NO_ERRNO, "%s: disconnecting netcam (2)");
netcam_disconnect(netcam);
return -1;
}
/*
* A +ve value returned from the select (actually, it must be a
* '1' showing 1 fd's changed) shows the select has completed.
* Now we must check the return code from the select.