~ubuntu-branches/ubuntu/trusty/rtmpdump/trusty

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
/*  HTTP-RTMP Stream Gateway
 *  Copyright (C) 2009 Andrej Stepanchuk
 *  Copyright (C) 2009-2010 Howard Chu
 *
 *  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, 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 RTMPDump; see the file COPYING.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA  02110-1301, USA.
 *  http://www.gnu.org/copyleft/gpl.html
 *
 */

#include <stdlib.h>
#include <string.h>
#include <math.h>

#include <signal.h>
#include <getopt.h>

#include <assert.h>

#include "librtmp/rtmp_sys.h"
#include "librtmp/log.h"

#include "thread.h"

#define RD_SUCCESS		0
#define RD_FAILED		1
#define RD_INCOMPLETE		2

#define PACKET_SIZE 1024*1024

#ifdef WIN32
#define InitSockets()	{\
        WORD version;			\
        WSADATA wsaData;		\
					\
        version = MAKEWORD(1,1);	\
        WSAStartup(version, &wsaData);	}

#define	CleanupSockets()	WSACleanup()
#else
#define InitSockets()
#define	CleanupSockets()
#endif

enum
{
  STREAMING_ACCEPTING,
  STREAMING_IN_PROGRESS,
  STREAMING_STOPPING,
  STREAMING_STOPPED
};

typedef struct
{
  int socket;
  int state;

} STREAMING_SERVER;

STREAMING_SERVER *httpServer = 0;	// server structure pointer

STREAMING_SERVER *startStreaming(const char *address, int port);
void stopStreaming(STREAMING_SERVER * server);

typedef struct
{
  AVal hostname;
  int rtmpport;
  int protocol;
  int bLiveStream;		// is it a live stream? then we can't seek/resume

  long int timeout;		// timeout connection after 120 seconds
  uint32_t bufferTime;

  char *rtmpurl;
  AVal playpath;
  AVal swfUrl;
  AVal tcUrl;
  AVal pageUrl;
  AVal app;
  AVal auth;
  AVal swfHash;
  AVal flashVer;
  AVal token;
  AVal subscribepath;
  AVal usherToken; //Justin.tv auth token
  AVal sockshost;
  AMFObject extras;
  int edepth;
  uint32_t swfSize;
  int swfAge;
  int swfVfy;

  uint32_t dStartOffset;
  uint32_t dStopOffset;

#ifdef CRYPTO
  unsigned char hash[RTMP_SWF_HASHLEN];
#endif
} RTMP_REQUEST;

#define STR2AVAL(av,str)	av.av_val = str; av.av_len = strlen(av.av_val)

int
parseAMF(AMFObject *obj, const char *arg, int *depth)
{
  AMFObjectProperty prop = {{0,0}};
  int i;
  char *p;

  if (arg[1] == ':')
    {
      p = (char *)arg+2;
      switch(arg[0])
        {
        case 'B':
          prop.p_type = AMF_BOOLEAN;
          prop.p_vu.p_number = atoi(p);
          break;
        case 'S':
          prop.p_type = AMF_STRING;
          STR2AVAL(prop.p_vu.p_aval,p);
          break;
        case 'N':
          prop.p_type = AMF_NUMBER;
          prop.p_vu.p_number = strtod(p, NULL);
          break;
        case 'Z':
          prop.p_type = AMF_NULL;
          break;
        case 'O':
          i = atoi(p);
          if (i)
            {
              prop.p_type = AMF_OBJECT;
            }
          else
            {
              (*depth)--;
              return 0;
            }
          break;
        default:
          return -1;
        }
    }
  else if (arg[2] == ':' && arg[0] == 'N')
    {
      p = strchr(arg+3, ':');
      if (!p || !*depth)
        return -1;
      prop.p_name.av_val = (char *)arg+3;
      prop.p_name.av_len = p - (arg+3);

      p++;
      switch(arg[1])
        {
        case 'B':
          prop.p_type = AMF_BOOLEAN;
          prop.p_vu.p_number = atoi(p);
          break;
        case 'S':
          prop.p_type = AMF_STRING;
          STR2AVAL(prop.p_vu.p_aval,p);
          break;
        case 'N':
          prop.p_type = AMF_NUMBER;
          prop.p_vu.p_number = strtod(p, NULL);
          break;
        case 'O':
          prop.p_type = AMF_OBJECT;
          break;
        default:
          return -1;
        }
    }
  else
    return -1;

  if (*depth)
    {
      AMFObject *o2;
      for (i=0; i<*depth; i++)
        {
          o2 = &obj->o_props[obj->o_num-1].p_vu.p_object;
          obj = o2;
        }
    }
  AMF_AddProp(obj, &prop);
  if (prop.p_type == AMF_OBJECT)
    (*depth)++;
  return 0;
}

