示例#1
0
int main()
{
	InitSockets();
	OneBitSliding();
	cleanup();
	return(0);
}
示例#2
0
//void InitServer(svcInfoPtr psvc)
void InitServer()
{
    svcInfo svc;
    
    strcpy(svc.version, RUISVC_VERSION);
    svc.listenInterface = htonl(INADDR_ANY);
    svc.sock = -1;
    svc.port=	RUISVC_PORT;
    svc.socketState=SOCKET_INIT;
    svc.host[0] = 0;
    svc.jpegquality = 90;
    strcpy(svc.ftproot, "/sdcard");

    //INIT_MUTEX(svc.fbc_mutex);
    //INIT_COND(svc.updateCond);
    INIT_MUTEX(svc.output_mutex);

    InitSockets(&svc);

    listenerRun(&svc);

   // RunEventLoop(&svc);


}
示例#3
0
void CIpSocket::Construct()
{
	// Initialize socket library
	InitSockets();

	m_hSocket = c_InvalidSocket;

	m_hSocketEvent = c_InvalidEvent;

	m_uLastError = 0;

	m_uConnectState = 0;

	m_uEventState = 0;
	memset( &m_uEventStatus, 0, sizeof( m_uEventStatus ) );

	m_uSocketFamily = 0;
	m_uSocketType = 0;
	m_uSocketProtocol = 0;

	m_uReads = 0;
	m_uWrites = 0;
	m_uAccepts = 0;

	m_uFlags = 0;

	m_bFree = 0;

	m_lActivity = 0;

	m_lTimeout = 60000;
}
示例#4
0
TSS2_RC InitSocketTcti (
    TSS2_TCTI_CONTEXT *tctiContext, // OUT
    size_t *contextSize,            // IN/OUT
    const TCTI_SOCKET_CONF *conf,              // IN
    const uint64_t magic,
    const uint32_t version,
	const char *interfaceName,
    const uint8_t serverSockets
    )
{
    TSS2_RC rval = TSS2_RC_SUCCESS;
    SOCKET otherSock;
    SOCKET tpmSock;

    if( tctiContext == NULL )
    {
        *contextSize = sizeof( TSS2_TCTI_CONTEXT_INTEL );
        return TSS2_RC_SUCCESS;
    }
    else
    {
        (*printfFunction)(NO_PREFIX, "Initializing %s Interface\n", interfaceName );

        // Init TCTI context.
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->magic = magic;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->version = version;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->transmit = SocketSendTpmCommand;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->receive = SocketReceiveTpmResponse;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->finalize = SocketFinalize;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->cancel = SocketCancel;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->getPollHandles = 0;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->setLocality = SocketSetLocality;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality = 3;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.rmDebugPrefix = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->currentTctiContext = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->previousStage = TCTI_STAGE_INITIALIZE;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.tagReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.responseSizeReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.protocolResponseSizeReceived = 0;

        rval = (TSS2_RC) InitSockets( conf->hostname, conf->port, serverSockets, &otherSock, &tpmSock );
        if( rval == TSS2_RC_SUCCESS )
        {
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->otherSock = otherSock;
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->tpmSock = tpmSock;
        }
        else
        {
            CloseSockets( otherSock, tpmSock);
        }            
    }

    return rval;
}
示例#5
0
TSS2_RC InitSocketTcti (
    TSS2_TCTI_CONTEXT *tctiContext, // OUT
    size_t *contextSize,            // IN/OUT
    const TCTI_SOCKET_CONF *conf,              // IN
    const uint8_t serverSockets
    )
{
    TSS2_RC rval = TSS2_RC_SUCCESS;
    SOCKET otherSock;
    SOCKET tpmSock;

    if( tctiContext == NULL )
    {
        *contextSize = sizeof( TSS2_TCTI_CONTEXT_INTEL );
        return TSS2_RC_SUCCESS;
    }
    else
    {
        // Init TCTI context.
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->magic = TCTI_MAGIC;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->version = TCTI_VERSION;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->transmit = SocketSendTpmCommand;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->receive = SocketReceiveTpmResponse;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->finalize = SocketFinalize;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->cancel = SocketCancel;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->getPollHandles = 0;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->setLocality = SocketSetLocality;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality = 3;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.rmDebugPrefix = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->currentTctiContext = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->previousStage = TCTI_STAGE_INITIALIZE;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.tagReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.responseSizeReceived = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.protocolResponseSizeReceived = 0;
        TCTI_LOG_CALLBACK( tctiContext ) = conf->logCallback;
        TCTI_LOG_BUFFER_CALLBACK( tctiContext ) = conf->logBufferCallback;
        TCTI_LOG_DATA( tctiContext ) = conf->logData;

        rval = (TSS2_RC) InitSockets( conf->hostname, conf->port, serverSockets, &otherSock, &tpmSock, TCTI_LOG_CALLBACK( tctiContext ), TCTI_LOG_DATA( tctiContext) );
        if( rval == TSS2_RC_SUCCESS )
        {
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->otherSock = otherSock;
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->tpmSock = tpmSock;
        }
        else
        {
            CloseSockets( otherSock, tpmSock);
        }            
    }

    return rval;
}
示例#6
0
文件: net.c 项目: execunix/vinos
static void
initialize_action(void) {
	InitSockets();
	ipv4_result = try_proto(PF_INET);
#ifdef ISC_PLATFORM_HAVEIPV6
#ifdef WANT_IPV6
#ifdef ISC_PLATFORM_HAVEIN6PKTINFO
	ipv6_result = try_proto(PF_INET6);
#endif
#endif
#endif
}
示例#7
0
int main(int argc, char * argv[])
{
	std::string message = "Hello world.";
	for (int i = 0; i < argc; i++) {
		//printf("arg %i = %s", i, argv[i]);
		if (strcmp(argv[i], "B") == 0) 
			isA = false;
		else if (strcmp(argv[i], "-m") == 0) {
			message = argv[++i];
		}
	}
	
	printf("Sending Message: %s\n", message.c_str());
	
	InitSockets();
	OneBitSliding(message);
	cleanup();
	return(0);
}
示例#8
0
UDPSocket::UDPSocket()
/*! \brief Konstruktor der Klasse
 *
 * \header \#include <ppl7-inet.h>
 * \desc
 * Initialisiert interne Daten der Klasse
 */
{
#ifdef _WIN32
	InitSockets();
#endif
	timeout_sec=0;
	timeout_usec=0;
	socket=NULL;
	SourcePort=0;
	connect_timeout_sec=0;
	connect_timeout_usec=0;
	connected=false;
}
示例#9
0
	void TWS_TLServer::Start(void)
	{
		TLServer_WM::Start();

		std::ifstream file;
		file.open(CONFIGFILE);
		int sessionid = 0;
		char skip[100];
		char data[8];
		file.getline(skip,100);
		file.getline(data,8);
		this->FIRSTSOCKET = atoi(data);
		file.getline(skip,100);
		file.getline(data,8);
		int maxsockets = atoi(data); // get the # of sockets first
		file.getline(skip,100);
		file.getline(data,8);
		sessionid = atoi(data); // get the session id next 
		file.close();
		CString msg;
		if (sessionid!=0)
		{
			D("Orders can only be received from this machine.");
			D(CString("To change this, see ")+CONFIGFILE);
		}
		msg.Format("Looking for %i TWS instances...",maxsockets);
		D(msg);
		D(CString(LINE));
		InitSockets(maxsockets,sessionid);
		D(CString(LINE));
		msg.Format("Found %i of %i.",this->validlinkids.size(),maxsockets);
		D(msg);
		D(CString("For more instances, change value in: ")+CONFIGFILE);
		msg.Format("Found accounts: %s",gjoin(accts,","));
		D(msg);
	}
