forked from Motion-Project/motion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.c
1343 lines (1126 loc) · 40.1 KB
/
stream.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
/*
* stream.c (based in webcam.c)
* Streaming using jpeg images over a multipart/x-mixed-replace stream
* Copyright (C) 2002 Jeroen Vreeken ([email protected])
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "translate.h"
#include "md5.h"
#include "picture.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ctype.h>
#include <fcntl.h>
#define STREAM_REALM "Motion Stream Security Access"
#define KEEP_ALIVE_TIMEOUT 100
typedef void* (*auth_handler)(void*);
struct auth_param {
struct context *cnt;
struct stream *stm;
int *stream_count;
int sock;
int sock_flags;
int* thread_count;
struct config *conf;
};
/**
* get_host
* Gets the host (IP) of a client from the socket file descriptor
* Returns nothing
*/
static void get_host(char *buf, int fd)
{
struct sockaddr_storage client;
socklen_t client_len = sizeof(client);
int res = getpeername(fd, (struct sockaddr *)&client, &client_len);
if (res != 0)
return;
char host[NI_MAXHOST];
res = getnameinfo((struct sockaddr *)&client, client_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
if (res != 0)
return;
strncpy(buf, host, NI_MAXHOST - 1);
}
pthread_mutex_t stream_auth_mutex;
/**
* set_sock_timeout
*
* Returns : 0 or 1 on timeout
*/
static int set_sock_timeout(int sock, int sec)
{
struct timeval tv;
tv.tv_sec = sec;
tv.tv_usec = 0;
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*) &tv, sizeof(tv))) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO
,_("set socket timeout failed"));
return 1;
}
return 0;
}
/**
* read_http_request
*
*
* Returns : 1 on success or 0 if any error happens
*/
static int read_http_request(int sock, char* buffer, int buflen, char* uri, int uri_len)
{
int nread = 0;
int ret,readb = 1;
char method[10] = {'\0'};
char url[512] = {'\0'};
char protocol[10] = {'\0'};
static const char *bad_request_response_raw =
"HTTP/1.0 400 Bad Request\r\n"
"Content-type: text/plain\r\n\r\n"
"Bad Request\n";
static const char *bad_method_response_template_raw =
"HTTP/1.0 501 Method Not Implemented\r\n"
"Content-type: text/plain\r\n\r\n"
"Method Not Implemented\n";
static const char *timeout_response_template_raw =
"HTTP/1.0 408 Request Timeout\r\n"
"Content-type: text/plain\r\n\r\n"
"Request Timeout\n";
buffer[0] = '\0';
while ((strstr(buffer, "\r\n\r\n") == NULL) && (readb != 0) && (nread < buflen)) {
readb = read(sock, buffer+nread, buflen - nread);
if (readb == -1) {
nread = -1;
break;
}
nread += readb;
if (nread > buflen) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO
,_("motion-stream End buffer reached waiting for buffer ending"));
break;
}
buffer[nread] = '\0';
}
/*
* Make sure the last read didn't fail. If it did, there's a
* problem with the connection, so give up.
*/
if (nread == -1) {
if(errno == EAGAIN) { // Timeout
ret = write(sock, timeout_response_template_raw, strlen(timeout_response_template_raw));
return 0;
}
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO
,_("motion-stream READ give up!"));
return 0;
}
ret = sscanf(buffer, "%9s %511s %9s", method, url, protocol);
if (ret != 3) {
ret = write(sock, bad_request_response_raw, sizeof(bad_request_response_raw));
return 0;
}
/* Check Protocol */
if (strcmp(protocol, "HTTP/1.0") && strcmp (protocol, "HTTP/1.1")) {
/* We don't understand this protocol. Report a bad response. */
ret = write(sock, bad_request_response_raw, sizeof(bad_request_response_raw));
return 0;
}
if (strcmp(method, "GET")) {
/*
* This server only implements the GET method. If client
* uses other method, report the failure.
*/
char response[1024];
snprintf(response, sizeof(response), bad_method_response_template_raw, method);
ret = write(sock, response, strlen (response));
return 0;
}
if(uri)
strncpy(uri, url, uri_len);
return 1;
}
static void stream_add_client(struct stream *list, int sc);
/**
* handle_basic_auth
*
*
*/
static void* handle_basic_auth(void* param)
{
struct auth_param *p = (struct auth_param*)param;
char buffer[1024] = {'\0'};
ssize_t length = 1023;
char *auth, *h, *authentication;
static const char *request_auth_response_template=
"HTTP/1.0 401 Authorization Required\r\n"
"Server: Motion/"VERSION"\r\n"
"Max-Age: 0\r\n"
"Expires: 0\r\n"
"Cache-Control: no-cache, private\r\n"
"Pragma: no-cache\r\n"
"WWW-Authenticate: Basic realm=\""STREAM_REALM"\"\r\n\r\n";
pthread_mutex_lock(&stream_auth_mutex);
p->thread_count++;
pthread_mutex_unlock(&stream_auth_mutex);
if (!read_http_request(p->sock,buffer, length, NULL, 0))
goto Invalid_Request;
auth = strstr(buffer, "Authorization: Basic");
if (!auth)
goto Error;
auth += sizeof("Authorization: Basic");
h = strstr(auth, "\r\n");
if(!h)
goto Error;
*h='\0';
if (p->conf->stream_authentication != NULL) {
char *userpass = NULL;
size_t auth_size = strlen(p->conf->stream_authentication);
authentication = mymalloc(BASE64_LENGTH(auth_size) + 1);
userpass = mymalloc(auth_size + 4);
/* motion_base64_encode can read 3 bytes after the end of the string, initialize it. */
memset(userpass, 0, auth_size + 4);
strcpy(userpass, p->conf->stream_authentication);
motion_base64_encode(userpass, authentication, auth_size);
free(userpass);
if (strcmp(auth, authentication)) {
free(authentication);
char host[NI_MAXHOST] = "unknown";
get_host(host, p->sock);
MOTION_LOG(ALR, TYPE_STREAM, NO_ERRNO
,_("motion-stream - failed auth attempt from %s"), host);
goto Error;
}
free(authentication);
}
// OK - Access
/* Set socket to non blocking */
if (fcntl(p->sock, F_SETFL, p->sock_flags) < 0) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO,_("fcntl"));
goto Error;
}
/* Lock the mutex */
pthread_mutex_lock(&stream_auth_mutex);
stream_add_client(p->stm, p->sock);
(*p->stream_count)++;
p->thread_count--;
/* Unlock the mutex */
pthread_mutex_unlock(&stream_auth_mutex);
free(p);
pthread_exit(NULL);
Error:
if (write(p->sock, request_auth_response_template, strlen (request_auth_response_template)) < 0)
MOTION_LOG(DBG, TYPE_STREAM, SHOW_ERRNO
,_("write failure 1:handle_basic_auth"));
Invalid_Request:
close(p->sock);
pthread_mutex_lock(&stream_auth_mutex);
p->thread_count--;
pthread_mutex_unlock(&stream_auth_mutex);
free(p);
pthread_exit(NULL);
}
#define HASHLEN 16
typedef char HASH[HASHLEN];
#define HASHHEXLEN 32
typedef char HASHHEX[HASHHEXLEN+1];
#define IN
#define OUT
/**
* CvtHex
* Calculates H(A1) as per HTTP Digest spec -- taken from RFC 2617.
*/
static void CvtHex(IN HASH Bin, OUT HASHHEX Hex)
{
unsigned short i;
unsigned char j;
for (i = 0; i < HASHLEN; i++) {
j = (Bin[i] >> 4) & 0xf;
if (j <= 9)
Hex[i*2] = (j + '0');
else
Hex[i*2] = (j + 'a' - 10);
j = Bin[i] & 0xf;
if (j <= 9)
Hex[i*2+1] = (j + '0');
else
Hex[i*2+1] = (j + 'a' - 10);
};
Hex[HASHHEXLEN] = '\0';
};
/**
* DigestCalcHA1
* Calculates H(A1) as per spec.
*/
static void DigestCalcHA1(
IN char * pszAlg,
IN char * pszUserName,
IN char * pszRealm,
IN char * pszPassword,
IN char * pszNonce,
IN char * pszCNonce,
OUT HASHHEX SessionKey
)
{
MD5_CTX Md5Ctx;
HASH HA1;
MD5Init(&Md5Ctx);
MD5Update(&Md5Ctx, (unsigned char *)pszUserName, strlen(pszUserName));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszRealm, strlen(pszRealm));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszPassword, strlen(pszPassword));
MD5Final((unsigned char *)HA1, &Md5Ctx);
if (strcmp(pszAlg, "md5-sess") == 0) {
MD5Init(&Md5Ctx);
MD5Update(&Md5Ctx, (unsigned char *)HA1, HASHLEN);
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszNonce, strlen(pszNonce));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszCNonce, strlen(pszCNonce));
MD5Final((unsigned char *)HA1, &Md5Ctx);
};
CvtHex(HA1, SessionKey);
};
/**
* DigestCalcResponse
* Calculates request-digest/response-digest as per HTTP Digest spec.
*/
static void DigestCalcResponse(
IN HASHHEX HA1, /* H(A1) */
IN char * pszNonce, /* nonce from server */
IN char * pszNonceCount, /* 8 hex digits */
IN char * pszCNonce, /* client nonce */
IN char * pszQop, /* qop-value: "", "auth", "auth-int" */
IN char * pszMethod, /* method from the request */
IN char * pszDigestUri, /* requested URL */
IN HASHHEX HEntity, /* H(entity body) if qop="auth-int" */
OUT HASHHEX Response /* request-digest or response-digest */
)
{
MD5_CTX Md5Ctx;
HASH HA2;
HASH RespHash;
HASHHEX HA2Hex;
// Calculate H(A2)
MD5Init(&Md5Ctx);
MD5Update(&Md5Ctx, (unsigned char *)pszMethod, strlen(pszMethod));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszDigestUri, strlen(pszDigestUri));
if (strcmp(pszQop, "auth-int") == 0) {
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)HEntity, HASHHEXLEN);
}
MD5Final((unsigned char *)HA2, &Md5Ctx);
CvtHex(HA2, HA2Hex);
// Calculate response
MD5Init(&Md5Ctx);
MD5Update(&Md5Ctx, (unsigned char *)HA1, HASHHEXLEN);
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszNonce, strlen(pszNonce));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
if (*pszQop) {
MD5Update(&Md5Ctx, (unsigned char *)pszNonceCount, strlen(pszNonceCount));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszCNonce, strlen(pszCNonce));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
MD5Update(&Md5Ctx, (unsigned char *)pszQop, strlen(pszQop));
MD5Update(&Md5Ctx, (unsigned char *)":", 1);
}
MD5Update(&Md5Ctx, (unsigned char *)HA2Hex, HASHHEXLEN);
MD5Final((unsigned char *)RespHash, &Md5Ctx);
CvtHex(RespHash, Response);
};
/**
* handle_md5_digest
*
*
*/
static void* handle_md5_digest(void* param)
{
struct auth_param *p = (struct auth_param*)param;
char buffer[1024] = {'\0'};
ssize_t length = 1023;
char *auth, *h, *username, *realm, *uri, *nonce, *response;
int username_len, realm_len, uri_len, nonce_len, response_len;
#define SERVER_NONCE_LEN 17
char server_nonce[SERVER_NONCE_LEN];
#define SERVER_URI_LEN 512
char server_uri[SERVER_URI_LEN];
char* server_user = NULL, *server_pass = NULL;
unsigned int rand1,rand2;
HASHHEX HA1;
HASHHEX HA2 = "";
HASHHEX server_response;
static const char *request_auth_response_template=
"HTTP/1.0 401 Authorization Required\r\n"
"Server: Motion/"VERSION"\r\n"
"Max-Age: 0\r\n"
"Expires: 0\r\n"
"Cache-Control: no-cache, private\r\n"
"Pragma: no-cache\r\n"
"WWW-Authenticate: Digest";
static const char *auth_failed_html_template=
"<!DOCTYPE html>\n"
"<html>\n"
"<head><title>401 Authorization Required</title></head>\n"
"<body>\n"
"<h1>Authorization Required</h1>\n"
"<p>This server could not verify that you are authorized to access the document "
"requested. Either you supplied the wrong credentials (e.g., bad password), "
"or your browser doesn't understand how to supply the credentials required.</p>\n"
"</body>\n"
"</html>\n";
static const char *internal_error_template=
"HTTP/1.0 500 Internal Server Error\r\n"
"Server: Motion/"VERSION"\r\n"
"Content-Type: text/html\r\n"
"Connection: Close\r\n\r\n"
"<!DOCTYPE html>\n"
"<html>\n"
"<head><title>500 Internal Server Error</title></head>\n"
"<body>\n"
"<h1>500 Internal Server Error</h1>\n"
"</body>\n"
"</html>\n";
pthread_mutex_lock(&stream_auth_mutex);
p->thread_count++;
pthread_mutex_unlock(&stream_auth_mutex);
set_sock_timeout(p->sock, KEEP_ALIVE_TIMEOUT);
srand(time(NULL));
rand1 = (unsigned int)(42000000.0 * rand() / (RAND_MAX + 1.0));
rand2 = (unsigned int)(42000000.0 * rand() / (RAND_MAX + 1.0));
snprintf(server_nonce, SERVER_NONCE_LEN, "%08x%08x", rand1, rand2);
if (!p->conf->stream_authentication) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO
,_("Error no authentication data"));
goto InternalError;
}
h = strstr(p->conf->stream_authentication, ":");
if (!h) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO
,_("Error no authentication data (no ':' found)"));
goto InternalError;
}
server_user = (char*)malloc((h - p->conf->stream_authentication) + 1);
server_pass = (char*)malloc(strlen(h) + 1);
if (!server_user || !server_pass) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO
,_("Error malloc failed"));
goto InternalError;
}
strncpy(server_user, p->conf->stream_authentication, h-p->conf->stream_authentication);
server_user[h - p->conf->stream_authentication] = '\0';
strncpy(server_pass, h + 1, strlen(h + 1));
server_pass[strlen(h + 1)] = '\0';
while(1) {
if(!read_http_request(p->sock, buffer, length, server_uri, SERVER_URI_LEN - 1))
goto Invalid_Request;
auth = strstr(buffer, "Authorization: Digest");
if(!auth)
goto Error;
auth += sizeof("Authorization: Digest");
h = strstr(auth, "\r\n");
if (!h)
goto Error;
*h = '\0';
// Username
h=strstr(auth, "username=\"");
if (!h)
goto Error;
username = h + 10;
h = strstr(username + 1, "\"");
if (!h)
goto Error;
username_len = h - username;
// Realm
h = strstr(auth, "realm=\"");
if (!h)
goto Error;
realm = h + 7;
h = strstr(realm + 1, "\"");
if (!h)
goto Error;
realm_len = h - realm;
// URI
h = strstr(auth, "uri=\"");
if (!h)
goto Error;
uri = h + 5;
h = strstr(uri + 1, "\"");
if (!h)
goto Error;
uri_len = h - uri;
// Nonce
h = strstr(auth, "nonce=\"");
if (!h)
goto Error;
nonce = h + 7;
h = strstr(nonce + 1, "\"");
if (!h)
goto Error;
nonce_len = h - nonce;
// Response
h = strstr(auth, "response=\"");
if (!h)
goto Error;
response = h + 10;
h = strstr(response + 1, "\"");
if (!h)
goto Error;
response_len = h - response;
username[username_len] = '\0';
realm[realm_len] = '\0';
uri[uri_len] = '\0';
nonce[nonce_len] = '\0';
response[response_len] = '\0';
DigestCalcHA1((char*)"md5", server_user, (char*)STREAM_REALM, server_pass, (char*)server_nonce, (char*)NULL, HA1);
DigestCalcResponse(HA1, server_nonce, NULL, NULL, (char*)"", (char*)"GET", server_uri, HA2, server_response);
if (strcmp(server_response, response) == 0){
break;
} else {
char host[NI_MAXHOST] = "unknown";
get_host(host, p->sock);
MOTION_LOG(ALR, TYPE_STREAM, NO_ERRNO
,_("motion-stream - failed auth attempt from %s"), host);
}
Error:
rand1 = (unsigned int)(42000000.0 * rand() / (RAND_MAX + 1.0));
rand2 = (unsigned int)(42000000.0 * rand() / (RAND_MAX + 1.0));
snprintf(server_nonce, SERVER_NONCE_LEN, "%08x%08x", rand1, rand2);
snprintf(buffer, length, "%s realm=\""STREAM_REALM"\", nonce=\"%s\"\r\n"
"Content-Type: text/html\r\n"
"Keep-Alive: timeout=%i\r\n"
"Connection: keep-alive\r\n"
"Content-Length: %zu\r\n\r\n",
request_auth_response_template, server_nonce,
KEEP_ALIVE_TIMEOUT, strlen(auth_failed_html_template));
if (write(p->sock, buffer, strlen(buffer)) < 0)
MOTION_LOG(DBG, TYPE_STREAM, SHOW_ERRNO
,_("write failure 1:handle_md5_digest"));
if (write(p->sock, auth_failed_html_template, strlen(auth_failed_html_template)) < 0)
MOTION_LOG(DBG, TYPE_STREAM, SHOW_ERRNO
,_("write failure 2:handle_md5_digest"));
}
// OK - Access
/* Set socket to non blocking */
if (fcntl(p->sock, F_SETFL, p->sock_flags) < 0) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO,_("fcntl"));
goto Error;
}
free(server_user);
free(server_pass);
/* Lock the mutex */
pthread_mutex_lock(&stream_auth_mutex);
stream_add_client(p->stm, p->sock);
(*p->stream_count)++;
p->thread_count--;
/* Unlock the mutex */
pthread_mutex_unlock(&stream_auth_mutex);
free(p);
pthread_exit(NULL);
InternalError:
free(server_user);
free(server_pass);
if (write(p->sock, internal_error_template, strlen(internal_error_template)) < 0)
MOTION_LOG(DBG, TYPE_STREAM, SHOW_ERRNO
,_("write failure 3:handle_md5_digest"));
Invalid_Request:
close(p->sock);
pthread_mutex_lock(&stream_auth_mutex);
p->thread_count--;
pthread_mutex_unlock(&stream_auth_mutex);
free(p);
pthread_exit(NULL);
}
/**
* do_client_auth
*
*
*/
static void do_client_auth(struct context *cnt, struct stream *stm, int *stream_count, int sc)
{
pthread_t thread_id;
pthread_attr_t attr;
auth_handler handle_func;
struct auth_param* handle_param = NULL;
int flags;
static int first_call = 0;
static int thread_count = 0;
if(first_call == 0) {
first_call = 1;
/* Initialize the mutex */
pthread_mutex_init(&stream_auth_mutex, NULL);
}
switch(cnt->conf.stream_auth_method)
{
case 1: // Basic
handle_func = handle_basic_auth;
break;
case 2: // MD5 Digest
handle_func = handle_md5_digest;
break;
default:
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO
,_("Error unknown stream authentication method"));
goto Error;
break;
}
handle_param = mymalloc(sizeof(struct auth_param));
handle_param->cnt = cnt;
handle_param->stm = stm;
handle_param->stream_count = stream_count;
handle_param->sock = sc;
handle_param->conf = &cnt->conf;
handle_param->thread_count = &thread_count;
/* Set socket to blocking */
if ((flags = fcntl(sc, F_GETFL, 0)) < 0) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO, _("fcntl"));
goto Error;
}
handle_param->sock_flags = flags;
if (fcntl(sc, F_SETFL, flags & (~O_NONBLOCK)) < 0) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO, _("fcntl"));
goto Error;
}
if (thread_count >= DEF_MAXSTREAMS)
goto Error;
if (pthread_attr_init(&attr)) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO,_("Error pthread_attr_init"));
goto Error;
}
if (pthread_create(&thread_id, &attr, handle_func, handle_param)) {
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO,_("Error pthread_create"));
goto Error;
}
pthread_detach(thread_id);
if (pthread_attr_destroy(&attr))
MOTION_LOG(ERR, TYPE_STREAM, SHOW_ERRNO,_("Error pthread_attr_destroy"));
return;
Error:
close(sc);
free(handle_param);
}
/**
* http_bindsock
* Sets up a TCP/IP socket for incoming requests. It is called only during
* initialisation of Motion from the function stream_init
* The function sets up a a socket on the port number given by _port_.
* If the parameter _local_ is not zero the socket is setup to only accept connects from localhost.
* Otherwise any client IP address is accepted. The function returns an integer representing the socket.
*
* Returns: socket descriptor or -1 if any error happens
*/
int http_bindsock(int port, int local, int ipv6_enabled)
{
int sd = socket(ipv6_enabled?AF_INET6:AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sd == -1)
{
MOTION_LOG(CRT, TYPE_STREAM, SHOW_ERRNO,_("error creating socket"));
return -1;
}
int yes = 1, no = 0;
if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) != 0)
{
MOTION_LOG(CRT, TYPE_STREAM, SHOW_ERRNO
,_("setting SO_REUSEADDR to yes failed"));
/* we can carry on even if this failed */
}
if (ipv6_enabled)
{
if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no)) != 0)
{
MOTION_LOG(CRT, TYPE_STREAM, SHOW_ERRNO
,_("setting IPV6_V6ONLY to no failed"));
/* we can carry on even if this failed */
}
}
const char *addr_str;
struct sockaddr_storage sin;
socklen_t sinsize;
bzero(&sin, sizeof(struct sockaddr_storage));
sin.ss_family = ipv6_enabled?AF_INET6:AF_INET;
if (ipv6_enabled) {
struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&sin;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = htons(port);
if(local) {
addr_str = "::1";
sin6->sin6_addr = in6addr_loopback;
} else {
addr_str = "any IPv4/IPv6 address";
sin6->sin6_addr = in6addr_any;
}
sinsize = sizeof(*sin6);
} else {
struct sockaddr_in *sin4 = (struct sockaddr_in*)&sin;
sin4->sin_family = AF_INET;
sin4->sin_port = htons(port);
if(local) {
addr_str = "127.0.0.1";
sin4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
} else {
addr_str = "any IPv4 address";
sin4->sin_addr.s_addr = htonl(INADDR_ANY);
}
sinsize = sizeof(*sin4);
}
if (bind(sd, (struct sockaddr*)&sin, sinsize) != 0) {
MOTION_LOG(CRT, TYPE_STREAM, SHOW_ERRNO
,_("error binding on %s port %d"), addr_str, port);
close(sd);
return -1;
}
if (listen(sd, DEF_MAXWEBQUEUE) != 0) {
MOTION_LOG(CRT, TYPE_STREAM, SHOW_ERRNO,_("error listening"));
close(sd);
return -1;
}
MOTION_LOG(NTC, TYPE_STREAM, NO_ERRNO
,_("listening on %s port %d"), addr_str, port);
return sd;
}
/**
* http_acceptsock
*
*
* Returns: socket descriptor or -1 if any error happens.
*/
static int http_acceptsock(int sl)
{
int sc;
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
sc = accept(sl, (struct sockaddr*)&addr, &addr_len);
if (sc < 0) {
MOTION_LOG(CRT, TYPE_STREAM, SHOW_ERRNO,_("motion-stream accept()"));
return -1;
}
unsigned long i = 1;
ioctl(sc, FIONBIO, &i);
return sc;
}
/**
* stream_flush
* Sends any outstanding data to all connected clients.
* It continuously goes through the client list until no data is able
* to be sent (either because there isn't any, or because the clients
* are not able to accept it).
*/
static void stream_flush(struct stream *list, int *stream_count, int lim)
{
int written; /* The number of bytes actually written. */
struct stream *client; /* Pointer to the client being served. */
int workdone = 0; /* Flag set any time data is successfully
written. */
client = list->next;
while (client) {
/* If data waiting for client, try to send it. */
if (client->tmpbuffer) {
/*
* We expect that list->filepos < list->tmpbuffer->size
* should always be true. The check is more for safety,
* in case of trouble is some other part of the code.
* Note that if it is false, the following section will
* clean up.
*/
if (client->filepos < client->tmpbuffer->size) {
/*
* Here we are finally ready to write out the
* data. Remember that (because the socket
* has been set non-blocking) we may only
* write out part of the buffer. The var
* 'filepos' contains how much of the buffer
* has already been written.
*/
written = write(client->socket,
client->tmpbuffer->ptr + client->filepos,
client->tmpbuffer->size - client->filepos);
/*
* If any data has been written, update the
* data pointer and set the workdone flag.
*/
if (written > 0) {
client->filepos += written;
workdone = 1;
}
} else
written = 0;
/*
* If we have written the entire buffer to the socket,
* or if there was some error (other than EAGAIN, which
* means the system couldn't take it), this request is
* finished.
*/
if ((client->filepos >= client->tmpbuffer->size) ||
(written < 0 && errno != EAGAIN)) {
/* If no other clients need this buffer, free it. */
if (--client->tmpbuffer->ref <= 0) {
free(client->tmpbuffer->ptr);
free(client->tmpbuffer);
if (client->cors_header != NULL) free(client->cors_header);
}
/* Mark this client's buffer as empty. */
client->tmpbuffer = NULL;
client->nr++;
}
/*
* If the client is no longer connected, or the total
* number of frames already sent to this client is
* greater than our configuration limit, disconnect
* the client and free the stream struct.
*/
if ((written < 0 && errno != EAGAIN) ||
(lim && !client->tmpbuffer && client->nr > lim)) {
void *tmp;
close(client->socket);
if (client->next)
client->next->prev = client->prev;
client->prev->next = client->next;
tmp = client;
client = client->prev;
free(tmp);
(*stream_count)--;
}
} /* End if (client->tmpbuffer) */
/*
* Step the the next client in the list. If we get to the
* end of the list, check if anything was written during
* that loop; (if so) reset the 'workdone' flag and go back
* to the beginning.
*/
client = client->next;
if (!client && workdone) {
client = list->next;
workdone = 0;
}
} /* End while (client) */
}
/**
* stream_tmpbuffer
* Routine to create a new "tmpbuffer", which is a common
* object used by all clients connected to a single camera.
*
* Returns: new allocated stream_buffer.
*/
static struct stream_buffer *stream_tmpbuffer(int size)
{
struct stream_buffer *tmpbuffer = mymalloc(sizeof(struct stream_buffer));
tmpbuffer->ref = 0;
tmpbuffer->ptr = mymalloc(size);
return tmpbuffer;
}
const char *base_header = "HTTP/1.0 200 OK\r\n"
"Server: Motion/"VERSION"\r\n"
"Connection: close\r\n"
"Max-Age: 0\r\n"
"Expires: 0\r\n"
"Cache-Control: no-cache, private\r\n"
"Pragma: no-cache\r\n"
"Content-Type: multipart/x-mixed-replace; "
"boundary=BoundaryString\r\n\r\n";
#define BASE_HEADER_LEN strlen(base_header)
/**
* stream_add_client
*
*
*/