/* this request is formed from the parameters and used to initialize a new request,
 * thus it is a default settings list. All settings can be overriden by specifying the
 * parameters in the GET request. */
RTMP_REQUEST defaultRTMPRequest;

int ParseOption(char opt, char *arg, RTMP_REQUEST * req);

#ifdef _DEBUG
uint32_t debugTS = 0;

int pnum = 0;

FILE *netstackdump = NULL;
FILE *netstackdump_read = NULL;
#endif

/* inplace http unescape. This is possible .. strlen(unescaped_string)  <= strlen(esacped_string) */
void
http_unescape(char *data)
{
  char hex[3];
  char *stp;
  int src_x = 0;
  int dst_x = 0;

  int length = (int) strlen(data);
  hex[2] = 0;

  while (src_x < length)
    {
      if (strncmp(data + src_x, "%", 1) == 0 && src_x + 2 < length)
	{
	  //
	  // Since we encountered a '%' we know this is an escaped character
	  //
	  hex[0] = data[src_x + 1];
	  hex[1] = data[src_x + 2];
	  data[dst_x] = (char) strtol(hex, &stp, 16);
	  dst_x += 1;
	  src_x += 3;
	}
      else if (src_x != dst_x)
	{
	  //
	  // This doesn't need to be unescaped. If we didn't unescape anything previously
	  // there is no need to copy the string either
	  //
	  data[dst_x] = data[src_x];
	  src_x += 1;
	  dst_x += 1;
	}
      else
	{
	  //
	  // This doesn't need to be unescaped, however we need to copy the string
	  //
	  src_x += 1;
	  dst_x += 1;
	}
    }
  data[dst_x] = '\0';
}

TFTYPE
controlServerThread(void *unused)
{
  char ich;
  while (1)
    {
      ich = getchar();
      switch (ich)
	{
	case 'q':
	  RTMP_LogPrintf("Exiting\n");
	  stopStreaming(httpServer);
	  exit(0);
	  break;
	default:
	  RTMP_LogPrintf("Unknown command \'%c\', ignoring\n", ich);
	}
    }
  TFRET();
}

/*
ssize_t readHTTPLine(int sockfd, char *buffer, size_t length)
{
	size_t i=0;

	while(i < length-1) {
		char c;
		int n = read(sockfd, &c, 1);

		if(n == 0)
			break;

		buffer[i] = c;
		i++;

		if(c == '\n')
			break;
	}
	buffer[i]='\0';
	i++;

	return i;
}

int isHTTPRequestEOF(char *line, size_t length)
{
	if(length < 2)
		return TRUE;

	if(line[0]=='\r' && line[1]=='\n')
		return TRUE;

	return FALSE;
}
*/