示例#10
0
文件: main-nt.C 项目: dyninst/paradyn
int
WINAPI
WinMain( HINSTANCE hInstance,
         HINSTANCE hPrevInstance,
         LPSTR lpCmdLine,
         int nCmdShow )
{
#ifdef _DEBUG
    // pause for attaching a debugger if desired
    MessageBox( NULL,
                "Pausing for debugger attach.  Press OK to continue",
                __argv[0],
                MB_OK );

    // provide a console for the visi so we can see error messages
    InitConsole();
#endif // _DEBUG

    // initialize our use of the WinSock library
    InitSockets( __argv[0] );    

    // call the traditional main()
    return main( __argc, __argv );
}
示例#11
0
isc_result_t
isc_interfaceiter_create(isc_mem_t *mctx, isc_interfaceiter_t **iterp) {
	char strbuf[ISC_STRERRORSIZE];
	isc_interfaceiter_t *iter;
	isc_result_t result;
	unsigned int major;
	unsigned int minor;
	unsigned int spmajor;
	ULONG err;
	int tries;
	int error;
	unsigned long bytesReturned = 0;

	REQUIRE(mctx != NULL);
	REQUIRE(iterp != NULL);
	REQUIRE(*iterp == NULL);

	iter = isc_mem_get(mctx, sizeof(*iter));
	if (iter == NULL)
		return (ISC_R_NOMEMORY);

	InitSockets();

	iter->mctx = mctx;
	iter->ipaa = NULL;
	iter->buf4 = NULL;
	iter->buf6 = NULL;
	iter->pos4 = NULL;
	iter->ipaaCur = NULL;
	iter->ipuaCur = NULL;
	iter->ipaasize = 0;
	iter->pos6 = 0;
	iter->buf6size = 0;
	iter->buf4size = 0;
	iter->result = ISC_R_FAILURE;
	iter->numIF = 0;
	iter->v4IF = 0;

	/*
	 * Use GetAdaptersAddresses in preference to ioctls when running
	 * on Windows XP SP1 or later.  Earlier GetAdaptersAddresses do
	 * not appear to provide enough information to associate unicast
	 * addresses with their prefixes.
	 */
	if (!use_GAA_determined) {
		major = isc_win32os_majorversion();
		minor = isc_win32os_minorversion();
		spmajor = isc_win32os_servicepackmajor();
		if (major > 5 || (5 == major &&
		    (minor > 1 || (1 == minor && spmajor >= 1)))) {
			if (NULL == hmod_iphlpapi)
				hmod_iphlpapi = LoadLibrary("iphlpapi");
			if (NULL != hmod_iphlpapi)
				pGAA = (PGETADAPTERSADDRESSES)
				    GetProcAddress(
					hmod_iphlpapi,
					"GetAdaptersAddresses");
			if (NULL != pGAA)
				use_GAA = ISC_TRUE;
		}
		use_GAA_determined = ISC_TRUE;
	}

	if (!use_GAA)
		goto use_ioctls;

	iter->ipaasize = 16 * 1024;

	for (tries = 0; tries < 5; tries++) {
		iter->ipaa = isc_mem_reallocate(mctx, iter->ipaa,
						 iter->ipaasize);
		if (NULL == iter->ipaa) {
			result = ISC_R_NOMEMORY;
			goto put_iter;
		}
		err = (*pGAA)(
			AF_UNSPEC,
			GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_ANYCAST,
			NULL,
			iter->ipaa,
			&iter->ipaasize);
		if (NO_ERROR == err || ERROR_BUFFER_OVERFLOW != err)
			break;
	}

	if (NO_ERROR != err) {
		isc__strerror(err, strbuf, sizeof(strbuf));
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				"GetAdaptersAddresses: %s",
				strbuf);
		result = ISC_R_UNEXPECTED;
		goto gaa_failure;
	}
	
	iter->ipaaCur = iter->ipaa;
	goto success;

 use_ioctls:
	/*
	 * Create an unbound datagram socket to do the
	 * SIO_GET_INTERFACE_LIST WSAIoctl on.
	 */
	if ((iter->socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		error = WSAGetLastError();
		if (error == WSAEAFNOSUPPORT)
			goto inet6_only;
		isc__strerror(error, strbuf, sizeof(strbuf));
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				"making interface scan socket: %s",
				strbuf);
		result = ISC_R_UNEXPECTED;
		goto put_iter;
	}

	/*
	 * Get the interface configuration, allocating more memory if
	 * necessary.
	 */
	iter->buf4size = IFCONF_SIZE_INITIAL*sizeof(INTERFACE_INFO);

	for (;;) {
		iter->buf4 = isc_mem_get(mctx, iter->buf4size);
		if (iter->buf4 == NULL) {
			result = ISC_R_NOMEMORY;
			goto alloc_failure;
		}

		if (WSAIoctl(iter->socket, SIO_GET_INTERFACE_LIST,
			     0, 0, iter->buf4, iter->buf4size,
			     &bytesReturned, 0, 0) == SOCKET_ERROR)
		{
			error = WSAGetLastError();
			if (error != WSAEFAULT && error != WSAENOBUFS) {
				errno = error;
				isc__strerror(error, strbuf, sizeof(strbuf));
				UNEXPECTED_ERROR(__FILE__, __LINE__,
						"get interface configuration: %s",
						strbuf);
				result = ISC_R_UNEXPECTED;
				goto ioctl_failure;
			}
			/*
			 * EINVAL.  Retry with a bigger buffer.
			 */
		} else {
			/*
			 * The WSAIoctl succeeded.
			 * If the number of the returned bytes is the same
			 * as the buffer size, we will grow it just in
			 * case and retry.
			 */
			if (bytesReturned > 0 &&
			    (bytesReturned < iter->buf4size))
				break;
		}
		if (iter->buf4size >= IFCONF_SIZE_MAX*sizeof(INTERFACE_INFO)) {
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "get interface configuration: "
					 "maximum buffer size exceeded");
			result = ISC_R_UNEXPECTED;
			goto ioctl_failure;
		}
		isc_mem_put(mctx, iter->buf4, iter->buf4size);

		iter->buf4size += IFCONF_SIZE_INCREMENT *
			sizeof(INTERFACE_INFO);
	}

	/*
	 * A newly created iterator has an undefined position
	 * until isc_interfaceiter_first() is called.
	 */
	iter->v4IF = bytesReturned/sizeof(INTERFACE_INFO);

	/* We don't need the socket any more, so close it */
	closesocket(iter->socket);

 inet6_only:
	/*
	 * Create an unbound datagram socket to do the
	 * SIO_ADDRESS_LIST_QUERY WSAIoctl on.
	 */
	if ((iter->socket = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
		error = WSAGetLastError();
		if (error == WSAEAFNOSUPPORT)
			goto success;
		isc__strerror(error, strbuf, sizeof(strbuf));
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				"making interface scan socket: %s",
				strbuf);
		result = ISC_R_UNEXPECTED;
		goto put_iter;
	}

	/*
	 * Get the interface configuration, allocating more memory if
	 * necessary.
	 */
	iter->buf6size = sizeof(SOCKET_ADDRESS_LIST) +
			 IFCONF_SIZE_INITIAL*sizeof(SOCKET_ADDRESS);

	for (;;) {
		iter->buf6 = isc_mem_get(mctx, iter->buf6size);
		if (iter->buf6 == NULL) {
			result = ISC_R_NOMEMORY;
			goto ioctl_failure;
		}

		if (WSAIoctl(iter->socket, SIO_ADDRESS_LIST_QUERY,
			     0, 0, iter->buf6, iter->buf6size,
			     &bytesReturned, 0, 0) == SOCKET_ERROR)
		{
			error = WSAGetLastError();
			if (error != WSAEFAULT && error != WSAENOBUFS) {
				errno = error;
				isc__strerror(error, strbuf, sizeof(strbuf));
				UNEXPECTED_ERROR(__FILE__, __LINE__,
						 "sio address list query: %s",
						 strbuf);
				result = ISC_R_UNEXPECTED;
				goto ioctl6_failure;
			}
			/*
			 * EINVAL.  Retry with a bigger buffer.
			 */
		} else
			break;

		if (iter->buf6size >= IFCONF_SIZE_MAX*sizeof(SOCKET_ADDRESS)) {
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "get interface configuration: "
					 "maximum buffer size exceeded");
			result = ISC_R_UNEXPECTED;
			goto ioctl6_failure;
		}
		isc_mem_put(mctx, iter->buf6, iter->buf6size);

		iter->buf6size += IFCONF_SIZE_INCREMENT *
			sizeof(SOCKET_ADDRESS);
	}

	/*
	 * initialize loop__1 to [::1] and loopfe80__1 to [fe80::1].
	 * used by internal_current6().
	 */
	memset(&iter->loop__1, 0, sizeof(iter->loop__1));
	memset(&iter->loopfe80__1, 0, sizeof(iter->loopfe80__1));
	iter->loop__1.s6_addr[15] = 1;
	iter->loopfe80__1.s6_addr[15] = 1;
	iter->loopfe80__1.s6_addr[0] = 0xfe;
	iter->loopfe80__1.s6_addr[1] = 0x80;

	closesocket(iter->socket);

 success:
	iter->magic = IFITER_MAGIC;
	*iterp = iter;
	return (ISC_R_SUCCESS);

 gaa_failure:
	isc_mem_put(mctx, iter->ipaa, iter->ipaasize);
	goto put_iter;

 ioctl6_failure:
	isc_mem_put(mctx, iter->buf6, iter->buf6size);

 ioctl_failure:
	if (iter->buf4 != NULL)
		isc_mem_put(mctx, iter->buf4, iter->buf4size);

 alloc_failure:
	if (iter->socket >= 0)
		(void) closesocket(iter->socket);

 put_iter:
	isc_mem_put(mctx, iter, sizeof(*iter));
	return (result);
}
示例#12
0
int
main(int argc, char **argv)
{
	extern char *optarg;

	int nStatus = RD_SUCCESS;
	double percent = 0;
	double duration = 0.0;

	int nSkipKeyFrames = DEF_SKIPFRM; // skip this number of keyframes when resuming

	int bOverrideBufferTime = FALSE;  // if the user specifies a buffer time override this is true
	int bStdoutMode = TRUE;	  // if true print the stream directly to stdout, messages go to stderr
	int bResume = FALSE;	  // true in resume mode
	uint32_t dSeek = 0;		  // seek position in resume mode, 0 otherwise
	uint32_t bufferTime = DEF_BUFTIME;

	// meta header and initial frame for the resume mode (they are read from the file and compared with
	// the stream we are trying to continue
	char *metaHeader = 0;
	uint32_t nMetaHeaderSize = 0;

	// video keyframe for matching
	char *initialFrame = 0;
	uint32_t nInitialFrameSize = 0;
	int initialFrameType = 0; // tye: audio or video

	AVal hostname = { 0, 0 };
	AVal playpath = { 0, 0 };
	AVal subscribepath = { 0, 0 };
	AVal usherToken = { 0, 0 };	//Justin.tv auth token
	int port = -1;
	int protocol = RTMP_PROTOCOL_UNDEFINED;
	int retries = 0;
	int bLiveStream = FALSE;  // is it a live stream? then we can't seek/resume
	int bRealtimeStream = FALSE;  // If true, disable the BUFX hack (be patient)
	int bHashes = FALSE;	  // display byte counters not hashes by default

	long int timeout = DEF_TIMEOUT;	  // timeout connection after 120 seconds
	uint32_t dStartOffset = 0;	  // seek position in non-live mode
	uint32_t dStopOffset = 0;
	RTMP rtmp = { 0 };
	FILE *pLogFile;

	AVal fullUrl = { 0, 0 };
	AVal swfUrl = { 0, 0 };
	AVal tcUrl = { 0, 0 };
	AVal pageUrl = { 0, 0 };
	AVal app = { 0, 0 };
	AVal auth = { 0, 0 };
	AVal swfHash = { 0, 0 };
	uint32_t swfSize = 0;
	AVal flashVer = { 0, 0 };
	AVal sockshost = { 0, 0 };

#ifdef CRYPTO
	int swfAge = 30;  /* 30 days for SWF cache by default */
	int swfVfy = 0;
	unsigned char hash[RTMP_SWF_HASHLEN];
#endif

	char *flvFile = 0;

	signal(SIGINT, sigIntHandler);
	signal(SIGTERM, sigIntHandler);
#ifndef WIN32
	signal(SIGHUP, sigIntHandler);
	signal(SIGPIPE, sigIntHandler);
	signal(SIGQUIT, sigIntHandler);
#endif

	RTMP_debuglevel = RTMP_LOGALL;

	//pLogFile = fopen("log.txt", "w");
	//RTMP_LogSetOutput(pLogFile);

	// Check for --quiet option before printing any output
	int index = 0;
	while (index < argc)
	{
		if (strcmp(argv[index], "--quiet") == 0
			|| strcmp(argv[index], "-q") == 0)
			RTMP_debuglevel = RTMP_LOGCRIT;
		index++;
	}
#define RTMPDUMP_VERSION "2.4"
	RTMP_LogPrintf("RTMPDump %s\n", RTMPDUMP_VERSION);
	RTMP_LogPrintf
	("(c) 2010 Andrej Stepanchuk, Howard Chu, The Flvstreamer Team; license: GPL\n");

	if (!InitSockets())
	{
		RTMP_Log(RTMP_LOGERROR,
				 "Couldn't load sockets support on your platform, exiting!");
		return RD_FAILED;
	}

	/* sleep(30); */

	RTMP_Init(&rtmp);

	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'},
	{"playlist", 0, NULL, 'Y'},
	{"rtmp", 1, NULL, 'r'},
	{"swfUrl", 1, NULL, 's'},
	{"tcUrl", 1, NULL, 't'},
	{"pageUrl", 1, NULL, 'p'},
	{"app", 1, NULL, 'a'},
	{"auth", 1, NULL, 'u'},
	{"conn", 1, NULL, 'C'},
#ifdef CRYPTO
	{"swfhash", 1, NULL, 'w'},
	{"swfsize", 1, NULL, 'x'},
	{"swfVfy", 1, NULL, 'W'},
	{"swfAge", 1, NULL, 'X'},
#endif
	{"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'},
	{"subscribe", 1, NULL, 'd'},
	{"start", 1, NULL, 'A'},
	{"stop", 1, NULL, 'B'},
	{"token", 1, NULL, 'T'},
	{"hashes", 0, NULL, '#'},
	{"debug", 0, NULL, 'z'},
	{"quiet", 0, NULL, 'q'},
	{"verbose", 0, NULL, 'V'},
	{0, 0, 0, 0}
  };*/

	while ((opt =
			getopt/*_long*/(argc, argv,
							"hVveqzr:s:t:p:a:b:f:o:u:C:n:c:l:y:Ym:k:d:A:B:T:w:x:W:X:S:#"/*,
							longopts, NULL*/)) != -1)
	{
		switch (opt)
		{
			case 'h':
				usage(argv[0]);
				return RD_SUCCESS;
#ifdef CRYPTO
			case 'w':
				{
					int res = hex2bin(optarg, &swfHash.av_val);
					if (res != RTMP_SWF_HASHLEN)
					{
						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);
					}
					swfHash.av_len = RTMP_SWF_HASHLEN;
					break;
				}
			case 'x':
				{
					int size = atoi(optarg);
					if (size <= 0)
					{
						RTMP_Log(RTMP_LOGERROR, "SWF Size must be at least 1, ignoring\n");
					}
					else
					{
						swfSize = size;
					}
					break;
				}
			case 'W':
				STR2AVAL(swfUrl, optarg);
				swfVfy = 1;
				break;
			case 'X':
				{
					int num = atoi(optarg);
					if (num < 0)
					{
						RTMP_Log(RTMP_LOGERROR, "SWF Age must be non-negative, ignoring\n");
					}
					else
					{
						swfAge = num;
					}
				}
				break;
#endif
			case 'k':
				nSkipKeyFrames = atoi(optarg);
				if (nSkipKeyFrames < 0)
				{
					RTMP_Log(RTMP_LOGERROR,
							 "Number of keyframes skipped must be greater or equal zero, using zero!");
					nSkipKeyFrames = 0;
				}
				else
				{
					RTMP_Log(RTMP_LOGDEBUG, "Number of skipped key frames for resume: %d",
							 nSkipKeyFrames);
				}
				break;
			case 'b':
				{
					int32_t bt = atol(optarg);
					if (bt < 0)
					{
						RTMP_Log(RTMP_LOGERROR,
								 "Buffer time must be greater than zero, ignoring the specified value %d!",
								 bt);
					}
					else
					{
						bufferTime = bt;
						bOverrideBufferTime = TRUE;
					}
					break;
				}
			case 'v':
				bLiveStream = TRUE;	  // no seeking or resuming possible!
				break;
			case 'R':
				bRealtimeStream = TRUE;	// seeking and resuming is still possible
				break;
			case 'd':
				STR2AVAL(subscribepath, optarg);
				break;
			case 'n':
				STR2AVAL(hostname, optarg);
				break;
			case 'c':
				port = atoi(optarg);
				break;
			case 'l':
				protocol = atoi(optarg);
				if (protocol < RTMP_PROTOCOL_RTMP || protocol > RTMP_PROTOCOL_RTMPTS)
				{
					RTMP_Log(RTMP_LOGERROR, "Unknown protocol specified: %d", protocol);
					return RD_FAILED;
				}
				break;
			case 'y':
				STR2AVAL(playpath, optarg);
				break;
			case 'Y':
				RTMP_SetOpt(&rtmp, &av_playlist, (AVal *)&av_true);
				break;
			case 'r':
				{
					AVal parsedHost, parsedApp, parsedPlaypath;
					unsigned int parsedPort = 0;
					int parsedProtocol = RTMP_PROTOCOL_UNDEFINED;

					if (!RTMP_ParseURL
						(optarg, &parsedProtocol, &parsedHost, &parsedPort,
						 &parsedPlaypath, &parsedApp))
					{
						RTMP_Log(RTMP_LOGWARNING, "Couldn't parse the specified url (%s)!",
								 optarg);
					}
					else
					{
						if (!hostname.av_len)
							hostname = parsedHost;
						if (port == -1)
							port = parsedPort;
						if (playpath.av_len == 0 && parsedPlaypath.av_len)
						{
							playpath = parsedPlaypath;
						}
						if (protocol == RTMP_PROTOCOL_UNDEFINED)
							protocol = parsedProtocol;
						if (app.av_len == 0 && parsedApp.av_len)
						{
							app = parsedApp;
						}
					}
					break;
				}
			case 'i':
				STR2AVAL(fullUrl, optarg);
				break;
			case 's':
				STR2AVAL(swfUrl, optarg);
				break;
			case 't':
				STR2AVAL(tcUrl, optarg);
				break;
			case 'p':
				STR2AVAL(pageUrl, optarg);
				break;
			case 'a':
				STR2AVAL(app, optarg);
				break;
			case 'f':
				STR2AVAL(flashVer, optarg);
				break;
			case 'o':
				flvFile = optarg;
				if (strcmp(flvFile, "-"))
					bStdoutMode = FALSE;

				break;
			case 'e':
				bResume = TRUE;
				break;
			case 'u':
				STR2AVAL(auth, optarg);
				break;
			case 'C': {
					AVal av;
					STR2AVAL(av, optarg);
					if (!RTMP_SetOpt(&rtmp, &av_conn, &av))
					{
						RTMP_Log(RTMP_LOGERROR, "Invalid AMF parameter: %s", optarg);
						return RD_FAILED;
					}
				}
				break;
			case 'm':
				timeout = atoi(optarg);
				break;
			case 'A':
				dStartOffset = (int) (atof(optarg) * 1000.0);
				break;
			case 'B':
				dStopOffset = (int) (atof(optarg) * 1000.0);
				break;
			case 'T': {
					AVal token;
					STR2AVAL(token, optarg);
					RTMP_SetOpt(&rtmp, &av_token, &token);
				}
				break;
			case '#':
				bHashes = TRUE;
				break;
			case 'q':
				RTMP_debuglevel = RTMP_LOGCRIT;
				break;
			case 'V':
				RTMP_debuglevel = RTMP_LOGDEBUG;
				break;
			case 'z':
				RTMP_debuglevel = RTMP_LOGALL;
				break;
			case 'S':
				STR2AVAL(sockshost, optarg);
				break;
			case 'j':
				STR2AVAL(usherToken, optarg);
				break;
			default:
				RTMP_LogPrintf("unknown option: %c\n", opt);
				usage(argv[0]);
				return RD_FAILED;
				break;
		}
	}

	if (!hostname.av_len && !fullUrl.av_len)
	{
		RTMP_Log(RTMP_LOGERROR,
				 "You must specify a hostname (--host) or url (-r \"rtmp://host[:port]/playpath\") containing a hostname");
		return RD_FAILED;
	}
	if (playpath.av_len == 0 && !fullUrl.av_len)
	{
		RTMP_Log(RTMP_LOGERROR,
				 "You must specify a playpath (--playpath) or url (-r \"rtmp://host[:port]/playpath\") containing a playpath");
		return RD_FAILED;
	}

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

	if (flvFile == 0)
	{
		RTMP_Log(RTMP_LOGWARNING,
				 "You haven't specified an output file (-o filename), using stdout");
		bStdoutMode = TRUE;
	}

	if (bStdoutMode && bResume)
	{
		RTMP_Log(RTMP_LOGWARNING,
				 "Can't resume in stdout mode, ignoring --resume option");
		bResume = FALSE;
	}

	if (bLiveStream && bResume)
	{
		RTMP_Log(RTMP_LOGWARNING, "Can't resume live stream, ignoring --resume option");
		bResume = FALSE;
	}

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

	if (swfHash.av_len == 0 && swfSize > 0)
	{
		RTMP_Log(RTMP_LOGWARNING,
				 "Ignoring SWF size, supply also the hash with --swfhash");
		swfSize = 0;
	}

	if (swfHash.av_len != 0 && swfSize == 0)
	{
		RTMP_Log(RTMP_LOGWARNING,
				 "Ignoring SWF hash, supply also the swf size  with --swfsize");
		swfHash.av_len = 0;
		swfHash.av_val = NULL;
	}