void processTCPrequest(STREAMING_SERVER * server,	// server socket and state (our listening socket)
		       int sockfd	// client connection socket
  )
{
  char buf[512] = { 0 };	// answer buffer
  char header[2048] = { 0 };	// request header
  char *filename = NULL;	// GET request: file name //512 not enuf
  char *buffer = NULL;		// stream buffer
  char *ptr = NULL;		// header pointer
  int len;

  size_t nRead = 0;

  char srvhead[] = "\r\nServer: HTTP-RTMP Stream Server " RTMPDUMP_VERSION "\r\n";

  char *status = "404 Not Found";

  server->state = STREAMING_IN_PROGRESS;

  RTMP rtmp = { 0 };
  uint32_t dSeek = 0;		// can be used to start from a later point in the stream

  // reset RTMP options to defaults specified upon invokation of streams
  RTMP_REQUEST req;
  memcpy(&req, &defaultRTMPRequest, sizeof(RTMP_REQUEST));

  // timeout for http requests
  fd_set fds;
  struct timeval tv;

  memset(&tv, 0, sizeof(struct timeval));
  tv.tv_sec = 5;

  // go through request lines
  //do {
  FD_ZERO(&fds);
  FD_SET(sockfd, &fds);

  if (select(sockfd + 1, &fds, NULL, NULL, &tv) <= 0)
    {
      RTMP_Log(RTMP_LOGERROR, "Request timeout/select failed, ignoring request");
      goto quit;
    }
  else
    {
      nRead = recv(sockfd, header, 2047, 0);
      header[2047] = '\0';

      RTMP_Log(RTMP_LOGDEBUG, "%s: header: %s", __FUNCTION__, header);

      if (strstr(header, "Range: bytes=") != 0)
	{
	  // TODO check range starts from 0 and asking till the end.
	  RTMP_LogPrintf("%s, Range request not supported\n", __FUNCTION__);
	  len = sprintf(buf, "HTTP/1.0 416 Requested Range Not Satisfiable%s\r\n",
		  srvhead);
	  send(sockfd, buf, len, 0);
	  goto quit;
	}

      if (strncmp(header, "GET", 3) == 0 && nRead > 4)
	{
	  filename = header + 4;

	  // filter " HTTP/..." from end of request
	  char *p = filename;
	  while (*p != '\0')
	    {
	      if (*p == ' ')
		{
		  *p = '\0';
		  break;
		}
	      p++;
	    }
	}
    }
  //} while(!isHTTPRequestEOF(header, nRead));

  // if we got a filename from the GET method
  if (filename != NULL)
    {
      RTMP_Log(RTMP_LOGDEBUG, "%s: Request header: %s", __FUNCTION__, filename);
      if (filename[0] == '/')
	{			// if its not empty, is it /?
	  ptr = filename + 1;

	  // parse parameters
	  if (*ptr == '?')
	    {
	      ptr++;
	      int len = strlen(ptr);

	      while (len >= 2)
		{
		  char ich = *ptr;
		  ptr++;
		  if (*ptr != '=')
		    goto filenotfound;	// long parameters not (yet) supported

		  ptr++;
		  len -= 2;

		  // get position of the next '&'
		  char *temp;

		  unsigned int nArgLen = len;
		  if ((temp = strstr(ptr, "&")) != 0)
		    {
		      nArgLen = temp - ptr;
		    }

		  char *arg = (char *) malloc((nArgLen + 1) * sizeof(char));
		  memcpy(arg, ptr, nArgLen * sizeof(char));
		  arg[nArgLen] = '\0';

		  //RTMP_Log(RTMP_LOGDEBUG, "%s: unescaping parameter: %s", __FUNCTION__, arg);
		  http_unescape(arg);

		  RTMP_Log(RTMP_LOGDEBUG, "%s: parameter: %c, arg: %s", __FUNCTION__,
		      ich, arg);

		  ptr += nArgLen + 1;
		  len -= nArgLen + 1;

		  if (!ParseOption(ich, arg, &req))
		    {
		      status = "400 unknown option";
		      goto filenotfound;
		    }
		}
	    }
	}
      else
	{
	  goto filenotfound;
	}
    }
  else
    {
      RTMP_LogPrintf("%s: No request header received/unsupported method\n",
		__FUNCTION__);
    }

  // do necessary checks right here to make sure the combined request of default values and GET parameters is correct
  if (!req.hostname.av_len)
    {
      RTMP_Log(RTMP_LOGERROR,
	  "You must specify a hostname (--host) or url (-r \"rtmp://host[:port]/playpath\") containing a hostname");
      status = "400 Missing Hostname";
      goto filenotfound;
    }
  if (req.playpath.av_len == 0)
    {
      RTMP_Log(RTMP_LOGERROR,
	  "You must specify a playpath (--playpath) or url (-r \"rtmp://host[:port]/playpath\") containing a playpath");
      status = "400 Missing Playpath";
      goto filenotfound;;
    }

  if (req.protocol == RTMP_PROTOCOL_UNDEFINED)
    {
      RTMP_Log(RTMP_LOGWARNING,
	  "You haven't specified a protocol (--protocol) or rtmp url (-r), using default protocol RTMP");
      req.protocol = RTMP_PROTOCOL_RTMP;
    }
  if (req.rtmpport == -1)
    {
      RTMP_Log(RTMP_LOGWARNING,
	  "You haven't specified a port (--port) or rtmp url (-r), using default port");
      req.rtmpport = 0;
    }
  if (req.rtmpport == 0)
    {
      if (req.protocol & RTMP_FEATURE_SSL)
	req.rtmpport = 443;
      else if (req.protocol & RTMP_FEATURE_HTTP)
	req.rtmpport = 80;
      else
	req.rtmpport = 1935;
    }

  if (req.tcUrl.av_len == 0)
    {
      char str[512] = { 0 };
      req.tcUrl.av_len = snprintf(str, 511, "%s://%.*s:%d/%.*s",
	RTMPProtocolStringsLower[req.protocol], req.hostname.av_len,
	req.hostname.av_val, req.rtmpport, req.app.av_len, req.app.av_val);
      req.tcUrl.av_val = (char *) malloc(req.tcUrl.av_len + 1);
      strcpy(req.tcUrl.av_val, str);
    }

  if (req.swfVfy)
    {
#ifdef CRYPTO
        if (RTMP_HashSWF(req.swfUrl.av_val, &req.swfSize, req.hash, req.swfAge) == 0)
          {
            req.swfHash.av_val = (char *)req.hash;
            req.swfHash.av_len = RTMP_SWF_HASHLEN;
          }
#endif
    }

  // after validation of the http request send response header
  len = sprintf(buf, "HTTP/1.0 200 OK%sContent-Type: video/flv\r\n\r\n", srvhead);
  send(sockfd, buf, len, 0);

  // send the packets
  buffer = (char *) calloc(PACKET_SIZE, 1);

  // User defined seek offset
  if (req.dStartOffset > 0)
    {
      if (req.bLiveStream)
	RTMP_Log(RTMP_LOGWARNING,
	    "Can't seek in a live stream, ignoring --seek option");
      else
	dSeek += req.dStartOffset;
    }

  if (dSeek != 0)
    {
      RTMP_LogPrintf("Starting at TS: %d ms\n", dSeek);
    }

  RTMP_Log(RTMP_LOGDEBUG, "Setting buffer time to: %dms", req.bufferTime);
  RTMP_Init(&rtmp);
  RTMP_SetBufferMS(&rtmp, req.bufferTime);
  RTMP_SetupStream(&rtmp, req.protocol, &req.hostname, req.rtmpport, &req.sockshost,
		   &req.playpath, &req.tcUrl, &req.swfUrl, &req.pageUrl, &req.app, &req.auth, &req.swfHash, req.swfSize, &req.flashVer, &req.subscribepath, &req.usherToken, dSeek, req.dStopOffset,
		   req.bLiveStream, req.timeout);
  /* backward compatibility, we always sent this as true before */
  if (req.auth.av_len)
    rtmp.Link.lFlags |= RTMP_LF_AUTH;

  rtmp.Link.extras = req.extras;
  rtmp.Link.token = req.token;
  rtmp.m_read.timestamp = dSeek;

  RTMP_LogPrintf("Connecting ... port: %d, app: %s\n", req.rtmpport, req.app.av_val);
  if (!RTMP_Connect(&rtmp, NULL))
    {
      RTMP_LogPrintf("%s, failed to connect!\n", __FUNCTION__);
    }
  else
    {
      unsigned long size = 0;
      double percent = 0;
      double duration = 0.0;

      int nWritten = 0;
      int nRead = 0;

      do
	{
	  nRead = RTMP_Read(&rtmp, buffer, PACKET_SIZE);

	  if (nRead > 0)
	    {
	      if ((nWritten = send(sockfd, buffer, nRead, 0)) < 0)
		{
		  RTMP_Log(RTMP_LOGERROR, "%s, sending failed, error: %d", __FUNCTION__,
		      GetSockError());
		  goto cleanup;	// we are in STREAMING_IN_PROGRESS, so we'll go to STREAMING_ACCEPTING
		}

	      size += nRead;

	      //RTMP_LogPrintf("write %dbytes (%.1f KB)\n", nRead, nRead/1024.0);
	      if (duration <= 0)	// if duration unknown try to get it from the stream (onMetaData)
		duration = RTMP_GetDuration(&rtmp);

	      if (duration > 0)
		{
		  percent =
		    ((double) (dSeek + rtmp.m_read.timestamp)) / (duration *
							   1000.0) * 100.0;
		  percent = ((double) (int) (percent * 10.0)) / 10.0;
		  RTMP_LogStatus("\r%.3f KB / %.2f sec (%.1f%%)",
			    (double) size / 1024.0,
			    (double) (rtmp.m_read.timestamp) / 1000.0, percent);
		}
	      else
		{
		  RTMP_LogStatus("\r%.3f KB / %.2f sec", (double) size / 1024.0,
			    (double) (rtmp.m_read.timestamp) / 1000.0);
		}
	    }
#ifdef _DEBUG
	  else
	    {
	      RTMP_Log(RTMP_LOGDEBUG, "zero read!");
	    }
#endif
	}
      while (server->state == STREAMING_IN_PROGRESS && nRead > -1
	     && RTMP_IsConnected(&rtmp) && nWritten >= 0);
    }
cleanup:
  RTMP_LogPrintf("Closing connection... ");
  RTMP_Close(&rtmp);
  RTMP_LogPrintf("done!\n\n");

quit:
  if (buffer)
    {
      free(buffer);
      buffer = NULL;
    }

  if (sockfd)
    closesocket(sockfd);

  if (server->state == STREAMING_IN_PROGRESS)
    server->state = STREAMING_ACCEPTING;

  return;

filenotfound:
  RTMP_LogPrintf("%s, %s, %s\n", __FUNCTION__, status, filename);
  len = sprintf(buf, "HTTP/1.0 %s%s\r\n", status, srvhead);
  send(sockfd, buf, len, 0);
  goto quit;
}

TFTYPE
serverThread(void *arg)
{
  STREAMING_SERVER *server = arg;
  server->state = STREAMING_ACCEPTING;

  while (server->state == STREAMING_ACCEPTING)
    {
      struct sockaddr_in addr;
      socklen_t addrlen = sizeof(struct sockaddr_in);
      int sockfd =
	accept(server->socket, (struct sockaddr *) &addr, &addrlen);

      if (sockfd > 0)
	{
	  // Create a new process and transfer the control to that
	  RTMP_Log(RTMP_LOGDEBUG, "%s: accepted connection from %s\n", __FUNCTION__,
	      inet_ntoa(addr.sin_addr));
	  processTCPrequest(server, sockfd);
	  RTMP_Log(RTMP_LOGDEBUG, "%s: processed request\n", __FUNCTION__);
	}
      else
	{
	  RTMP_Log(RTMP_LOGERROR, "%s: accept failed", __FUNCTION__);
	}
    }
  server->state = STREAMING_STOPPED;
  TFRET();
}

STREAMING_SERVER *
startStreaming(const char *address, int port)
{
  struct sockaddr_in addr;
  int sockfd;
  STREAMING_SERVER *server;

  sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sockfd == -1)
    {
      RTMP_Log(RTMP_LOGERROR, "%s, couldn't create socket", __FUNCTION__);
      return 0;
    }

  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = inet_addr(address);	//htonl(INADDR_ANY);
  addr.sin_port = htons(port);

  if (bind(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) ==
      -1)
    {
      RTMP_Log(RTMP_LOGERROR, "%s, TCP bind failed for port number: %d", __FUNCTION__,
	  port);
      return 0;
    }

  if (listen(sockfd, 10) == -1)
    {
      RTMP_Log(RTMP_LOGERROR, "%s, listen failed", __FUNCTION__);
      closesocket(sockfd);
      return 0;
    }

  server = (STREAMING_SERVER *) calloc(1, sizeof(STREAMING_SERVER));
  server->socket = sockfd;

  ThreadCreate(serverThread, server);

  return server;
}