#endif

	if (tcUrl.av_len == 0)
	{
		tcUrl.av_len = strlen(RTMPProtocolStringsLower[protocol]) +
					   hostname.av_len + app.av_len + sizeof("://:65535/");
		tcUrl.av_val = (char *) malloc(tcUrl.av_len);
		if (!tcUrl.av_val)
			return RD_FAILED;
		tcUrl.av_len = snprintf(tcUrl.av_val, tcUrl.av_len, "%s://%.*s:%d/%.*s",
								RTMPProtocolStringsLower[protocol], hostname.av_len,
								hostname.av_val, port, app.av_len, app.av_val);
	}

	int first = 1;

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

	if (!fullUrl.av_len)
	{
		RTMP_SetupStream(&rtmp, protocol, &hostname, port, &sockshost, &playpath,
						 &tcUrl, &swfUrl, &pageUrl, &app, &auth, &swfHash, swfSize,
						 &flashVer, &subscribepath, &usherToken, dSeek, dStopOffset, bLiveStream, timeout);
	}
	else
	{
		if (RTMP_SetupURL(&rtmp, fullUrl.av_val) == FALSE)
		{
			RTMP_Log(RTMP_LOGERROR, "Couldn't parse URL: %s", fullUrl.av_val);
			return RD_FAILED;
		}
	}

	/* Try to keep the stream moving if it pauses on us */
	if (!bLiveStream && !bRealtimeStream && !(protocol & RTMP_FEATURE_HTTP))
		rtmp.Link.lFlags |= RTMP_LF_BUFX;

	off_t size = 0;

	// ok, we have to get the timestamp of the last keyframe (only keyframes are seekable) / last audio frame (audio only streams)
	if (bResume)
	{
		nStatus =
		OpenResumeFile(flvFile, &file, &size, &metaHeader, &nMetaHeaderSize,
					   &duration);
		if (nStatus == RD_FAILED)
			goto clean;

		if (!file)
		{
			// file does not exist, so go back into normal mode
			bResume = FALSE;  // we are back in fresh file mode (otherwise finalizing file won't be done)
		}
		else
		{
			nStatus = GetLastKeyframe(file, nSkipKeyFrames,
									  &dSeek, &initialFrame,
									  &initialFrameType, &nInitialFrameSize);
			if (nStatus == RD_FAILED)
			{
				RTMP_Log(RTMP_LOGDEBUG, "Failed to get last keyframe.");
				goto clean;
			}

			if (dSeek == 0)
			{
				RTMP_Log(RTMP_LOGDEBUG,
						 "Last keyframe is first frame in stream, switching from resume to normal mode!");
				bResume = FALSE;
			}
		}
	}

	if (!file)
	{
		if (bStdoutMode)
		{
			file = stdout;
			SET_BINMODE(file);
		}
		else
		{
			file = fopen(flvFile, "w+b");
			if (file == 0)
			{
				RTMP_LogPrintf("Failed to open file! %s\n", flvFile);
				return RD_FAILED;
			}
		}
	}

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

	while (!RTMP_ctrlC)
	{
		RTMP_Log(RTMP_LOGDEBUG, "Setting buffer time to: %dms", bufferTime);
		RTMP_SetBufferMS(&rtmp, bufferTime);

		if (first)
		{
			first = 0;
			RTMP_LogPrintf("Connecting ...\n");

			if (!RTMP_Connect(&rtmp, NULL))
			{
				nStatus = RD_NO_CONNECT;
				break;
			}

			RTMP_Log(RTMP_LOGINFO, "Connected...");

			// User defined seek offset
			if (dStartOffset > 0)
			{
				// Don't need the start offset if resuming an existing file
				if (bResume)
				{
					RTMP_Log(RTMP_LOGWARNING,
							 "Can't seek a resumed stream, ignoring --start option");
					dStartOffset = 0;
				}
				else
				{
					dSeek = dStartOffset;
				}
			}

			// Calculate the length of the stream to still play
			if (dStopOffset > 0)
			{
				// Quit if start seek is past required stop offset
				if (dStopOffset <= dSeek)
				{
					RTMP_LogPrintf("Already Completed\n");
					nStatus = RD_SUCCESS;
					break;
				}
			}

			if (!RTMP_ConnectStream(&rtmp, dSeek))
			{
				nStatus = RD_FAILED;
				break;
			}
		}
		else
		{
			nInitialFrameSize = 0;

			if (retries)
			{
				RTMP_Log(RTMP_LOGERROR, "Failed to resume the stream\n\n");
				if (!RTMP_IsTimedout(&rtmp))
					nStatus = RD_FAILED;
				else
					nStatus	= RD_INCOMPLETE;
				break;
			}
			RTMP_Log(RTMP_LOGINFO, "Connection timed out, trying to resume.\n\n");
			/* Did we already try pausing, and it still didn't work? */
			if (rtmp.m_pausing == 3)
			{
				/* Only one try at reconnecting... */
				retries = 1;
				dSeek = rtmp.m_pauseStamp;
				if (dStopOffset > 0)
				{
					if (dStopOffset <= dSeek)
					{
						RTMP_LogPrintf("Already Completed\n");
						nStatus = RD_SUCCESS;
						break;
					}
				}
				if (!RTMP_ReconnectStream(&rtmp, dSeek))
				{
					RTMP_Log(RTMP_LOGERROR, "Failed to resume the stream\n\n");
					if (!RTMP_IsTimedout(&rtmp))
						nStatus = RD_FAILED;
					else
						nStatus	= RD_INCOMPLETE;
					break;
				}
			}
			else if (!RTMP_ToggleStream(&rtmp))
			{
				RTMP_Log(RTMP_LOGERROR, "Failed to resume the stream\n\n");
				if (!RTMP_IsTimedout(&rtmp))
					nStatus = RD_FAILED;
				else
					nStatus	= RD_INCOMPLETE;
				break;
			}
			bResume = TRUE;
		}

		nStatus = Download(&rtmp, file, dSeek, dStopOffset, duration, bResume,
						   metaHeader, nMetaHeaderSize, initialFrame,
						   initialFrameType, nInitialFrameSize, nSkipKeyFrames,
						   bStdoutMode, bLiveStream, bRealtimeStream, bHashes,
						   bOverrideBufferTime, bufferTime, &percent);
		free(initialFrame);
		initialFrame = NULL;

		/* If we succeeded, we're done.
		 */
		if (nStatus != RD_INCOMPLETE || !RTMP_IsTimedout(&rtmp) || bLiveStream)
			break;
	}

	if (nStatus == RD_SUCCESS)
	{
		RTMP_LogPrintf("Download complete\n");
	}
	else if (nStatus == RD_INCOMPLETE)
	{
		RTMP_LogPrintf
		("Download may be incomplete (downloaded about %.2f%%), try resuming\n",
		 percent);
	}

	clean:
	RTMP_Log(RTMP_LOGDEBUG, "Closing connection.\n");
	RTMP_Close(&rtmp);

	if (file != 0)
		fclose(file);

	CleanupSockets();

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

	fclose(pLogFile);
	return nStatus;
}
示例#13
0
static lwres_result_t
context_connect(lwres_context_t *ctx) {
#ifndef WIN32
	int s;
#else
	SOCKET s;
#endif
	int ret;
	struct sockaddr_in sin;
	struct sockaddr_in6 sin6;
	struct sockaddr *sa;
	LWRES_SOCKADDR_LEN_T salen;
	int domain;

	if (ctx->confdata.lwnext != 0) {
		memmove(&ctx->address, &ctx->confdata.lwservers[0],
			sizeof(lwres_addr_t));
		LWRES_LINK_INIT(&ctx->address, link);
	} else {
		/* The default is the IPv4 loopback address 127.0.0.1. */
		memset(&ctx->address, 0, sizeof(ctx->address));
		ctx->address.family = LWRES_ADDRTYPE_V4;
		ctx->address.length = 4;
		ctx->address.address[0] = 127;
		ctx->address.address[1] = 0;
		ctx->address.address[2] = 0;
		ctx->address.address[3] = 1;
	}

	if (ctx->address.family == LWRES_ADDRTYPE_V4) {
		memmove(&sin.sin_addr, ctx->address.address,
			sizeof(sin.sin_addr));
		sin.sin_port = htons(lwres_udp_port);
		sin.sin_family = AF_INET;
		sa = (struct sockaddr *)&sin;
		salen = sizeof(sin);
		domain = PF_INET;
	} else if (ctx->address.family == LWRES_ADDRTYPE_V6) {
		memmove(&sin6.sin6_addr, ctx->address.address,
			sizeof(sin6.sin6_addr));
		sin6.sin6_port = htons(lwres_udp_port);
		sin6.sin6_family = AF_INET6;
		sa = (struct sockaddr *)&sin6;
		salen = sizeof(sin6);
		domain = PF_INET6;
	} else
		return (LWRES_R_IOERROR);

#ifdef WIN32
	InitSockets();
#endif
	s = socket(domain, SOCK_DGRAM, IPPROTO_UDP);
#ifndef WIN32
	if (s < 0) {
		return (LWRES_R_IOERROR);
	}
#else
	if (s == INVALID_SOCKET) {
		DestroySockets();
		return (LWRES_R_IOERROR);
	}
#endif

	ret = connect(s, sa, salen);
	if (ret != 0) {
#ifdef WIN32
		DestroySockets();
#endif
		(void)close(s);
		return (LWRES_R_IOERROR);
	}

	MAKE_NONBLOCKING(s, ret);
	if (ret < 0) {
#ifdef WIN32
		DestroySockets();
#endif
		(void)close(s);
		return (LWRES_R_IOERROR);
	}

	ctx->sock = (int)s;

	return (LWRES_R_SUCCESS);
}
示例#14
0
TSS2_RC InitSocketsTcti (
    TSS2_TCTI_CONTEXT *tctiContext, // OUT
    size_t *contextSize,            // IN/OUT
    const char *config,              // IN
    const uint64_t magic,
    const uint32_t version,
	const char *interfaceName,
    const uint8_t serverSockets
    )
{
    TSS2_RC rval = TSS2_RC_SUCCESS;
    char hostName[200];
    int port;
    SOCKET otherSock;
    SOCKET tpmSock;

    if( tctiContext == NULL )
    {
        *contextSize = sizeof( TSS2_TCTI_CONTEXT_INTEL );
        return TSS2_RC_SUCCESS;
    }
    else
    {
        OpenOutFile( &outFp );
        (*printfFunction)(NO_PREFIX, "Initializing %s Interface\n", interfaceName );

        // Init TCTI context.
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->magic = magic;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->version = version;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->transmit = SocketSendTpmCommand;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->receive = SocketReceiveTpmResponse;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->finalize = SocketFinalize;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->cancel = SocketCancel;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->getPollHandles = 0;
        ((TSS2_TCTI_CONTEXT_COMMON_V1 *)tctiContext)->setLocality = SocketSetLocality;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.locality = 3;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.commandSent = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->status.rmDebugPrefix = 0;
        ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->currentTctiContext = 0;

        // Get hostname and port.
        if( ( strlen( config ) + 2 ) <= ( HOSTNAME_LENGTH  ) )
        {
            if( 1 == sscanf( config, "%199s", hostName ) ) 
            {
                if( strlen( config) - ( strlen( hostName ) + 2 ) <= PORT_LENGTH )
                {
                    if( 1 != sscanf( &config[strlen( hostName )], "%d", &port ) )
                    {
                        return( TSS2_TCTI_RC_BAD_VALUE );
                    }
                }
                else
                {
                    return( TSS2_TCTI_RC_BAD_VALUE );
                }
            }
            else
            {
                return( TSS2_TCTI_RC_BAD_VALUE );
            }
        }
        else
        {
            return( TSS2_TCTI_RC_INSUFFICIENT_BUFFER );
        }

        rval = (TSS2_RC) InitSockets( &hostName[0], port, serverSockets, &otherSock, &tpmSock );
        if( rval == TSS2_RC_SUCCESS )
        {
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->otherSock = otherSock;
            ((TSS2_TCTI_CONTEXT_INTEL *)tctiContext)->tpmSock = tpmSock;
        }
        else
        {
            CloseSockets( otherSock, tpmSock);
        }            
        CloseOutFile( &outFp );
    }

    return rval;
}
示例#15
0
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 *rtmpStreamingDevice = DEFAULT_HTTP_STREAMING_DEVICE;	// streaming device, default 0.0.0.0
  int nRtmpStreamingPort = 1935;	// port

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

  RTMP_debuglevel = RTMP_LOGINFO;

  if (argc > 1 && !strcmp(argv[1], "-z"))
    RTMP_debuglevel = RTMP_LOGALL;

  // 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 = 300;	// timeout connection afte 300 seconds
  defaultRTMPRequest.bufferTime = 20 * 1000;


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

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

  InitSockets();

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

  // start http streaming
  if ((rtmpServer =
       startStreaming(rtmpStreamingDevice, nRtmpStreamingPort)) == 0)
    {
      RTMP_Log(RTMP_LOGERROR, "Failed to start RTMP server, exiting!");
      return RD_FAILED;
    }
  RTMP_LogPrintf("Streaming on rtmp://%s:%d\n", rtmpStreamingDevice,
	    nRtmpStreamingPort);

  while (rtmpServer->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;
}
示例#16
0
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
  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'},
    {0, 0, 0, 0}
  };
  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;



  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:", 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
	    ("--buffer|-b             Buffer time in milliseconds (default: %lu)\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;
}
示例#17
0
int NET2_Init()
{
  if (initialized)
  {
    return 0;
  }

#ifndef WIN32

  // SIGPIPE has to be ignored so that NET2 can handle broken
  // connections without raising a program wide exception. SDL_net
  // "should" do this so that it can handle exception properly, but it
  // doesn't.

  signal(SIGPIPE, SIG_IGN); // work around for bug in SDL_net
#endif

  error = 0;
  errorSocket = -1;

  doneYet = 0;

  dataLock = SDL_CreateMutex();
  if (NULL == dataLock)
  {
    setError("NET2: can't create a mutex", -1);
    return -1;
  }

  sdlNetLock = SDL_CreateMutex();
  if (NULL == sdlNetLock)
  {
    setError("NET2: can't create a mutex", -1);
    return -1;
  }

  dataWait = SDL_CreateCond();
  if (NULL == dataWait)
  {
    setError("NET2: can't create a condition variable", -1);
    return -1;
  }

  InitSockets(maxSockets);

  udpSendSocket = snUDPOpen(0);
  if (NULL == udpSendSocket)
  {
    setError("NET2: can't open the UDP send socket", -1);
    return -1;
  }

  processSockets = SDL_CreateThread(PumpNetworkEvents, NULL);
  if (NULL == processSockets)
  {
    setError("NET2: can't start the network thread", -1);
    return -1;
  }
  //printf("root=%d thread=%d\n", SDL_ThreadID(), SDL_GetThreadID(processSockets)); fflush(NULL);

  initialized = 1;
  return 0;
}
示例#18
0
//Publish using RTMP_Write()
int publish_using_write(){
         uint32_t start_time=0;
         uint32_t now_time=0;
         uint32_t pre_frame_time=0;
         uint32_t lasttime=0;
         int bNextIsKey=0;
         char* pFileBuf=NULL;
 
         //read from tag header
         uint32_t type=0;
         uint32_t datalength=0;
         uint32_t timestamp=0;
 
         RTMP *rtmp=NULL;                           
        
         FILE*fp=NULL;
         fp=fopen("cuc_ieschool.flv","rb");
         if (!fp){
                   RTMP_LogPrintf("Open File Error.\n");
                   CleanupSockets();
                   return -1;
         }
 
         /* set log level */
         //RTMP_LogLevel loglvl=RTMP_LOGDEBUG;
         //RTMP_LogSetLevel(loglvl);
                  
         if (!InitSockets()){
                  RTMP_LogPrintf("Init Socket Err\n");
                   return -1;
         }
 
         rtmp=RTMP_Alloc();
         RTMP_Init(rtmp);
         //set connection timeout,default 30s
         rtmp->Link.timeout=5;                      
         if(!RTMP_SetupURL(rtmp,"rtmp://localhost/publishlive/livestream"))
         {
                   RTMP_Log(RTMP_LOGERROR,"SetupURL Err\n");
                   RTMP_Free(rtmp);
                   CleanupSockets();
                   return -1;
         }
 
         RTMP_EnableWrite(rtmp);
         //1hour
         RTMP_SetBufferMS(rtmp, 3600*1000);         
         if (!RTMP_Connect(rtmp,NULL)){
                   RTMP_Log(RTMP_LOGERROR,"Connect Err\n");
                   RTMP_Free(rtmp);
                   CleanupSockets();
                   return -1;
         }
        
         if (!RTMP_ConnectStream(rtmp,0)){
                   RTMP_Log(RTMP_LOGERROR,"ConnectStream Err\n");
                   RTMP_Close(rtmp);
                   RTMP_Free(rtmp);
                   CleanupSockets();
                   return -1;
         }
 
         printf("Start to send data ...\n");
        
         //jump over FLV Header
         fseek(fp,9,SEEK_SET);     
         //jump over previousTagSizen
         fseek(fp,4,SEEK_CUR);   
         start_time=RTMP_GetTime();
         while(1)
         {
                   if((((now_time=RTMP_GetTime())-start_time)
                              <(pre_frame_time)) && bNextIsKey){        
                            //wait for 1 sec if the send process is too fast
                            //this mechanism is not very good,need some improvement
                            if(pre_frame_time>lasttime){
                                     RTMP_LogPrintf("TimeStamp:%8lu ms\n",pre_frame_time);
                                     lasttime=pre_frame_time;
                            }
                            sleep(1);
                            continue;
                   }
                  
                   //jump over type
                   fseek(fp,1,SEEK_CUR);   
                   if(!ReadU24(&datalength,fp))
                            break;
                   if(!ReadTime(&timestamp,fp))
                            break;
                   //jump back
                   fseek(fp,-8,SEEK_CUR);  
                  
                   pFileBuf=(char*)malloc(11+datalength+4);
                   memset(pFileBuf,0,11+datalength+4);
                   if(fread(pFileBuf,1,11+datalength+4,fp)!=(11+datalength+4))
                            break;
                  
                   pre_frame_time=timestamp;
                  
                   if (!RTMP_IsConnected(rtmp)){
                            RTMP_Log(RTMP_LOGERROR,"rtmp is not connect\n");
                            break;
                   }
                   if (!RTMP_Write(rtmp,pFileBuf,11+datalength+4)){
                            RTMP_Log(RTMP_LOGERROR,"Rtmp Write Error\n");
                            break;
                   }
                  
                   free(pFileBuf);
                   pFileBuf=NULL;
 
                   if(!PeekU8(&type,fp))
                            break;
                   if(type==0x09){
                            if(fseek(fp,11,SEEK_CUR)!=0)
                                     break;
                            if(!PeekU8(&type,fp)){
                                     break;
                            }
                            if(type==0x17)
                                     bNextIsKey=1;
                            else
                                     bNextIsKey=0;
                            fseek(fp,-11,SEEK_CUR);
                   }
         }
 
         RTMP_LogPrintf("\nSend Data Over\n");
        
         if(fp)
                   fclose(fp);
 
         if (rtmp!=NULL){
                   RTMP_Close(rtmp);        
                   RTMP_Free(rtmp);
                   rtmp=NULL;
         }
 
         if(pFileBuf){
                   free(pFileBuf);
                   pFileBuf=NULL;
         }
 
         CleanupSockets();
         return 0;
}
示例#19
0
文件: socket.cpp 项目: starand/cpp
CSocket::CSocket( bool bUseLength /* = false */ ) : m_bUseHeaderLength(bUseLength)
{
	InitSockets();
}
示例#20
0
static int
scan_interfaces(int *have_v4, int *have_v6) {
#if !defined(SIOCGIFCONF) || !defined(SIOCGIFADDR)
	*have_v4 = *have_v6 = 1;
	return (0);
#else
	struct ifconf ifc;
	union {
		char _pad[256];		/* leave space for IPv6 addresses */
		struct ifreq ifreq;
	} u;
	struct in_addr in4;
	struct in6_addr in6;
	char *buf = NULL, *cp, *cplim;
	static unsigned int bufsiz = 4095;
	int s, n;
	size_t cpsize;

#ifdef WIN32
	InitSockets();
#endif
#if defined(SIOCGLIFCONF) && defined(SIOCGLIFADDR) && \
    !defined(IRIX_EMUL_IOCTL_SIOCGIFCONF)
	/*
	 * Try to scan the interfaces using IPv6 ioctls().
	 */
	if (!scan_interfaces6(have_v4, have_v6)) {
#ifdef WIN32
		DestroySockets();
#endif
		return (0);
	}
#endif

	/*
	 * Set to zero.  Used as loop terminators below.
	 */
	*have_v4 = *have_v6 = 0;

	/*
	 * Get interface list from system.
	 */
	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
		goto err_ret;

	/*
	 * Grow buffer until large enough to contain all interface
	 * descriptions.
	 */
	for (;;) {
		buf = malloc(bufsiz);
		if (buf == NULL)
			goto err_ret;
		ifc.ifc_len = bufsiz;
		ifc.ifc_buf = buf;
#ifdef IRIX_EMUL_IOCTL_SIOCGIFCONF
		/*
		 * This is a fix for IRIX OS in which the call to ioctl with
		 * the flag SIOCGIFCONF may not return an entry for all the
		 * interfaces like most flavors of Unix.
		 */
		if (emul_ioctl(&ifc) >= 0)
			break;
#else
		if ((n = ioctl(s, SIOCGIFCONF, (char *)&ifc)) != -1) {
			/*
			 * Some OS's just return what will fit rather
			 * than set EINVAL if the buffer is too small
			 * to fit all the interfaces in.  If
			 * ifc.ifc_len is too near to the end of the
			 * buffer we will grow it just in case and
			 * retry.
			 */
			if (ifc.ifc_len + 2 * sizeof(u.ifreq) < bufsiz)
				break;
		}
#endif
		if ((n == -1) && errno != EINVAL)
			goto err_ret;

		if (bufsiz > 1000000)
			goto err_ret;

		free(buf);
		bufsiz += 4096;
	}

	/*
	 * Parse system's interface list.
	 */
	cplim = buf + ifc.ifc_len;    /* skip over if's with big ifr_addr's */
	for (cp = buf;
	     (*have_v4 == 0 || *have_v6 == 0) && cp < cplim;
	     cp += cpsize) {
		memcpy(&u.ifreq, cp, sizeof(u.ifreq));
#ifdef LWRES_PLATFORM_HAVESALEN
#ifdef FIX_ZERO_SA_LEN
		if (u.ifreq.ifr_addr.sa_len == 0)
			u.ifreq.ifr_addr.sa_len = 16;
#endif
#ifdef HAVE_MINIMUM_IFREQ
		cpsize = sizeof(u.ifreq);
		if (u.ifreq.ifr_addr.sa_len > sizeof(struct sockaddr))
			cpsize += (int)u.ifreq.ifr_addr.sa_len -
				(int)(sizeof(struct sockaddr));
#else
		cpsize = sizeof(u.ifreq.ifr_name) + u.ifreq.ifr_addr.sa_len;
#endif /* HAVE_MINIMUM_IFREQ */
		if (cpsize > sizeof(u.ifreq) && cpsize <= sizeof(u))
			memcpy(&u.ifreq, cp, cpsize);
#elif defined SIOCGIFCONF_ADDR
		cpsize = sizeof(u.ifreq);
#else
		cpsize = sizeof(u.ifreq.ifr_name);
		/* XXX maybe this should be a hard error? */
		if (ioctl(s, SIOCGIFADDR, (char *)&u.ifreq) < 0)
			continue;
#endif
		switch (u.ifreq.ifr_addr.sa_family) {
		case AF_INET:
			if (*have_v4 == 0) {
				memcpy(&in4,
				       &((struct sockaddr_in *)
				       &u.ifreq.ifr_addr)->sin_addr,
				       sizeof(in4));
				if (in4.s_addr == INADDR_ANY)
					break;
				n = ioctl(s, SIOCGIFFLAGS, (char *)&u.ifreq);
				if (n < 0)
					break;
				if ((u.ifreq.ifr_flags & IFF_UP) == 0)
					break;
				*have_v4 = 1;
			}
			break;
		case AF_INET6:
			if (*have_v6 == 0) {
				memcpy(&in6,
				       &((struct sockaddr_in6 *)
				       &u.ifreq.ifr_addr)->sin6_addr,
				       sizeof(in6));
				if (memcmp(&in6, &in6addr_any,
					   sizeof(in6)) == 0)
					break;
				n = ioctl(s, SIOCGIFFLAGS, (char *)&u.ifreq);
				if (n < 0)
					break;
				if ((u.ifreq.ifr_flags & IFF_UP) == 0)
					break;
				*have_v6 = 1;
			}
			break;
		}
	}
	if (buf != NULL)
		free(buf);
#ifdef WIN32
	DestroySockets();
#endif
	close(s);
	return (0);

 err_ret:
	if (buf != NULL)
		free(buf);
	if (s != -1)
		close(s);
#ifdef WIN32
	DestroySockets();
#endif
	return (-1);
#endif
}
示例#21
0
//Publish using RTMP_SendPacket()
int publish_using_packet(){
         RTMP *rtmp=NULL;                           
         RTMPPacket *packet=NULL;
         uint32_t start_time=0;
         uint32_t now_time=0;
         //the timestamp of the previous frame
         long pre_frame_time=0;
         long lasttime=0;
         int bNextIsKey=1;
         uint32_t preTagsize=0;
        
         //packet attributes
         uint32_t type=0;                        
         uint32_t datalength=0;           
         uint32_t timestamp=0;           
         uint32_t streamid=0;                        
 
         FILE*fp=NULL;
         fp=fopen("Wildlife.flv","rb");
         if (!fp){
                   RTMP_LogPrintf("Open File Error.\n");
                   CleanupSockets();
                   return -1;
         }
 
         /* set log level */
         //RTMP_LogLevel loglvl=RTMP_LOGDEBUG;
         //RTMP_LogSetLevel(loglvl);
                  
         if (!InitSockets()){
                   RTMP_LogPrintf("Init Socket Err\n");
                   return -1;
         }
 
         rtmp=RTMP_Alloc();
         RTMP_Init(rtmp);
         //set connection timeout,default 30s
         rtmp->Link.timeout=5;                      
         if(!RTMP_SetupURL(rtmp,"rtmp://127.0.0.1:8080/live/test"))
         {
                   RTMP_Log(RTMP_LOGERROR,"SetupURL Err\n");
                   RTMP_Free(rtmp);
                   CleanupSockets();
                   return -1;
         }
        
         //if unable,the AMF command would be 'play' instead of 'publish'
         RTMP_EnableWrite(rtmp);     
        
         if (!RTMP_Connect(rtmp,NULL)){
                   RTMP_Log(RTMP_LOGERROR,"Connect Err\n");
                   RTMP_Free(rtmp);
                   CleanupSockets();
                   return -1;
         }
        
         if (!RTMP_ConnectStream(rtmp,0)){
                   RTMP_Log(RTMP_LOGERROR,"ConnectStream Err\n");
                   RTMP_Close(rtmp);
                   RTMP_Free(rtmp);
                   CleanupSockets();
                   return -1;
         }
 
         packet=(RTMPPacket*)malloc(sizeof(RTMPPacket));
         RTMPPacket_Alloc(packet,1024*64);
         RTMPPacket_Reset(packet);
 
         packet->m_hasAbsTimestamp = 0;        
         packet->m_nChannel = 0x04;
         packet->m_nInfoField2 = rtmp->m_stream_id;
 
         RTMP_LogPrintf("Start to send data ...\n");
        
         //jump over FLV Header
         fseek(fp,9,SEEK_SET);     
         //jump over previousTagSizen
         fseek(fp,4,SEEK_CUR);   
         start_time=RTMP_GetTime();
         while(1)
         {
                   if((((now_time=RTMP_GetTime())-start_time)
                              <(pre_frame_time)) && bNextIsKey){        
                            //wait for 1 sec if the send process is too fast
                            //this mechanism is not very good,need some improvement
                            if(pre_frame_time>lasttime){
                                     RTMP_LogPrintf("TimeStamp:%8lu ms\n",pre_frame_time);
                                     lasttime=pre_frame_time;
                            }
                            sleep(1);
                            continue;
                   }
                  
                   //not quite the same as FLV spec
                   if(!ReadU8(&type,fp))     
                            break;
                   if(!ReadU24(&datalength,fp))
                            break;
                   if(!ReadTime(&timestamp,fp))
                            break;
                   if(!ReadU24(&streamid,fp))
                            break;
 
                   if (type!=0x08&&type!=0x09){
                            //jump over non_audio and non_video frame,
                            //jump over next previousTagSizen at the same time
                            fseek(fp,datalength+4,SEEK_CUR);
                            continue;
                   }
                  
                   if(fread(packet->m_body,1,datalength,fp)!=datalength)
                            break;
 
                   packet->m_headerType = RTMP_PACKET_SIZE_LARGE;
                   packet->m_nTimeStamp = timestamp;
                   packet->m_packetType = type;
                   packet->m_nBodySize  = datalength;
                   pre_frame_time=timestamp;
 
                   if (!RTMP_IsConnected(rtmp)){
                            RTMP_Log(RTMP_LOGERROR,"rtmp is not connect\n");
                            break;
                   }
                   if (!RTMP_SendPacket(rtmp,packet,0)){
                            RTMP_Log(RTMP_LOGERROR,"Send Error\n");
                            break;
                   }
 
                   if(!ReadU32(&preTagsize,fp))
                            break;
                           
                   if(!PeekU8(&type,fp))
                            break;
                   if(type==0x09){
                            if(fseek(fp,11,SEEK_CUR)!=0)
                                     break;
                            if(!PeekU8(&type,fp)){
                                     break;
                            }
                            if(type==0x17)
                                     bNextIsKey=1;
                            else
                                     bNextIsKey=0;
 
                            fseek(fp,-11,SEEK_CUR);
                   }
         }               
 
         RTMP_LogPrintf("\nSend Data Over\n");
        
         if(fp)
                   fclose(fp);
 
         if (rtmp!=NULL){
                   RTMP_Close(rtmp);        
                   RTMP_Free(rtmp); 
                   rtmp=NULL;
         }
         if (packet!=NULL){
                   RTMPPacket_Free(packet);    
                   free(packet);
                   packet=NULL;
         }
 
         CleanupSockets();
         return 0;
}
示例#22
0
isc_result_t
isc_interfaceiter_create(isc_mem_t *mctx, isc_interfaceiter_t **iterp) {
	char strbuf[ISC_STRERRORSIZE];
	isc_interfaceiter_t *iter;
	isc_result_t result;
	int error;
	unsigned long bytesReturned = 0;

	REQUIRE(mctx != NULL);
	REQUIRE(iterp != NULL);
	REQUIRE(*iterp == NULL);

	iter = isc_mem_get(mctx, sizeof(*iter));
	if (iter == NULL)
		return (ISC_R_NOMEMORY);

	InitSockets();

	iter->mctx = mctx;
	iter->buf4 = NULL;
	iter->buf6 = NULL;
	iter->pos4 = NULL;
	iter->pos6 = 0;
	iter->buf6size = 0;
	iter->buf4size = 0;
	iter->result = ISC_R_FAILURE;
	iter->numIF = 0;
	iter->v4IF = 0;

	/*
	 * Create an unbound datagram socket to do the
	 * SIO_GET_INTERFACE_LIST WSAIoctl on.
	 */
	iter->socket = socket(AF_INET, SOCK_DGRAM, 0);
	if (iter->socket == INVALID_SOCKET) {
		error = WSAGetLastError();
		if (error == WSAEAFNOSUPPORT)
			goto inet6_only;
		isc__strerror(error, strbuf, sizeof(strbuf));
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				"making interface scan socket: %s",
				strbuf);
		result = ISC_R_UNEXPECTED;
		goto socket_failure;
	}

	/*
	 * Get the interface configuration, allocating more memory if
	 * necessary.
	 */
	iter->buf4size = IFCONF_SIZE_INITIAL*sizeof(INTERFACE_INFO);

	for (;;) {
		iter->buf4 = isc_mem_get(mctx, iter->buf4size);
		if (iter->buf4 == NULL) {
			result = ISC_R_NOMEMORY;
			goto alloc_failure;
		}

		if (WSAIoctl(iter->socket, SIO_GET_INTERFACE_LIST,
			     0, 0, iter->buf4, iter->buf4size,
			     &bytesReturned, 0, 0) == SOCKET_ERROR)
		{
			error = WSAGetLastError();
			if (error != WSAEFAULT && error != WSAENOBUFS) {
				errno = error;
				isc__strerror(error, strbuf, sizeof(strbuf));
				UNEXPECTED_ERROR(__FILE__, __LINE__,
						"get interface configuration: %s",
						strbuf);
				result = ISC_R_UNEXPECTED;
				goto ioctl_failure;
			}
			/*
			 * EINVAL.  Retry with a bigger buffer.
			 */
		} else {
			/*
			 * The WSAIoctl succeeded.
			 * If the number of the returned bytes is the same
			 * as the buffer size, we will grow it just in
			 * case and retry.
			 */
			if (bytesReturned > 0 &&
			    (bytesReturned < iter->buf4size))
				break;
		}
		if (iter->buf4size >= IFCONF_SIZE_MAX*sizeof(INTERFACE_INFO)) {
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "get interface configuration: "
					 "maximum buffer size exceeded");
			result = ISC_R_UNEXPECTED;
			goto ioctl_failure;
		}
		isc_mem_put(mctx, iter->buf4, iter->buf4size);

		iter->buf4size += IFCONF_SIZE_INCREMENT *
			sizeof(INTERFACE_INFO);
	}

	/*
	 * A newly created iterator has an undefined position
	 * until isc_interfaceiter_first() is called.
	 */
	iter->v4IF = bytesReturned/sizeof(INTERFACE_INFO);

	/* We don't need the socket any more, so close it */
	closesocket(iter->socket);

 inet6_only:
	/*
	 * Create an unbound datagram socket to do the
	 * SIO_ADDRESS_LIST_QUERY WSAIoctl on.
	 */
	iter->socket = socket(AF_INET6, SOCK_DGRAM, 0);
	if (iter->socket == INVALID_SOCKET) {
		error = WSAGetLastError();
		if (error == WSAEAFNOSUPPORT)
			goto inet_only;
		isc__strerror(error, strbuf, sizeof(strbuf));
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				"making interface scan socket: %s",
				strbuf);
		result = ISC_R_UNEXPECTED;
		goto ioctl_failure;
	}

	/*
	 * Get the interface configuration, allocating more memory if
	 * necessary.
	 */
	iter->buf6size = sizeof(SOCKET_ADDRESS_LIST) +
			 IFCONF_SIZE_INITIAL*sizeof(SOCKET_ADDRESS);

	for (;;) {
		iter->buf6 = isc_mem_get(mctx, iter->buf6size);
		if (iter->buf6 == NULL) {
			result = ISC_R_NOMEMORY;
			goto ioctl_failure;
		}

		if (WSAIoctl(iter->socket, SIO_ADDRESS_LIST_QUERY,
			     0, 0, iter->buf6, iter->buf6size,
			     &bytesReturned, 0, 0) == SOCKET_ERROR)
		{
			error = WSAGetLastError();
			if (error != WSAEFAULT && error != WSAENOBUFS) {
				errno = error;
				isc__strerror(error, strbuf, sizeof(strbuf));
				UNEXPECTED_ERROR(__FILE__, __LINE__,
						 "sio address list query: %s",
						 strbuf);
				result = ISC_R_UNEXPECTED;
				goto ioctl6_failure;
			}
			/*
			 * EINVAL.  Retry with a bigger buffer.
			 */
		} else
			break;

		if (iter->buf6size >= IFCONF_SIZE_MAX*sizeof(SOCKET_ADDRESS)) {
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "get interface configuration: "
					 "maximum buffer size exceeded");
			result = ISC_R_UNEXPECTED;
			goto ioctl6_failure;
		}
		isc_mem_put(mctx, iter->buf6, iter->buf6size);

		iter->buf6size += IFCONF_SIZE_INCREMENT *
			sizeof(SOCKET_ADDRESS);
	}

	closesocket(iter->socket);

 inet_only:
	iter->magic = IFITER_MAGIC;
	*iterp = iter;
	return (ISC_R_SUCCESS);

 ioctl6_failure:
	isc_mem_put(mctx, iter->buf6, iter->buf6size);

 ioctl_failure:
	if (iter->buf4 != NULL)
		isc_mem_put(mctx, iter->buf4, iter->buf4size);

 alloc_failure:
	if (iter->socket != INVALID_SOCKET)
		(void) closesocket(iter->socket);

 socket_failure:
	isc_mem_put(mctx, iter, sizeof(*iter));
	return (result);
}
/*% main processing routine */
int
main(int argc, char **argv) {
	int c;
	char *origin = NULL;
	char *filename = NULL;
	isc_log_t *lctx = NULL;
	isc_result_t result;
	char classname_in[] = "IN";
	char *classname = classname_in;
	const char *workdir = NULL;
	const char *inputformatstr = NULL;
	const char *outputformatstr = NULL;
	dns_masterformat_t inputformat = dns_masterformat_text;
	dns_masterformat_t outputformat = dns_masterformat_text;
	dns_masterrawheader_t header;
	isc_uint32_t rawversion = 1, serialnum = 0;
	isc_boolean_t snset = ISC_FALSE;
	isc_boolean_t logdump = ISC_FALSE;
	FILE *errout = stdout;
	char *endp;

	outputstyle = &dns_master_style_full;

	prog_name = strrchr(argv[0], '/');
	if (prog_name == NULL)
		prog_name = strrchr(argv[0], '\\');
	if (prog_name != NULL)
		prog_name++;
	else
		prog_name = argv[0];
	/*
	 * Libtool doesn't preserve the program name prior to final
	 * installation.  Remove the libtool prefix ("lt-").
	 */
	if (strncmp(prog_name, "lt-", 3) == 0)
		prog_name += 3;

#define PROGCMP(X) \
	(strcasecmp(prog_name, X) == 0 || strcasecmp(prog_name, X ".exe") == 0)

	if (PROGCMP("named-checkzone"))
		progmode = progmode_check;
	else if (PROGCMP("named-compilezone"))
		progmode = progmode_compile;
	else
		INSIST(0);

	/* Compilation specific defaults */
	if (progmode == progmode_compile) {
		zone_options |= (DNS_ZONEOPT_CHECKNS |
				 DNS_ZONEOPT_FATALNS |
				 DNS_ZONEOPT_CHECKSPF |
				 DNS_ZONEOPT_CHECKDUPRR |
				 DNS_ZONEOPT_CHECKNAMES |
				 DNS_ZONEOPT_CHECKNAMESFAIL |
				 DNS_ZONEOPT_CHECKWILDCARD);
	} else
		zone_options |= (DNS_ZONEOPT_CHECKDUPRR |
				 DNS_ZONEOPT_CHECKSPF);

#define ARGCMP(X) (strcmp(isc_commandline_argument, X) == 0)

	isc_commandline_errprint = ISC_FALSE;

	while ((c = isc_commandline_parse(argc, argv,
			       "c:df:hi:jk:L:m:n:qr:s:t:o:vw:DF:M:S:T:W:"))
	       != EOF) {
		switch (c) {
		case 'c':
			classname = isc_commandline_argument;
			break;

		case 'd':
			debug++;
			break;

		case 'i':
			if (ARGCMP("full")) {
				zone_options |= DNS_ZONEOPT_CHECKINTEGRITY |
						DNS_ZONEOPT_CHECKSIBLING;
				docheckmx = ISC_TRUE;
				docheckns = ISC_TRUE;
				dochecksrv = ISC_TRUE;
			} else if (ARGCMP("full-sibling")) {
				zone_options |= DNS_ZONEOPT_CHECKINTEGRITY;
				zone_options &= ~DNS_ZONEOPT_CHECKSIBLING;
				docheckmx = ISC_TRUE;
				docheckns = ISC_TRUE;
				dochecksrv = ISC_TRUE;
			} else if (ARGCMP("local")) {
				zone_options |= DNS_ZONEOPT_CHECKINTEGRITY;
				zone_options |= DNS_ZONEOPT_CHECKSIBLING;
				docheckmx = ISC_FALSE;
				docheckns = ISC_FALSE;
				dochecksrv = ISC_FALSE;
			} else if (ARGCMP("local-sibling")) {
				zone_options |= DNS_ZONEOPT_CHECKINTEGRITY;
				zone_options &= ~DNS_ZONEOPT_CHECKSIBLING;
				docheckmx = ISC_FALSE;
				docheckns = ISC_FALSE;
				dochecksrv = ISC_FALSE;
			} else if (ARGCMP("none")) {
				zone_options &= ~DNS_ZONEOPT_CHECKINTEGRITY;
				zone_options &= ~DNS_ZONEOPT_CHECKSIBLING;
				docheckmx = ISC_FALSE;
				docheckns = ISC_FALSE;
				dochecksrv = ISC_FALSE;
			} else {
				fprintf(stderr, "invalid argument to -i: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 'f':
			inputformatstr = isc_commandline_argument;
			break;

		case 'F':
			outputformatstr = isc_commandline_argument;
			break;

		case 'j':
			nomerge = ISC_FALSE;
			break;

		case 'k':
			if (ARGCMP("warn")) {
				zone_options |= DNS_ZONEOPT_CHECKNAMES;
				zone_options &= ~DNS_ZONEOPT_CHECKNAMESFAIL;
			} else if (ARGCMP("fail")) {
				zone_options |= DNS_ZONEOPT_CHECKNAMES |
						DNS_ZONEOPT_CHECKNAMESFAIL;
			} else if (ARGCMP("ignore")) {
				zone_options &= ~(DNS_ZONEOPT_CHECKNAMES |
						  DNS_ZONEOPT_CHECKNAMESFAIL);
			} else {
				fprintf(stderr, "invalid argument to -k: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 'L':
			snset = ISC_TRUE;
			endp = NULL;
			serialnum = strtol(isc_commandline_argument, &endp, 0);
			if (*endp != '\0') {
				fprintf(stderr, "source serial number "
						"must be numeric");
				exit(1);
			}
			break;

		case 'n':
			if (ARGCMP("ignore")) {
				zone_options &= ~(DNS_ZONEOPT_CHECKNS|
						  DNS_ZONEOPT_FATALNS);
			} else if (ARGCMP("warn")) {
				zone_options |= DNS_ZONEOPT_CHECKNS;
				zone_options &= ~DNS_ZONEOPT_FATALNS;
			} else if (ARGCMP("fail")) {
				zone_options |= DNS_ZONEOPT_CHECKNS|
						DNS_ZONEOPT_FATALNS;
			} else {
				fprintf(stderr, "invalid argument to -n: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 'm':
			if (ARGCMP("warn")) {
				zone_options |= DNS_ZONEOPT_CHECKMX;
				zone_options &= ~DNS_ZONEOPT_CHECKMXFAIL;
			} else if (ARGCMP("fail")) {
				zone_options |= DNS_ZONEOPT_CHECKMX |
						DNS_ZONEOPT_CHECKMXFAIL;
			} else if (ARGCMP("ignore")) {
				zone_options &= ~(DNS_ZONEOPT_CHECKMX |
						  DNS_ZONEOPT_CHECKMXFAIL);
			} else {
				fprintf(stderr, "invalid argument to -m: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 'o':
			output_filename = isc_commandline_argument;
			break;

		case 'q':
			quiet++;
			break;

		case 'r':
			if (ARGCMP("warn")) {
				zone_options |= DNS_ZONEOPT_CHECKDUPRR;
				zone_options &= ~DNS_ZONEOPT_CHECKDUPRRFAIL;
			} else if (ARGCMP("fail")) {
				zone_options |= DNS_ZONEOPT_CHECKDUPRR |
						DNS_ZONEOPT_CHECKDUPRRFAIL;
			} else if (ARGCMP("ignore")) {
				zone_options &= ~(DNS_ZONEOPT_CHECKDUPRR |
						  DNS_ZONEOPT_CHECKDUPRRFAIL);
			} else {
				fprintf(stderr, "invalid argument to -r: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 's':
			if (ARGCMP("full"))
				outputstyle = &dns_master_style_full;
			else if (ARGCMP("relative")) {
				outputstyle = &dns_master_style_default;
			} else {
				fprintf(stderr,
					"unknown or unsupported style: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 't':
			result = isc_dir_chroot(isc_commandline_argument);
			if (result != ISC_R_SUCCESS) {
				fprintf(stderr, "isc_dir_chroot: %s: %s\n",
					isc_commandline_argument,
					isc_result_totext(result));
				exit(1);
			}
			break;

		case 'v':
			printf(VERSION "\n");
			exit(0);

		case 'w':
			workdir = isc_commandline_argument;
			break;

		case 'D':
			dumpzone++;
			break;

		case 'M':
			if (ARGCMP("fail")) {
				zone_options &= ~DNS_ZONEOPT_WARNMXCNAME;
				zone_options &= ~DNS_ZONEOPT_IGNOREMXCNAME;
			} else if (ARGCMP("warn")) {
				zone_options |= DNS_ZONEOPT_WARNMXCNAME;
				zone_options &= ~DNS_ZONEOPT_IGNOREMXCNAME;
			} else if (ARGCMP("ignore")) {
				zone_options |= DNS_ZONEOPT_WARNMXCNAME;
				zone_options |= DNS_ZONEOPT_IGNOREMXCNAME;
			} else {
				fprintf(stderr, "invalid argument to -M: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 'S':
			if (ARGCMP("fail")) {
				zone_options &= ~DNS_ZONEOPT_WARNSRVCNAME;
				zone_options &= ~DNS_ZONEOPT_IGNORESRVCNAME;
			} else if (ARGCMP("warn")) {
				zone_options |= DNS_ZONEOPT_WARNSRVCNAME;
				zone_options &= ~DNS_ZONEOPT_IGNORESRVCNAME;
			} else if (ARGCMP("ignore")) {
				zone_options |= DNS_ZONEOPT_WARNSRVCNAME;
				zone_options |= DNS_ZONEOPT_IGNORESRVCNAME;
			} else {
				fprintf(stderr, "invalid argument to -S: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 'T':
			if (ARGCMP("warn")) {
				zone_options |= DNS_ZONEOPT_CHECKSPF;
			} else if (ARGCMP("ignore")) {
				zone_options &= ~DNS_ZONEOPT_CHECKSPF;
			} else {
				fprintf(stderr, "invalid argument to -T: %s\n",
					isc_commandline_argument);
				exit(1);
			}
			break;

		case 'W':
			if (ARGCMP("warn"))
				zone_options |= DNS_ZONEOPT_CHECKWILDCARD;
			else if (ARGCMP("ignore"))
				zone_options &= ~DNS_ZONEOPT_CHECKWILDCARD;
			break;

		case '?':
			if (isc_commandline_option != '?')
				fprintf(stderr, "%s: invalid argument -%c\n",
					prog_name, isc_commandline_option);
			/* FALLTHROUGH */
		case 'h':
			usage();

		default:
			fprintf(stderr, "%s: unhandled option -%c\n",
				prog_name, isc_commandline_option);
			exit(1);
		}
	}

	if (workdir != NULL) {
		result = isc_dir_chdir(workdir);
		if (result != ISC_R_SUCCESS) {
			fprintf(stderr, "isc_dir_chdir: %s: %s\n",
				workdir, isc_result_totext(result));
			exit(1);
		}
	}

	if (inputformatstr != NULL) {
		if (strcasecmp(inputformatstr, "text") == 0)
			inputformat = dns_masterformat_text;
		else if (strcasecmp(inputformatstr, "raw") == 0)
			inputformat = dns_masterformat_raw;
		else if (strncasecmp(inputformatstr, "raw=", 4) == 0) {
			inputformat = dns_masterformat_raw;
			fprintf(stderr,
				"WARNING: input format raw, version ignored\n");
		} else {
			fprintf(stderr, "unknown file format: %s\n",
			    inputformatstr);
			exit(1);
		}
	}

	if (outputformatstr != NULL) {
		if (strcasecmp(outputformatstr, "text") == 0) {
			outputformat = dns_masterformat_text;
		} else if (strcasecmp(outputformatstr, "raw") == 0) {
			outputformat = dns_masterformat_raw;
		} else if (strncasecmp(outputformatstr, "raw=", 4) == 0) {
			char *end;

			outputformat = dns_masterformat_raw;
			rawversion = strtol(outputformatstr + 4, &end, 10);
			if (end == outputformatstr + 4 || *end != '\0' ||
			    rawversion > 1U) {
				fprintf(stderr,
					"unknown raw format version\n");
				exit(1);
			}
		} else {
			fprintf(stderr, "unknown file format: %s\n",
				outputformatstr);
			exit(1);
		}
	}

	if (progmode == progmode_compile) {
		dumpzone = 1;	/* always dump */
		logdump = !quiet;
		if (output_filename == NULL) {
			fprintf(stderr,
				"output file required, but not specified\n");
			usage();
		}
	}

	if (output_filename != NULL)
		dumpzone = 1;

	/*
	 * If we are outputing to stdout then send the informational
	 * output to stderr.
	 */
	if (dumpzone &&
	    (output_filename == NULL ||
	     strcmp(output_filename, "-") == 0 ||
	     strcmp(output_filename, "/dev/fd/1") == 0 ||
	     strcmp(output_filename, "/dev/stdout") == 0)) {
		errout = stderr;
		logdump = ISC_FALSE;
	}

	if (isc_commandline_index + 2 != argc)
		usage();

#ifdef _WIN32
	InitSockets();
#endif

	RUNTIME_CHECK(isc_mem_create(0, 0, &mctx) == ISC_R_SUCCESS);
	if (!quiet)
		RUNTIME_CHECK(setup_logging(mctx, errout, &lctx)
			      == ISC_R_SUCCESS);
	RUNTIME_CHECK(isc_entropy_create(mctx, &ectx) == ISC_R_SUCCESS);
	RUNTIME_CHECK(isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE)
		      == ISC_R_SUCCESS);

	dns_result_register();

	origin = argv[isc_commandline_index++];
	filename = argv[isc_commandline_index++];
	result = load_zone(mctx, origin, filename, inputformat, classname,
			   &zone);

	if (snset) {
		dns_master_initrawheader(&header);
		header.flags = DNS_MASTERRAW_SOURCESERIALSET;
		header.sourceserial = serialnum;
		dns_zone_setrawdata(zone, &header);
	}

	if (result == ISC_R_SUCCESS && dumpzone) {
		if (logdump) {
			fprintf(errout, "dump zone to %s...", output_filename);
			fflush(errout);
		}
		result = dump_zone(origin, zone, output_filename,
				   outputformat, outputstyle, rawversion);
		if (logdump)
			fprintf(errout, "done\n");
	}

	if (!quiet && result == ISC_R_SUCCESS)
		fprintf(errout, "OK\n");
	destroy();
	if (lctx != NULL)
		isc_log_destroy(&lctx);
	isc_hash_destroy();
	isc_entropy_detach(&ectx);
	isc_mem_destroy(&mctx);
#ifdef _WIN32
	DestroySockets();
#endif
	return ((result == ISC_R_SUCCESS) ? 0 : 1);
}
int main(int argc, char* argv[])
{
    InitSockets();

    double duration = -1;
    int nRead;
    //is live stream ?
    bool bLiveStream = TRUE;

    int bufsize = 1024 * 1024 * 10;
    char *buf = (char*)malloc(bufsize);
    memset(buf, 0, bufsize);
    long countbufsize = 0;

    FILE *fp = fopen("receive.flv", "wb");
    if (!fp)
    {
        RTMP_LogPrintf("Open File Error.\n");
        CleanupSockets();
        return -1;
    }

    /* set log level */
    RTMP_LogLevel loglvl = RTMP_LOGDEBUG;
    RTMP_LogSetLevel(loglvl);

    RTMP *rtmp = RTMP_Alloc();
    RTMP_Init(rtmp);
    //set connection timeout,default 30s
    rtmp->Link.timeout = 10;

	char* rtmpFilePath = "d:\\rtmp.raw";
	rtmp->m_pRTMPFile = fopen(rtmpFilePath,"rb");
	if (!rtmp->m_pRTMPFile)
	{
		RTMP_LogPrintf("Failed to open File :%s\n", rtmpFilePath);
		return FALSE;
	}

	// HKS's live URL
	if(!RTMP_SetupURL(rtmp, "rtmp://live.hkstv.hk.lxdns.com/live/hks"))
    {
        RTMP_Log(RTMP_LOGERROR, "SetupURL Err\n");
        RTMP_Free(rtmp);
        CleanupSockets();
        return -1;
    }
    if (bLiveStream)
    {
        rtmp->Link.lFlags |= RTMP_LF_LIVE;
    }

    //1hour
    RTMP_SetBufferMS(rtmp, 3600 * 1000);

    if(!RTMP_Connect(rtmp, NULL))
    {
        RTMP_Log(RTMP_LOGERROR, "Connect Err\n");
        RTMP_Free(rtmp);
        CleanupSockets();
        return -1;
    }

    if(!RTMP_ConnectStream(rtmp, 0))
    {
        RTMP_Log(RTMP_LOGERROR, "ConnectStream Err\n");
        RTMP_Close(rtmp);
        RTMP_Free(rtmp);
        CleanupSockets();
        return -1;
    }

    while(nRead = RTMP_Read(rtmp, buf, bufsize))
    {
        fwrite(buf, 1, nRead, fp);

        countbufsize += nRead;
        RTMP_LogPrintf("Receive: %5dByte, Total: %5.2fkB\n", nRead, countbufsize * 1.0 / 1024);
    }

    if(fp)
        fclose(fp);

    if(fpPcap)
        fclose(fpPcap);

	if (rtmp->m_pRTMPFile)
	{
		fclose(rtmp->m_pRTMPFile);
	}

    if(buf)
    {
        free(buf);
    }

    if(rtmp)
    {
        RTMP_Close(rtmp);
        RTMP_Free(rtmp);
        CleanupSockets();
        rtmp = NULL;
    }
    return 0;
}
示例#25
0
/*% The main processing routine */
int
main(int argc, char **argv) {
	int c;
	cfg_parser_t *parser = NULL;
	cfg_obj_t *config = NULL;
	const char *conffile = NULL;
	isc_mem_t *mctx = NULL;
	isc_result_t result;
	int exit_status = 0;
	isc_entropy_t *ectx = NULL;
	isc_boolean_t load_zones = ISC_FALSE;
	isc_boolean_t print = ISC_FALSE;

	isc_commandline_errprint = ISC_FALSE;

	while ((c = isc_commandline_parse(argc, argv, "dhjt:pvz")) != EOF) {
		switch (c) {
		case 'd':
			debug++;
			break;

		case 'j':
			nomerge = ISC_FALSE;
			break;

		case 't':
			result = isc_dir_chroot(isc_commandline_argument);
			if (result != ISC_R_SUCCESS) {
				fprintf(stderr, "isc_dir_chroot: %s\n",
					isc_result_totext(result));
				exit(1);
			}
			break;

		case 'p':
			print = ISC_TRUE;
			break;

		case 'v':
			printf(VERSION "\n");
			exit(0);

		case 'z':
			load_zones = ISC_TRUE;
			docheckmx = ISC_FALSE;
			docheckns = ISC_FALSE;
			dochecksrv = ISC_FALSE;
			break;

		case '?':
			if (isc_commandline_option != '?')
				fprintf(stderr, "%s: invalid argument -%c\n",
					program, isc_commandline_option);
		case 'h':
			usage();

		default:
			fprintf(stderr, "%s: unhandled option -%c\n",
				program, isc_commandline_option);
			exit(1);
		}
	}

	if (isc_commandline_index + 1 < argc)
		usage();
	if (argv[isc_commandline_index] != NULL)
		conffile = argv[isc_commandline_index];
	if (conffile == NULL || conffile[0] == '\0')
		conffile = NAMED_CONFFILE;

#ifdef _WIN32
	InitSockets();
#endif

	RUNTIME_CHECK(isc_mem_create(0, 0, &mctx) == ISC_R_SUCCESS);

	RUNTIME_CHECK(setup_logging(mctx, stdout, &logc) == ISC_R_SUCCESS);

	RUNTIME_CHECK(isc_entropy_create(mctx, &ectx) == ISC_R_SUCCESS);
	RUNTIME_CHECK(isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE)
		      == ISC_R_SUCCESS);

	dns_result_register();

	RUNTIME_CHECK(cfg_parser_create(mctx, logc, &parser) == ISC_R_SUCCESS);

	cfg_parser_setcallback(parser, directory_callback, NULL);

	if (cfg_parse_file(parser, conffile, &cfg_type_namedconf, &config) !=
	    ISC_R_SUCCESS)
		exit(1);

	result = bind9_check_namedconf(config, logc, mctx);
	if (result != ISC_R_SUCCESS)
		exit_status = 1;

	if (result == ISC_R_SUCCESS && load_zones) {
		result = load_zones_fromconfig(config, mctx);
		if (result != ISC_R_SUCCESS)
			exit_status = 1;
	}

	if (print && exit_status == 0)
		cfg_print(config, output, NULL);
	cfg_obj_destroy(parser, &config);

	cfg_parser_destroy(&parser);

	dns_name_destroy();

	isc_log_destroy(&logc);

	isc_hash_destroy();
	isc_entropy_detach(&ectx);

	isc_mem_destroy(&mctx);

#ifdef _WIN32
	DestroySockets();
#endif

	return (exit_status);
}
示例#26
0
int
start_sample_rtmp_server(int argc, char **argv)
{
	int nStatus = RD_SUCCESS;
	int i;

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

	char *rtmpStreamingDevice = DEFAULT_HTTP_STREAMING_DEVICE;	// streaming device, default 0.0.0.0
	int nRtmpStreamingPort = 1935;	// port
	char *cert = NULL, *key = NULL;

	RTMP_LogPrintf("RTMP Server %s\n", "AVRemoteControl Build 1.0");
	RTMP_LogPrintf("(c) 2010 Andrej Stepanchuk, Howard Chu; license: GPL\n\n");

	RTMP_debuglevel = RTMP_LOGINFO;

	for (i = 1; i < argc; i++)
	{
		if (!strcmp(argv[i], "-z"))
			RTMP_debuglevel = RTMP_LOGALL;
		else if (!strcmp(argv[i], "-c") && i + 1 < argc)
			cert = argv[++i];
		else if (!strcmp(argv[i], "-k") && i + 1 < argc)
			key = argv[++i];
	}

	if (cert && key)
		sslCtx = RTMP_TLS_AllocServerContext(cert, key);

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

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

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


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

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

	InitSockets();

	// start text UI
	//ThreadCreate(controlServerThread, 0);
	std::thread theThread(controlServerThread);

	// start http streaming
	if ((rtmpServer =
		startStreaming(rtmpStreamingDevice, nRtmpStreamingPort)) == 0)
	{
		RTMP_Log(RTMP_LOGERROR, "Failed to start RTMP server, exiting!");
		return RD_FAILED;
	}
	RTMP_LogPrintf("Streaming on rtmp://%s:%d\n", rtmpStreamingDevice,
		nRtmpStreamingPort);

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

	if (sslCtx)
		RTMP_TLS_FreeServerContext(sslCtx);

	CleanupSockets();

#ifdef _DEBUG
	if (netstackdump != 0)
		fclose(netstackdump);
	if (netstackdump_read != 0)
		fclose(netstackdump_read);
#endif
	return nStatus;
}
示例#27
0
/*% The main processing routine */
int
main(int argc, char **argv) {
	int c;
	cfg_parser_t *parser = NULL;
	cfg_obj_t *config = NULL;
	const char *conffile = NULL;
	isc_mem_t *mctx = NULL;
	isc_result_t result;
	int exit_status = 0;
	isc_entropy_t *ectx = NULL;
	isc_boolean_t load_zones = ISC_FALSE;
	isc_boolean_t print = ISC_FALSE;
	unsigned int flags = 0;

	isc_commandline_errprint = ISC_FALSE;

	/*
	 * Process memory debugging argument first.
	 */
#define CMDLINE_FLAGS "dhjm:t:pvxz"
	while ((c = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
		switch (c) {
		case 'm':
			if (strcasecmp(isc_commandline_argument, "record") == 0)
				isc_mem_debugging |= ISC_MEM_DEBUGRECORD;
			if (strcasecmp(isc_commandline_argument, "trace") == 0)
				isc_mem_debugging |= ISC_MEM_DEBUGTRACE;
			if (strcasecmp(isc_commandline_argument, "usage") == 0)
				isc_mem_debugging |= ISC_MEM_DEBUGUSAGE;
			if (strcasecmp(isc_commandline_argument, "size") == 0)
				isc_mem_debugging |= ISC_MEM_DEBUGSIZE;
			if (strcasecmp(isc_commandline_argument, "mctx") == 0)
				isc_mem_debugging |= ISC_MEM_DEBUGCTX;
			break;
		default:
			break;
		}
	}
	isc_commandline_reset = ISC_TRUE;

	RUNTIME_CHECK(isc_mem_create(0, 0, &mctx) == ISC_R_SUCCESS);

	while ((c = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != EOF) {
		switch (c) {
		case 'd':
			debug++;
			break;

		case 'j':
			nomerge = ISC_FALSE;
			break;

		case 'm':
			break;

		case 't':
			result = isc_dir_chroot(isc_commandline_argument);
			if (result != ISC_R_SUCCESS) {
				fprintf(stderr, "isc_dir_chroot: %s\n",
					isc_result_totext(result));
				exit(1);
			}
			break;

		case 'p':
			print = ISC_TRUE;
			break;

		case 'v':
			printf(VERSION "\n");
			exit(0);

		case 'x':
			flags |= CFG_PRINTER_XKEY;
			break;

		case 'z':
			load_zones = ISC_TRUE;
			docheckmx = ISC_FALSE;
			docheckns = ISC_FALSE;
			dochecksrv = ISC_FALSE;
			break;

		case '?':
			if (isc_commandline_option != '?')
				fprintf(stderr, "%s: invalid argument -%c\n",
					program, isc_commandline_option);
			/* FALLTHROUGH */
		case 'h':
			usage();

		default:
			fprintf(stderr, "%s: unhandled option -%c\n",
				program, isc_commandline_option);
			exit(1);
		}
	}

	if (((flags & CFG_PRINTER_XKEY) != 0) && !print) {
		fprintf(stderr, "%s: -x cannot be used without -p\n", program);
		exit(1);
	}

	if (isc_commandline_index + 1 < argc)
		usage();
	if (argv[isc_commandline_index] != NULL)
		conffile = argv[isc_commandline_index];
	if (conffile == NULL || conffile[0] == '\0')
		conffile = NAMED_CONFFILE;

#ifdef _WIN32
	InitSockets();
#endif

	RUNTIME_CHECK(setup_logging(mctx, stdout, &logc) == ISC_R_SUCCESS);

	RUNTIME_CHECK(isc_entropy_create(mctx, &ectx) == ISC_R_SUCCESS);
	RUNTIME_CHECK(isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE)
		      == ISC_R_SUCCESS);

	dns_result_register();

	RUNTIME_CHECK(cfg_parser_create(mctx, logc, &parser) == ISC_R_SUCCESS);

	cfg_parser_setcallback(parser, directory_callback, NULL);

	if (cfg_parse_file(parser, conffile, &cfg_type_namedconf, &config) !=
	    ISC_R_SUCCESS)
		exit(1);

	result = bind9_check_namedconf(config, logc, mctx);
	if (result != ISC_R_SUCCESS)
		exit_status = 1;

	if (result == ISC_R_SUCCESS && load_zones) {
		result = load_zones_fromconfig(config, mctx);
		if (result != ISC_R_SUCCESS)
			exit_status = 1;
	}

	if (print && exit_status == 0)
		cfg_printx(config, flags, output, NULL);
	cfg_obj_destroy(parser, &config);

	cfg_parser_destroy(&parser);

	dns_name_destroy();

	isc_log_destroy(&logc);

	isc_hash_destroy();
	isc_entropy_detach(&ectx);

	isc_mem_destroy(&mctx);

#ifdef _WIN32
	DestroySockets();
#endif

	return (exit_status);
}
示例#28
0
文件: main.C 项目: dyninst/paradyn
int main(int argc, char **argv) {

    bool sawParadynFlag = false;

#if defined(os_windows)
    // initialize our use of the WinSock library
    InitSockets( __argv[0] );    
#endif

    for( unsigned int i = 1; i < argc; i++ )
    {
        if( strcmp(argv[i], "--debug" ) == 0 )
        {
          xsynch_flag = true;
#if !defined(i386_unknown_nt4_0)
          cout << "tableVisi at sigpause...pid=" << getpid() << endl;
          sigpause(0);
#endif // !defined(i386_unknown_nt4_0)
        }
        else if( strcmp( argv[i], "--paradyn" ) == 0 )
        {
            sawParadynFlag = true;
        }
        else
        {
            Tcl_Panic( "unrecognized argument seen", NULL );
        }
    }

    if( !sawParadynFlag )
    {
        ShowNoSoloVisiMessage( argv[0] );
    }

    // Let Tcl know something about our executable (and do some filesystem-
    // specific initialization).
    //
    // NOTE: this is obligatory with modern versions of Tcl.
    Tcl_FindExecutable( argv[0] );

   mainInterp = Tcl_CreateInterp();
   assert(mainInterp);

#if !defined(i386_unknown_nt4_0)
   if (xsynch_flag) {
      cout << "xsynching..." << endl;
      XSynchronize(Tk_Display(Tk_MainWindow(mainInterp)), 1);
   }
#endif // !defined(i386_unknown_nt4_0)

   if (TCL_OK != Tcl_Init(mainInterp))
      tclpanic(mainInterp, "Could not Tcl_Init");

    // Set argv0 before we do any other Tk program initialization because
    // Tk takes the main window's class and instance name from argv0
    // We set it to "paradyn" instead of "termwin" so that we can 
    // set resources for all paradyn-related windows with the same root.
    Tcl_SetVar( mainInterp,
                "argv0", 
                "paradyn",
                TCL_GLOBAL_ONLY );

   if (TCL_OK != Tk_Init(mainInterp))
      tclpanic(mainInterp, "Could not Tk_Init");

   if (TCL_OK != Dg2_Init(mainInterp))
      tclpanic(mainInterp, "Could not Dg2_Init");

   PDSOCKET visi_sock = visi_Init();
   if (visi_sock < 0)
      Tcl_Panic("failed to initialize w/ visi lib", NULL);

   Tcl_SetVar(mainInterp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);

   // Install our new tcl commands here:
   installTableVisiCommands(mainInterp);

   if (visi_RegistrationCallback(ADDMETRICSRESOURCES,Dg2AddMetricsCallback)!=0)
      Tcl_Panic("Dg2_Init() -- couldn't install ADDMETRICSRESOURCES callback",
        NULL);

   if (visi_RegistrationCallback(DATAVALUES, Dg2NewDataCallback) != 0)
      Tcl_Panic("Dg2_Init() -- couldn't install DATAVALUES callback", NULL);

   if (visi_RegistrationCallback(PARADYNEXITED, Dg2ParadynExitedCallback) != 0)
       panic("Dg2_Init() -- couldn't install PARADYNEXITED callback");

//   if (visi_RegistrationCallback(PHASEDATA, Dg2PhaseDataCallback) != 0)
//      panic("Dg2_Init() -- couldn't install PHASEINFO callback");

	// install a handler to notify us when there is data to be read
	Tcl_Channel visi_chan = 
	  Tcl_MakeTcpClientChannel((ClientData)(Address)(PDDESC)visi_sock);
	Tcl_CreateChannelHandler(visi_chan,
				 TCL_READABLE,
				 (Tcl_FileProc*)visiFdReadableHandler,
				 0);

   // Krishna's tcl2c stuff:
   extern int initialize_tcl_sources(Tcl_Interp *);
   if (TCL_OK != initialize_tcl_sources(mainInterp))
      tclpanic(mainInterp, "tableVisi: could not initialize_tcl_sources");

//if (Tcl_EvalFile(mainInterp, "/p/paradyn/development/tamches/core/visiClients/tableVisi/tcl/tableVisi.tcl") != TCL_OK)
//   tclpanic(mainInterp, "could not open tableVisi.tcl");

   pdLogo::install_fixed_logo("paradynLogo", logo_bits, logo_width, logo_height);
   tcl_cmd_installer createPdLogo(mainInterp, "makeLogo", pdLogo::makeLogoCommand,
				  (ClientData)Tk_MainWindow(mainInterp));

   myTclEval(mainInterp, "initializeTableVisi");

   // Create our main data structure:
   theTableVisi = new tableVisi(mainInterp,
                                Tk_NameToWindow(mainInterp, ".body",
                                Tk_MainWindow(mainInterp)),
                                "lightBlue", // line color
                                "blue", // metric color
                                "black", // metric units color
                                "maroon3", // focus color
                                "black", // cell color
                                "gray", // background color
                                "lightGray", // highlight background color
                                3 // initial # sig figs
                                );
   assert(theTableVisi);

   Tk_MainLoop(); // returns when all tk windows are closed

   delete theTableVisi;
   theTableVisi = NULL;

   return 0;
}