void
stopStreaming(STREAMING_SERVER * server)
{
  assert(server);

  if (server->state != STREAMING_STOPPED)
    {
      if (server->state == STREAMING_IN_PROGRESS)
	{
	  server->state = STREAMING_STOPPING;

	  // wait for streaming threads to exit
	  while (server->state != STREAMING_STOPPED)
	    msleep(1);
	}

      if (closesocket(server->socket))
	RTMP_Log(RTMP_LOGERROR, "%s: Failed to close listening socket, error %d",
	    __FUNCTION__, GetSockError());

      server->state = STREAMING_STOPPED;
    }
}


void
sigIntHandler(int sig)
{
  RTMP_ctrlC = TRUE;
  RTMP_LogPrintf("Caught signal: %d, cleaning up, just a second...\n", sig);
  if (httpServer)
    stopStreaming(httpServer);
  signal(SIGINT, SIG_DFL);
}

#define HEX2BIN(a)      (((a)&0x40)?((a)&0xf)+9:((a)&0xf))
int hex2bin(char *str, char **hex)
{
  char *ptr;
  int i, l = strlen(str);

  if (l & 1)
  	return 0;

  *hex = malloc(l/2);
  ptr = *hex;
  if (!ptr)
    return 0;

  for (i=0; i<l; i+=2)
    *ptr++ = (HEX2BIN(str[i]) << 4) | HEX2BIN(str[i+1]);
  return l/2;
}

// this will parse RTMP related options as needed
// excludes the following options: h, d, g

// Return values: true (option parsing ok)
//                false (option not parsed/invalid)
int
ParseOption(char opt, char *arg, RTMP_REQUEST * req)
{
  switch (opt)
    {
#ifdef CRYPTO
    case 'w':
      {
	int res = hex2bin(arg, &req->swfHash.av_val);
	if (!res || res != RTMP_SWF_HASHLEN)
	  {
	    req->swfHash.av_val = NULL;
	    RTMP_Log(RTMP_LOGWARNING,
		"Couldn't parse swf hash hex string, not hexstring or not %d bytes, ignoring!", RTMP_SWF_HASHLEN);
	  }
	req->swfHash.av_len = RTMP_SWF_HASHLEN;
	break;
      }
    case 'x':
      {
	int size = atoi(arg);
	if (size <= 0)
	  {
	    RTMP_Log(RTMP_LOGERROR, "SWF Size must be at least 1, ignoring\n");
	  }
	else
	  {
	    req->swfSize = size;
	  }
	break;
      }
    case 'W':
      {
        STR2AVAL(req->swfUrl, arg);
        req->swfVfy = 1;
      }
      break;
    case 'X':
      {
	int num = atoi(arg);
	if (num < 0)
	  {
	    RTMP_Log(RTMP_LOGERROR, "SWF Age must be non-negative, ignoring\n");
	  }
	else
	  {
	    req->swfAge = num;
	  }
	break;
      }
#endif
    case 'b':
      {
	int32_t bt = atol(arg);
	if (bt < 0)
	  {
	    RTMP_Log(RTMP_LOGERROR,
		"Buffer time must be greater than zero, ignoring the specified value %d!",
		bt);
	  }
	else
	  {
	    req->bufferTime = bt;
	  }
	break;
      }
    case 'v':
      req->bLiveStream = TRUE;	// no seeking or resuming possible!
      break;
    case 'd':
      STR2AVAL(req->subscribepath, arg);
      break;
    case 'n':
      STR2AVAL(req->hostname, arg);
      break;
    case 'c':
      req->rtmpport = atoi(arg);
      break;
    case 'l':
      {
	int protocol = atoi(arg);
	if (protocol < RTMP_PROTOCOL_RTMP || protocol > RTMP_PROTOCOL_RTMPTS)
	  {
	    RTMP_Log(RTMP_LOGERROR, "Unknown protocol specified: %d, using default",
		protocol);
	    return FALSE;
	  }
	else
	  {
	    req->protocol = protocol;
	  }
	break;
      }
    case 'y':
      STR2AVAL(req->playpath, arg);
      break;
    case 'r':
      {
	req->rtmpurl = arg;

	AVal parsedHost, parsedPlaypath, parsedApp;
	unsigned int parsedPort = 0;
	int parsedProtocol = RTMP_PROTOCOL_UNDEFINED;

	if (!RTMP_ParseURL
	    (req->rtmpurl, &parsedProtocol, &parsedHost, &parsedPort,
	     &parsedPlaypath, &parsedApp))
	  {
	    RTMP_Log(RTMP_LOGWARNING, "Couldn't parse the specified url (%s)!", arg);
	  }
	else
	  {
	    if (!req->hostname.av_len)
	      req->hostname = parsedHost;
	    if (req->rtmpport == -1)
	      req->rtmpport = parsedPort;
	    if (req->playpath.av_len == 0 && parsedPlaypath.av_len)
	      {
		    req->playpath = parsedPlaypath;
	      }
	    if (req->protocol == RTMP_PROTOCOL_UNDEFINED)
	      req->protocol = parsedProtocol;
	    if (req->app.av_len == 0 && parsedApp.av_len)
	      {
		    req->app = parsedApp;
	      }
	  }
	break;
      }
    case 's':
      STR2AVAL(req->swfUrl, arg);
      break;
    case 't':
      STR2AVAL(req->tcUrl, arg);
      break;
    case 'p':
      STR2AVAL(req->pageUrl, arg);
      break;
    case 'a':
      STR2AVAL(req->app, arg);
      break;
    case 'f':
      STR2AVAL(req->flashVer, arg);
      break;
    case 'u':
      STR2AVAL(req->auth, arg);
      break;
    case 'C':
      parseAMF(&req->extras, optarg, &req->edepth);
      break;
    case 'm':
      req->timeout = atoi(arg);
      break;
    case 'A':
      req->dStartOffset = (int)(atof(arg) * 1000.0);
      //printf("dStartOffset = %d\n", dStartOffset);
      break;
    case 'B':
      req->dStopOffset = (int)(atof(arg) * 1000.0);
      //printf("dStartOffset = %d\n", dStartOffset);
      break;
    case 'T':
      STR2AVAL(req->token, arg);
      break;
    case 'S':
      STR2AVAL(req->sockshost, arg);
    case 'q':
      RTMP_debuglevel = RTMP_LOGCRIT;
      break;
    case 'V':
      RTMP_debuglevel = RTMP_LOGDEBUG;
      break;
    case 'z':
      RTMP_debuglevel = RTMP_LOGALL;
      break;
    case 'j':
      STR2AVAL(req->usherToken, arg);
      break;
    default:
      RTMP_LogPrintf("unknown option: %c, arg: %s\n", opt, arg);
      return FALSE;
    }
  return TRUE;
}

int
main(int argc, char **argv)
{
  int nStatus = RD_SUCCESS;

  // http streaming server
  char DEFAULT_HTTP_STREAMING_DEVICE[] = "0.0.0.0";	// 0.0.0.0 is any device

  char *httpStreamingDevice = DEFAULT_HTTP_STREAMING_DEVICE;	// streaming device, default 0.0.0.0
  int nHttpStreamingPort = 80;	// port

  RTMP_LogPrintf("HTTP-RTMP Stream Gateway %s\n", RTMPDUMP_VERSION);
  RTMP_LogPrintf("(c) 2010 Andrej Stepanchuk, Howard Chu; license: GPL\n\n");

  // init request
  memset(&defaultRTMPRequest, 0, sizeof(RTMP_REQUEST));

  defaultRTMPRequest.rtmpport = -1;
  defaultRTMPRequest.protocol = RTMP_PROTOCOL_UNDEFINED;
  defaultRTMPRequest.bLiveStream = FALSE;	// is it a live stream? then we can't seek/resume

  defaultRTMPRequest.timeout = 120;	// timeout connection after 120 seconds
  defaultRTMPRequest.bufferTime = 20 * 1000;

  defaultRTMPRequest.swfAge = 30;

  int opt;
  struct option longopts[] = {
    {"help", 0, NULL, 'h'},
    {"host", 1, NULL, 'n'},
    {"port", 1, NULL, 'c'},
    {"socks", 1, NULL, 'S'},
    {"protocol", 1, NULL, 'l'},
    {"playpath", 1, NULL, 'y'},
    {"rtmp", 1, NULL, 'r'},
    {"swfUrl", 1, NULL, 's'},
    {"tcUrl", 1, NULL, 't'},
    {"pageUrl", 1, NULL, 'p'},
    {"app", 1, NULL, 'a'},
#ifdef CRYPTO
    {"swfhash", 1, NULL, 'w'},
    {"swfsize", 1, NULL, 'x'},
    {"swfVfy", 1, NULL, 'W'},
    {"swfAge", 1, NULL, 'X'},
#endif
    {"auth", 1, NULL, 'u'},
    {"conn", 1, NULL, 'C'},
    {"flashVer", 1, NULL, 'f'},
    {"live", 0, NULL, 'v'},
    //{"flv",     1, NULL, 'o'},
    //{"resume",  0, NULL, 'e'},
    {"timeout", 1, NULL, 'm'},
    {"buffer", 1, NULL, 'b'},
    //{"skip",    1, NULL, 'k'},
    {"device", 1, NULL, 'D'},
    {"sport", 1, NULL, 'g'},
    {"subscribe", 1, NULL, 'd'},
    {"start", 1, NULL, 'A'},
    {"stop", 1, NULL, 'B'},
    {"token", 1, NULL, 'T'},
    {"debug", 0, NULL, 'z'},
    {"quiet", 0, NULL, 'q'},
    {"verbose", 0, NULL, 'V'},
    {"jtv", 1, NULL, 'j'},
    {0, 0, 0, 0}
  };

  signal(SIGINT, sigIntHandler);
#ifndef WIN32
  signal(SIGPIPE, SIG_IGN);
#endif

  InitSockets();

  while ((opt =
	  getopt_long(argc, argv,
		      "hvqVzr:s:t:p:a:f:u:n:c:l:y:m:d:D:A:B:T:g:w:x:W:X:S:j:", longopts,
		      NULL)) != -1)
    {
      switch (opt)
	{
	case 'h':
	  RTMP_LogPrintf
	    ("\nThis program serves media content streamed from RTMP onto HTTP.\n\n");
	  RTMP_LogPrintf("--help|-h               Prints this help screen.\n");
	  RTMP_LogPrintf
	    ("--rtmp|-r url           URL (e.g. rtmp://host[:port]/path)\n");
	  RTMP_LogPrintf
	    ("--host|-n hostname      Overrides the hostname in the rtmp url\n");
	  RTMP_LogPrintf
	    ("--port|-c port          Overrides the port in the rtmp url\n");
	  RTMP_LogPrintf
	    ("--socks|-S host:port    Use the specified SOCKS proxy\n");
	  RTMP_LogPrintf
	    ("--protocol|-l           Overrides the protocol in the rtmp url (0 - RTMP, 2 - RTMPE)\n");
	  RTMP_LogPrintf
	    ("--playpath|-y           Overrides the playpath parsed from rtmp url\n");
	  RTMP_LogPrintf("--swfUrl|-s url         URL to player swf file\n");
	  RTMP_LogPrintf
	    ("--tcUrl|-t url          URL to played stream (default: \"rtmp://host[:port]/app\")\n");
	  RTMP_LogPrintf("--pageUrl|-p url        Web URL of played programme\n");
	  RTMP_LogPrintf("--app|-a app            Name of target app in server\n");
#ifdef CRYPTO
	  RTMP_LogPrintf
	    ("--swfhash|-w hexstring  SHA256 hash of the decompressed SWF file (32 bytes)\n");
	  RTMP_LogPrintf
	    ("--swfsize|-x num        Size of the decompressed SWF file, required for SWFVerification\n");
	  RTMP_LogPrintf
	    ("--swfVfy|-W url         URL to player swf file, compute hash/size automatically\n");
	  RTMP_LogPrintf
	    ("--swfAge|-X days        Number of days to use cached SWF hash before refreshing\n");
#endif
	  RTMP_LogPrintf
	    ("--auth|-u string        Authentication string to be appended to the connect string\n");
	  RTMP_LogPrintf
	    ("--conn|-C type:data     Arbitrary AMF data to be appended to the connect string\n");
	  RTMP_LogPrintf
	    ("                        B:boolean(0|1), S:string, N:number, O:object-flag(0|1),\n");
	  RTMP_LogPrintf
	    ("                        Z:(null), NB:name:boolean, NS:name:string, NN:name:number\n");
	  RTMP_LogPrintf
	    ("--flashVer|-f string    Flash version string (default: \"%s\")\n",
	     RTMP_DefaultFlashVer.av_val);
	  RTMP_LogPrintf
	    ("--live|-v               Get a live stream, no --resume (seeking) of live streams possible\n");
	  RTMP_LogPrintf
	    ("--subscribe|-d string   Stream name to subscribe to (otherwise defaults to playpath if live is specified)\n");
	  RTMP_LogPrintf
	    ("--timeout|-m num        Timeout connection num seconds (default: %lu)\n",
	     defaultRTMPRequest.timeout);
	  RTMP_LogPrintf
	    ("--start|-A num          Start at num seconds into stream (not valid when using --live)\n");
	  RTMP_LogPrintf
	    ("--stop|-B num           Stop at num seconds into stream\n");
	  RTMP_LogPrintf
	    ("--token|-T key          Key for SecureToken response\n");
	  RTMP_LogPrintf
	    ("--jtv|-j JSON           Authentication token for Justin.tv legacy servers\n");
	  RTMP_LogPrintf
	    ("--buffer|-b             Buffer time in milliseconds (default: %u)\n\n",
	     defaultRTMPRequest.bufferTime);

	  RTMP_LogPrintf
	    ("--device|-D             Streaming device ip address (default: %s)\n",
	     DEFAULT_HTTP_STREAMING_DEVICE);
	  RTMP_LogPrintf
	    ("--sport|-g              Streaming port (default: %d)\n\n",
	     nHttpStreamingPort);
	  RTMP_LogPrintf
	    ("--quiet|-q              Suppresses all command output.\n");
	  RTMP_LogPrintf("--verbose|-V            Verbose command output.\n");
	  RTMP_LogPrintf("--debug|-z              Debug level command output.\n");
	  RTMP_LogPrintf
	    ("If you don't pass parameters for swfUrl, pageUrl, or auth these properties will not be included in the connect ");
	  RTMP_LogPrintf("packet.\n\n");
	  return RD_SUCCESS;
	  break;
	  // streaming server specific options
	case 'D':
	  if (inet_addr(optarg) == INADDR_NONE)
	    {
	      RTMP_Log(RTMP_LOGERROR,
		  "Invalid binding address (requested address %s), ignoring",
		  optarg);
	    }
	  else
	    {
	      httpStreamingDevice = optarg;
	    }
	  break;
	case 'g':
	  {
	    int port = atoi(optarg);
	    if (port < 0 || port > 65535)
	      {
		RTMP_Log(RTMP_LOGERROR,
		    "Streaming port out of range (requested port %d), ignoring\n",
		    port);
	      }
	    else
	      {
		nHttpStreamingPort = port;
	      }
	    break;
	  }
	default:
	  //RTMP_LogPrintf("unknown option: %c\n", opt);
	  if (!ParseOption(opt, optarg, &defaultRTMPRequest))
	    return RD_FAILED;
	  break;
	}
    }

#ifdef _DEBUG
  netstackdump = fopen("netstackdump", "wb");
  netstackdump_read = fopen("netstackdump_read", "wb");
#endif

  // start text UI
  ThreadCreate(controlServerThread, 0);

  // start http streaming
  if ((httpServer =
       startStreaming(httpStreamingDevice, nHttpStreamingPort)) == 0)
    {
      RTMP_Log(RTMP_LOGERROR, "Failed to start HTTP server, exiting!");
      return RD_FAILED;
    }
  RTMP_LogPrintf("Streaming on http://%s:%d\n", httpStreamingDevice,
	    nHttpStreamingPort);

  while (httpServer->state != STREAMING_STOPPED)
    {
      sleep(1);
    }
  RTMP_Log(RTMP_LOGDEBUG, "Done, exiting...");

  CleanupSockets();

#ifdef _DEBUG
  if (netstackdump != 0)
    fclose(netstackdump);
  if (netstackdump_read != 0)
    fclose(netstackdump_read);
#endif
  return nStatus;
}