Exemple #1
0
int pmatch_process(const char **Compiled, const char *String, int len, ListNode *Matches, int Flags)
{
//p_ptr points to the pattern from 'Compiled' that's currently being
//tested. s_ptr holds our progress through the string
    const char **p_ptr;
    const char *Start=NULL, *End=NULL;
    int result;
    TPMatch *Match;
    int NoOfItems=0;

    for (p_ptr=Compiled; *p_ptr != NULL; p_ptr++)
    {
        if (pmatch_one(*p_ptr, String, len, &Start, &End, Flags))
        {
            NoOfItems++;
            if (Matches)
            {
                Match=(TPMatch *) calloc(1, sizeof(TPMatch));
                Match->Start=Start;
                Match->End=End;
                ListAddItem(Matches,Match);
            }
        }
    }

    return(NoOfItems);
}
Exemple #2
0
STREAM *ConnectManagerAddClient(char *Host, int Port, int Flags, char *Name, CONNECT_FUNC OnConnect, ONDATA_FUNC OnData)
{
STREAM *S;
TConnectManagerItem *Item;

if (! ConnectManClients) ConnectManClients=ListCreate();

S=STREAMCreate();
if (! STREAMConnectToHost(S,Host,Port,Flags))
{
STREAMClose(S);
return(NULL);
}

Item=(TConnectManagerItem *) calloc(1,sizeof(TConnectManagerItem));
Item->OnConnect=OnConnect;
Item->OnData=OnData;
Item->Data=(void *) S;
Item->Name=CopyStr(Item->Name,Name);
Item->Host=CopyStr(Item->Host,Host);
Item->Port=Port;

if (Item->OnConnect && STREAMIsConnected(S)) Item->OnConnect(Item);

ListAddItem(ConnectManClients,Item);
return(S);
}
int DownloadM3U(char *URL, char *Title, int Flags)
{
char *Tempstr=NULL, *ID=NULL, *Doc=NULL, *ptr;
int Port=0, BytesRead=0, len=0, count=0;
int RetVal=FALSE;
ListNode *Items, *Curr;
int M3UType=M3U_PLAYLIST;
STREAM *Con;

if (Flags & FLAG_DEBUG) fprintf(stderr,"M3U STREAM: %s\n",URL);


Items=ListCreate();
Con=ConnectAndRetryUntilDownload(URL, 0, 0);
if (Con)
{
Tempstr=STREAMReadLine(Tempstr,Con);
while (Tempstr)
{
StripTrailingWhitespace(Tempstr);
StripLeadingWhitespace(Tempstr);

if (Flags & (FLAG_DEBUG2 | FLAG_DEBUG3)) fprintf(stderr,"%s\n",Tempstr);
if (StrLen(Tempstr))
{
	if (strncmp("#EXT-X-STREAM-INF",Tempstr,StrLen("#EXT-X-STREAM-INF"))==0)
	{
			RetVal=M3UStreamInfo(Con,Title,URL,Tempstr,Flags);
			M3UType=M3U_STREAMINFO;
	}
	else if (strncmp("#EXT-X-MEDIA-SEQUENCE",Tempstr,StrLen("#EXT-X-MEDIA-SEQUENCE"))==0) M3UType=M3U_PLAYLIST;
	else if (*Tempstr != '#') 
	{
		if (strncasecmp(Tempstr,"http",4) !=0) 
		{
			Doc=CopyStr(Doc,URL);
			ptr=strrchr(Doc,'/');
			if (ptr) *ptr='\0';
			Doc=MCatStr(Doc,"/",Tempstr,NULL);
		}
		else Doc=CopyStr(Doc,Tempstr);
		ListAddItem(Items,CopyStr(NULL,Doc));
	}
}

Tempstr=STREAMReadLine(Tempstr,Con);
}

STREAMClose(Con);
if (M3UType == M3U_PLAYLIST) RetVal=DownloadStream(URL, Title, Items, Flags);
}

ListDestroy(Items,DestroyString);
DestroyString(Tempstr);
DestroyString(Doc);
DestroyString(ID);


return(RetVal);
}
Exemple #4
0
int FindFilesInPath(const char *File, const char *Path, ListNode *Files)
{
char *Tempstr=NULL, *CurrPath=NULL, *ptr;
int i;
glob_t Glob;

if (*File=='/')
{
	CurrPath=CopyStr(CurrPath,"");
	ptr=""; //so we execute once below
}
else ptr=GetToken(Path,":",&CurrPath,0);
while (ptr)
{
CurrPath=SlashTerminateDirectoryPath(CurrPath);
Tempstr=MCopyStr(Tempstr,CurrPath,File,NULL);

glob(Tempstr,0,0,&Glob);
for (i=0; i < Glob.gl_pathc; i++) ListAddItem(Files,CopyStr(NULL,Glob.gl_pathv[i]));
globfree(&Glob);

ptr=GetToken(ptr,":",&CurrPath,0);
}

DestroyString(Tempstr);
DestroyString(CurrPath);

return(ListSize(Files));
}
Exemple #5
0
TConnectManagerItem *ConnectManagerAddIncoming(STREAM *S, char *Name, ONDATA_FUNC OnData)
{
TConnectManagerItem *Item=NULL;

if (! ConnectManClients) ConnectManClients=ListCreate();

Item=(TConnectManagerItem *) calloc(1,sizeof(TConnectManagerItem));
Item->OnData=OnData;
Item->Data=(void *) S;
Item->Name=CopyStr(Item->Name,Name);

ListAddItem(ConnectManClients,Item);
return(Item);
}
Exemple #6
0
int M3UStreamDownload(STREAM *ManifestCon, const char *URL, const char *Title)
{
STREAM *Con=NULL;
char *Tempstr=NULL, *BasePath=NULL, *Line=NULL;
const char *ptr;
ListNode *Segments, *Curr;
int result;
double BytesRead=0;

Segments=ListCreate();
ptr=strrchr(URL, '/');
if (ptr)
{
BasePath=CopyStrLen(BasePath, URL, ptr - URL);
	Line=STREAMReadLine(Line,ManifestCon);
	while (Line)
	{
		StripLeadingWhitespace(Line);
		StripTrailingWhitespace(Line);
		
		if (*Line != '#')
		{
			Tempstr=MCopyStr(Tempstr, BasePath, "/", Line, NULL);
			ListAddItem(Segments, CopyStr(NULL, Tempstr));
		}
	Line=STREAMReadLine(Line,ManifestCon);
	}

	OpenOutputFiles(Title, URL, &BytesRead);
	Tempstr=SetStrLen(Tempstr,BUFSIZ);
	Curr=ListGetNext(Segments);
	while (Curr)
	{
		Con=ConnectAndRetryUntilDownload(Curr->Item, 0, 0);
		if (Con)
		{
		TransferItem(Con, Title, URL, "m3u8-stream", 0, 0, &BytesRead, FALSE);
		STREAMClose(Con);
		}

	Curr=ListGetNext(Curr);
	}
	CloseOutputFiles();
}

ListDestroy(Segments, DestroyString);
DestroyString(Tempstr);
DestroyString(BasePath);
DestroyString(Line);
}
Exemple #7
0
void AddIncludeExclude(HashratCtx *Ctx, int Type, const char *Item)
{
ListNode *Node;

//if we get given an include with no previous excludes, then 
//set CTX_EXCLUDE as the default
if (! IncludeExclude)
{
  IncludeExclude=ListCreate();
  if (Type==CTX_INCLUDE) Ctx->Flags |= CTX_EXCLUDE;
}

Node=ListAddItem(IncludeExclude, CopyStr(NULL, Item));
Node->ItemType=Type;
}
Exemple #8
0
int ConnectManagerAddTimer(int Secs, char *Name, ONTIMER_FUNC OnTime, void *Data)
{
TConnectManagerItem *Item;

if (! Timers) Timers=ListCreate();

Item=(TConnectManagerItem *) calloc(1,sizeof(TConnectManagerItem));
Item->OnData=(ONDATA_FUNC) OnTime;
Item->Name=CopyStr(Item->Name,Name);
Item->TimerVal=Secs;
Item->LastTimerFire=time(NULL);
Item->Data=Data;

ListAddItem(Timers,Item);
return(TRUE);
}
Exemple #9
0
int ConnectManagerAddServer(int sock, char *Name,  CONNECT_FUNC OnConnect, ONDATA_FUNC OnData)
{
TConnectManagerItem *Item;

if (! ConnectManServers) ConnectManServers=ListCreate();

if (sock==-1) return(FALSE);

Item=(TConnectManagerItem *) calloc(1,sizeof(TConnectManagerItem));
Item->OnConnect=OnConnect;
Item->OnData=OnData;
Item->Data=(void *) STREAMFromFD(sock);
Item->Name=CopyStr(Item->Name,Name);

ListAddItem(ConnectManServers,Item);
return(TRUE);
}
Exemple #10
0
int DownloadASX(char *URL, char *Title, int Flags)
{
char *Tempstr=NULL, *Token=NULL, *ptr;
int Port=0, len=0;
int RetVal=FALSE;
STREAM *Con=NULL;
ListNode *Items;

if (Flags & FLAG_DEBUG) fprintf(stderr,"ASX STREAM: %s\n",URL);

Items=ListCreate();
Con=ConnectAndRetryUntilDownload(URL, 0, 0);
if (Con)
{
Tempstr=STREAMReadLine(Tempstr,Con);
while (Tempstr)
{
StripTrailingWhitespace(Tempstr);
StripLeadingWhitespace(Tempstr);

  if (Flags & (FLAG_DEBUG2 | FLAG_DEBUG3)) fprintf(stderr,"%s\n",Tempstr);
	if (StrLen(Tempstr) && (strncasecmp(Tempstr,"<Ref href",9)==0))
	{
		ptr=GetToken(Tempstr,"=",&Token,0);
		while (isspace(*ptr)) ptr++;
		if (*ptr=='"') ptr++;
		ptr=GetToken(ptr,"\"",&Token,0);

		ListAddItem(Items,CopyStr(NULL,Token));
	}

Tempstr=STREAMReadLine(Tempstr,Con);
}

STREAMClose(Con);

RetVal=DownloadStream(URL, Title, Items, Flags);
}
	
ListDestroy(Items,DestroyString);
DestroyString(Tempstr);


return(RetVal);
}
Exemple #11
0
int CheckForKeyboardInput()
{
char *Tempstr=NULL;
int result=FALSE;

if (STREAMCheckForBytes(StdIn))
{
  Tempstr=STREAMReadLine(Tempstr,StdIn);
  StripTrailingWhitespace(Tempstr);
  if (StrLen(Tempstr))
  {
    ListAddItem(DownloadQueue,CopyStr(NULL,Tempstr));
    if (! (Flags & FLAG_QUIET)) fprintf(stderr,"\r\nQUEUED: %s\n",Tempstr);
    result=TRUE;
  }
}
DestroyString(Tempstr);

return(result);
}
CTlvEsM8Sta * CreateTlvEsM8Sta(bool isWirelessWPS = false )
{
	char    *cp_data;
    uint16    data16;
	uint8 mac[] = { 0, 1, 2, 3, 4, 5 };

    CTlvEsM8Sta * mp_tlvEsM8Sta = new CTlvEsM8Sta();

	if (isWirelessWPS) { // only include a wireless Credential if run in wireless mode.
		// credential
		CTlvCredential *p_tlvCred = new CTlvCredential();
		// Fill in credential items
		// nwIndex
		p_tlvCred->nwIndex.Set( WSC_ID_NW_INDEX, 1 );
		// ssid
		data16 = 3;
		p_tlvCred->ssid.Set( WSC_ID_SSID, (uint8 *)"foo", data16 );
		// authType
		data16 = WSC_AUTHTYPE_WPAPSK;
		p_tlvCred->authType.Set( WSC_ID_AUTH_TYPE, data16 );
		// encrType
		data16 = WSC_ENCRTYPE_TKIP;
		p_tlvCred->encrType.Set( WSC_ID_ENCR_TYPE, data16 );
		// nwKeyIndex
		p_tlvCred->nwKeyIndex.Set( WSC_ID_NW_KEY_INDEX, 1 );
		// nwKey
		p_tlvCred->nwKey.Set( WSC_ID_NW_KEY, "foo", 3);
		// macAddr
		data16 = SIZE_MAC_ADDR;
		p_tlvCred->macAddr.Set( WSC_ID_MAC_ADDR, mac, data16 );
		ListAddItem( mp_tlvEsM8Sta->credential, p_tlvCred );
	}

    // New pwd
    // TODO

    // PwdId
    // TODO

	return mp_tlvEsM8Sta;
} // CreateTlvEsM8Sta
Exemple #13
0
int DownloadPLS(char *URL, char *Title, int Flags)
{
char *Tempstr=NULL, *Token=NULL, *ptr;
int Port=0, len=0;
STREAM *Con=NULL;
int RetVal=FALSE;
ListNode *Items;

if (Flags & FLAG_DEBUG) fprintf(stderr,"PLS STREAM: %s\n",URL);

Items=ListCreate();
Con=ConnectAndRetryUntilDownload(URL, 0, 0);
if (Con)
{
Tempstr=STREAMReadLine(Tempstr,Con);
while (Tempstr)
{
StripTrailingWhitespace(Tempstr);
StripLeadingWhitespace(Tempstr);

  if (Flags & (FLAG_DEBUG2 | FLAG_DEBUG3)) fprintf(stderr,"%s\n",Tempstr);
if (StrLen(Tempstr))
{
	ptr=GetToken(Tempstr,"=",&Token,0);
	if (strncmp(Token,"File",4)==0) ListAddItem(Items,CopyStr(NULL,ptr));
}

Tempstr=STREAMReadLine(Tempstr,Con);
}

//Close the Connection and Download the next stage
STREAMClose(Con);

RetVal=DownloadStream(URL, Title, Items, Flags);
}
	
ListDestroy(Items,DestroyString);
DestroyString(Tempstr);

return(RetVal);
}
Exemple #14
0
void HTTPParseCookie(HTTPInfoStruct *Info, char *Str)
{
	char *startptr, *endptr;
	char *Tempstr=NULL;
	ListNode *Curr;
	int len;

	startptr=Str;
	while (*startptr==' ') startptr++;

	endptr=strchr(startptr,';');
	if (endptr==NULL) endptr=startptr+strlen(Str);
//	if (( *endptr==';') || (*endptr=='\r') ) endptr--;

	Tempstr=CopyStrLen(Tempstr,startptr,endptr-startptr);

	Curr=ListGetNext(Cookies);
	endptr=strchr(Tempstr,'=');
	len=endptr-Tempstr;
	len--;

	while (Curr !=NULL)
	{
		if (strncmp(Curr->Item,Tempstr,len)==0)
		{
			Curr->Item=CopyStr(Curr->Item,Tempstr);
			DestroyString(Tempstr);
			return;
		}
		Curr=ListGetNext(Curr);
	}

	if (! Cookies) Cookies=ListCreate();
	ListAddItem(Cookies,(void *)CopyStr(NULL,Tempstr));

DestroyString(Tempstr);
}
Exemple #15
0
int pmatch_process(char **Compiled, char *String, int len, ListNode *Matches, int iFlags)
{
//p_ptr points to the pattern from 'Compiled' that's currently being
//tested. s_ptr holds our progress through the string
char **p_ptr;
char *s_ptr, *s_end, *tp_ptr, *ts_ptr;
char *Start=NULL, *End=NULL;
int result, Flags;
TPMatch *Match;
int NoOfItems=0;

Flags=iFlags &= ~PMATCH_SUBSTR;
s_end=String+len;
//We handle PMATCH substr in this function
for (s_ptr=String; s_ptr < s_end; s_ptr++)
{
	for (p_ptr=Compiled; *p_ptr != NULL; p_ptr++)
	{
		result=pmatch_process_one(*p_ptr, s_ptr, s_end-s_ptr, &Start, &End, Flags);
		if (result==MATCH_ONE) 
		{
			NoOfItems++;
			if (Matches)
			{
				Match=(TPMatch *) calloc(1, sizeof(TPMatch));
				Match->Start=Start;
				Match->End=End;
				ListAddItem(Matches,Match);
			}
		}
	}
	Flags |= PMATCH_NOTSTART;
}

return(NoOfItems);
}
Exemple #16
0
int UpdateNativeFile(char *Path, char *Name, char *PassType, char *Pass, char *HomeDir, char *RealUser, char *Args)
{
STREAM *S;
ListNode *Entries;
char *Tempstr=NULL, *Token=NULL, *Salt=NULL;
ListNode *Curr;
int RetVal=ERR_FILE;


Entries=ListCreate();
S=STREAMOpenFile(Settings.AuthPath,SF_RDONLY);

if (S)
{
	Tempstr=STREAMReadLine(Tempstr,S);
	while (Tempstr)
	{
		GetToken(Tempstr,":",&Token,0);

		if (strcmp(Token,Name) !=0) ListAddItem(Entries,CopyStr(NULL,Tempstr));	
	
		Tempstr=STREAMReadLine(Tempstr,S);
	}
	STREAMClose(S);
}


S=STREAMOpenFile(Settings.AuthPath,SF_WRONLY| SF_CREAT | SF_TRUNC);
if (S)
{
	//First copy all other entries
	Curr=ListGetNext(Entries);
	while (Curr)
	{
		STREAMWriteLine((char *) Curr->Item,S);
		Curr=ListGetNext(Curr);
	}
	STREAMFlush(S);


	if (strcmp(PassType,"delete")==0)
	{
		//Don't bother to write new entry, effectively deleting user
	}
	else
	{
		//WriteNew Entry
		if (strcmp(PassType,"plain")==0)
		{
			Token=CopyStr(Token,Pass);
			Tempstr=MCopyStr(Tempstr,Name,":",PassType,":",Token,":",RealUser,":",HomeDir,":",Args,"\n",NULL);
		}
		else if (strcmp(PassType,"htdigest-md5")==0)
		{
			//Calc 'HA1'
			Tempstr=MCopyStr(Tempstr,Name,":",Settings.AuthRealm,":",Pass,NULL);
			HashBytes(&Token,"md5",Tempstr,StrLen(Tempstr),ENCODE_HEX);
			Tempstr=MCopyStr(Tempstr,Name,":",PassType,":",Token,":",RealUser,":",HomeDir,":",Args,"\n",NULL);
		}
		else
		{
			GenerateRandomBytes(&Salt,24, ENCODE_BASE64);
			Tempstr=MCopyStr(Tempstr,Name,":",Pass,":",Salt,NULL);
			HashBytes(&Token, PassType, Tempstr, StrLen(Tempstr), ENCODE_BASE64);
			Tempstr=MCopyStr(Tempstr,Name,":",PassType,":",Salt,"$",Token,":",RealUser,":",HomeDir,":",Args,"\n",NULL);
		}
	
		STREAMWriteLine(Tempstr,S);

		SwitchUser(RealUser);
		mkdir(HomeDir,0770);
	}

	STREAMClose(S);
	RetVal=ERR_OKAY;
}
else RetVal=ERR_FILE;

DestroyString(Tempstr);
DestroyString(Token);
DestroyString(Salt);

ListDestroy(Entries,DestroyString);

return(RetVal);
}
void CTlvEsM8Sta::parse(BufferObj &theBuf, BufferObj &authKey, bool allocate, bool isWirelessWPS)
{
    //There should be at least 1 credential TLV
    CTlvCredential *pCredential;

	if (isWirelessWPS) { // Credential(s) are processed only when doing wireless WPS
		pCredential = new CTlvCredential();
		pCredential->parse(theBuf, allocate);
		ListAddItem(credential, pCredential);

		//now parse any additional credential TLVs
		while(WSC_ID_CREDENTIAL == theBuf.NextType())
		{
			pCredential = new CTlvCredential();
			pCredential->parse(theBuf, allocate);
			ListAddItem(credential, pCredential);
		}
	} 
	// Note that all Credentials are ignored if not doing wireless WPS.  Also, if a Credential
	// is present in this case, then the new password attribute will be ignored as well, because 
	// the Credential attribute will be next to be parsed in the message, which will cause the code 
	// to drop down to just skipping all attributes until the key wrap authenticator.

    if(WSC_ID_NEW_PWD == theBuf.NextType())
    {
       //If the New Password TLV is included, the Device password ID is required
        new_pwd = CTlvNewPwd(WSC_ID_NEW_PWD, theBuf, SIZE_64_BYTES, allocate);
        pwdId = CTlvDevicePwdId(WSC_ID_DEVICE_PWD_ID, theBuf);
    }

	// Skip attributes until the KeyWrapAuthenticator
	while(WSC_ID_KEY_WRAP_AUTH != theBuf.NextType())
    {
        //advance past the TLV
        uint8 *Pos = theBuf.Advance( sizeof(S_WSC_TLV_HEADER) + 
							WscNtohs(*(uint16 *)(theBuf.Pos()+sizeof(uint16))) );
        
        //If Advance returned NULL, it means there's no more data in the
        //buffer. This is an error.
        if(Pos == NULL)
            throw RPROT_ERR_REQD_TLV_MISSING;
    }

	uint8 * startOfAuthenticator = theBuf.Pos();
    keyWrapAuth = CTlvAuthenticator(WSC_ID_KEY_WRAP_AUTH, theBuf, SIZE_64_BITS);

    //validate the mac
    uint8 dataMac[BUF_SIZE_256_BITS];

    //calculate the hmac of the data (data only, not the last auth TLV)
    if(HMAC(EVP_sha256(), authKey.GetBuf(), SIZE_256_BITS, theBuf.GetBuf(),
            startOfAuthenticator - theBuf.GetBuf(), 
            dataMac, NULL) == NULL)
    {
        TUTRACE((TUTRACE_ERR, "RPROTO: HMAC failed\n"));
        throw RPROT_ERR_CRYPTO;
    }

    //compare it against the received hmac
    if(memcmp(dataMac, keyWrapAuth.Value(), SIZE_64_BITS) != 0)
    {
        TUTRACE((TUTRACE_ERR, "RPROTO: HMAC results don't match\n"));
        throw RPROT_ERR_INVALID_VALUE;
    }
}
void CTlvEsM8Ap::parse(BufferObj &theBuf, BufferObj &authKey, bool allocate)
{
    CTlvNwKeyIndex  *keyIndex;
    CTlvNwKey        *key;

    //NW Index is optional
    if(WSC_ID_NW_INDEX == theBuf.NextType())
        nwIndex = CTlvNwIndex(WSC_ID_NW_INDEX, theBuf);

    ssid  = CTlvSsid(WSC_ID_SSID, theBuf, SIZE_32_BYTES, allocate);
    authType = CTlvAuthType(WSC_ID_AUTH_TYPE, theBuf);
    encrType = CTlvEncrType(WSC_ID_ENCR_TYPE, theBuf);
   
    //The next field is network key index. There are two possibilities:
    //1. The TLV is omitted, in which case, there is only 1 network key
    //2. The TLV is present, in which case, there may be 1 or more network keys
    
    //condition 1. If the next field is a network Key, the index TLV was omitted
    if(WSC_ID_NW_KEY == theBuf.NextType())
    {
        key = new CTlvNwKey(WSC_ID_NW_KEY, theBuf, SIZE_64_BYTES, allocate);
        if(!key)
            throw WSC_ERR_OUTOFMEMORY;
        ListAddItem(nwKey, key);
    }
    else
    {
        //condition 2. any other possibities are illegal & will be caught later
        while(WSC_ID_NW_KEY_INDEX == theBuf.NextType())
        {
            keyIndex = new CTlvNwKeyIndex(WSC_ID_NW_KEY_INDEX, theBuf);
            if(!keyIndex)
                throw WSC_ERR_OUTOFMEMORY;
            ListAddItem(nwKeyIndex, keyIndex);

            key = new CTlvNwKey(WSC_ID_NW_KEY, theBuf, SIZE_64_BYTES, allocate);
            if(!key)
                throw WSC_ERR_OUTOFMEMORY;
            ListAddItem(nwKey, key);
        }//while
    }//else

    macAddr = CTlvMacAddr(WSC_ID_MAC_ADDR, theBuf, SIZE_6_BYTES, allocate);

    if(WSC_ID_NEW_PWD == theBuf.NextType())
    {
       //If the New Password TLV is included, the Device password ID is required
        new_pwd = CTlvNewPwd(WSC_ID_NEW_PWD, theBuf, SIZE_64_BYTES, allocate);
        pwdId = CTlvDevicePwdId(WSC_ID_DEVICE_PWD_ID, theBuf);
    }

    //skip Permitted Config Methods field.
    if(WSC_ID_PERM_CFG_METHODS == theBuf.NextType())
    {
        //advance past the TLV
        theBuf.Advance( sizeof(S_WSC_TLV_HEADER) + 
                        WscNtohs(*(uint16 *)(theBuf.Pos()+sizeof(uint16))) );
    }

	// Skip attributes until the KeyWrapAuthenticator
	while(WSC_ID_KEY_WRAP_AUTH != theBuf.NextType())
    {
        //advance past the TLV
        uint8 *Pos = theBuf.Advance( sizeof(S_WSC_TLV_HEADER) + 
							WscNtohs(*(uint16 *)(theBuf.Pos()+sizeof(uint16))) );
        
        //If Advance returned NULL, it means there's no more data in the
        //buffer. This is an error.
        if(Pos == NULL)
            throw RPROT_ERR_REQD_TLV_MISSING;
    }

	uint8 * startOfAuthenticator = theBuf.Pos();
    keyWrapAuth = CTlvAuthenticator(WSC_ID_KEY_WRAP_AUTH, theBuf, SIZE_64_BITS);

    //validate the mac
    uint8 dataMac[BUF_SIZE_256_BITS];

    //calculate the hmac of the data (data only, not the last auth TLV)
    if(HMAC(EVP_sha256(), authKey.GetBuf(), SIZE_256_BITS, theBuf.GetBuf(),
            startOfAuthenticator - theBuf.GetBuf(), 
            dataMac, NULL) == NULL)
    {
        TUTRACE((TUTRACE_ERR, "RPROTO: HMAC failed\n"));
        throw RPROT_ERR_CRYPTO;
    }

    //compare it against the received hmac
    if(memcmp(dataMac, keyWrapAuth.Value(), SIZE_64_BITS) != 0)
    {
        TUTRACE((TUTRACE_ERR, "RPROTO: HMAC results don't match\n"));
        throw RPROT_ERR_INVALID_VALUE;
    }
}
Exemple #19
0
int UpdateNativeFile(const char *Path, const char *Name, const char *iPassType, const char *Pass, const char *iHomeDir, const char *iRealUser, const char *iArgs)
{
STREAM *S;
ListNode *Entries;
char *Tempstr=NULL, *Token=NULL, *ptr;
char *PassType=NULL, *HomeDir=NULL, *RealUser=NULL, *Args=NULL, *Salt=NULL;
ListNode *Curr;
int RetVal=ERR_FILE;

Entries=ListCreate();
S=STREAMOpenFile(Path,O_RDONLY);

if (S)
{
	Tempstr=STREAMReadLine(Tempstr,S);
	while (Tempstr)
	{
		ptr=GetToken(Tempstr,":",&Token,0);

		if (strcmp(Token,Name) !=0) ListAddItem(Entries,CopyStr(NULL,Tempstr));	
		else 
		{
			StripTrailingWhitespace(Tempstr);
			ptr=GetToken(ptr,":",&PassType,0);
			ptr=GetToken(ptr,":",&Salt,0);
			ptr=GetToken(ptr,":",&Token,0);
			ptr=GetToken(ptr,":",&RealUser,0);
			ptr=GetToken(ptr,":",&HomeDir,0);
			ptr=GetToken(ptr,":",&Args,0);
		}
	
		Tempstr=STREAMReadLine(Tempstr,S);
	}
	STREAMClose(S);
}

if (iPassType) PassType=CopyStr(PassType,iPassType);
if (iHomeDir) HomeDir=CopyStr(HomeDir,iHomeDir);
if (iRealUser) RealUser=CopyStr(RealUser,iRealUser);
if (iArgs) Args=CopyStr(Args,iArgs);


S=STREAMOpenFile(Path,O_WRONLY| O_CREAT | O_TRUNC);
if (S)
{
	//First copy all other entries
	Curr=ListGetNext(Entries);
	while (Curr)
	{
		STREAMWriteLine((char *) Curr->Item,S);
		Curr=ListGetNext(Curr);
	}
	STREAMFlush(S);


	if (strcmp(PassType,"delete")==0)
	{
		//Don't bother to write new entry, effectively deleting user
	}
	else //WriteNew Entry
	{
		//Do this or else HashBytes appends
		Token=CopyStr(Token,"");
		if (strcmp(PassType,"plain") == 0) Token=CopyStr(Token,Pass);
		else if (strcmp(PassType,"challenge") == 0) Token=CopyStr(Token,Pass);
		else 
		{
		  //Generate a new salt
			GenerateRandomBytes(&Salt,20,ENCODE_HEX);
			Tempstr=MCopyStr(Tempstr,Name,Salt,Pass,NULL);
			HashBytes(&Token, PassType, Tempstr, StrLen(Tempstr), ENCODE_HEX);
		}
		Tempstr=MCopyStr(Tempstr,Name,":",PassType,":",Salt,":",Token,":",RealUser,":",HomeDir,":",Args,"\n",NULL);
	
		STREAMWriteLine(Tempstr,S);
	}

	STREAMClose(S);
	RetVal=ERR_OKAY;
}

DestroyString(Args);
DestroyString(Salt);
DestroyString(HomeDir);
DestroyString(RealUser);
DestroyString(PassType);
DestroyString(Tempstr);
DestroyString(Token);
ListDestroy(Entries,DestroyString);

return(RetVal);
}
void RunTelnetSession(TSession *Session)
{
STREAM *Local, *S;
char *Tempstr=NULL;
int result, fd;
ListNode *Streams;
struct passwd *pwent;
struct group *grent;
struct timeval tv;
time_t Duration, Start, Now, LastActivity;

time(&Start);
LastActivity=Start;
Streams=ListCreate();
ListAddItem(Streams,Session->S);

//if '-real-user' was specified on the command-line, then this overrides
//anything read from password files
if (Settings.Flags & FLAG_FORCE_REALUSER)
{
	Session->RealUser=CopyStr(Session->RealUser,Settings.RealUser);
}

//Get User Details before we chroot! 
if (StrLen(Session->RealUser))
{
    pwent=getpwnam(Session->RealUser);
		if (! pwent)
		{
			syslog(Settings.InfoLogLevel,"Failed to lookup RealUser '%s' for user '%s'",Session->RealUser,Session->User);
			exit(1);
		}
		Session->RealUserUID=pwent->pw_uid;
		Session->GroupID=pwent->pw_gid;
}


//if '-shell' was specified on the command-line, then this overrides
//anything read from password files
if (Settings.Flags & FLAG_FORCE_SHELL)
{
	Session->Shell=CopyStr(Session->Shell,Settings.RealUser);
}


if (Settings.Flags & FLAG_DYNHOME)
{
	Session->HomeDir=SessionSubstituteVars(Session->HomeDir,Settings.DynamicHomeDir,Session);
	Session->HomeDir=SlashTerminateDirectoryPath(Session->HomeDir);
	MakeDirPath(Session->HomeDir,0777);
}

//CD to the user's home directory
if (StrLen(Session->HomeDir)) 
{
	chdir(Session->HomeDir);
}

DoBindMounts(Settings.BindMounts,0);

//This login script allows setting up any aspects of the environment before we launch the shell. For instance it 
//might be used to copy files into the chroot environment before chrooting
if (StrLen(Settings.LoginScript)) system(Settings.LoginScript);


//LAUNCH THE SHELL FUNCTION!!! This launches the program that the telnet user is 'speaking' to.
//If chhome is active, then it will be chrooted into the user's home directory


PseudoTTYSpawnFunction(&fd, LaunchPtyFunc, Session,  TTYFLAG_CANON | TTYFLAG_ECHO | TTYFLAG_CRLF | TTYFLAG_LFCR | TTYFLAG_IGNSIG);
Local=STREAMFromFD(fd);
STREAMSetTimeout(Local,0);


//Might as well chroot on this side of the pipe too, unless we have a 'LogoutScript'
//Logout scripts exist to allow copying stuff back out of the chroot when the session is
//finished. We can't do this if we chroot this side as well as the 'shell' side
if (
		(! StrLen(Settings.LogoutScript)) &&
		(Settings.Flags & FLAG_CHHOME) 
	) chroot(".");

//DON'T SWITCH USER. NEED root TO UNBIND MOUNTS
//if (setreuid(Session->RealUserUID,Session->RealUserUID) !=0) exit(1);

ListAddItem(Streams,Local);


Tempstr=SetStrLen(Tempstr,4096);
while (1)
{
	if (Settings.IdleTimeout) tv.tv_sec=Settings.IdleTimeout;
	else tv.tv_sec=3600 * 24;
  S=STREAMSelect(Streams,&tv);
	time(&Now);
  if (S)
  {
    if (S==Session->S)
		{
			result=TelnetReadBytes(Session->S, Tempstr, 4096, TNRB_NONBLOCK);
			if (result ==-1) break;
			STREAMWriteBytes(Local,Tempstr,result);
		}
    else 
		{
			result=STREAMReadBytes(Local,Tempstr,4096);
			if (result < 0) break;
			STREAMWriteBytes(Session->S,Tempstr,result);

    if (result < 0) break;
		}
		if (Settings.Flags & FLAG_WINSIZE) SetWindowSize(Session->S->out_fd);
		LastActivity=Now;
  }

	
	if ((Settings.IdleTimeout > 0) && ((Now - LastActivity) > Settings.IdleTimeout)) break;
}

if (StrLen(Settings.LogoutScript)) system(Settings.LogoutScript);
if (Settings.Flags & FLAG_UNMOUNT) UndoBindMounts(Settings.BindMounts, 0);
if (Settings.Flags & FLAG_DYNHOME) rmdir(Session->HomeDir);

Duration=time(NULL) - Start;
syslog(Settings.InfoLogLevel,"%s@%s logged out after %d secs",Session->User,Session->ClientIP, Duration);

STREAMClose(Session->S);
STREAMClose(Local);
DestroyString(Tempstr);
}
Exemple #21
0
main(int argc, char *argv[])
{
ListNode *Curr, *Next;
int OverrideType=TYPE_NONE;
char *Tempstr=NULL;
int result;

//HTTPSetFlags(HTTP_NOCOMPRESS);
StdIn=STREAMFromFD(0);
STREAMSetTimeout(StdIn,0);
ParseEnvironmentVariables();

DownloadQueue=ListCreate();
Tempstr=MCopyStr(Tempstr,"Movgrab ",Version,NULL);
HTTPSetUserAgent(Tempstr);
FormatPreference=CopyStr(FormatPreference,"mp4,flv,webm,m4v,mov,mpg,mpeg,wmv,avi,3gp,reference,mp3,m4a,wma,m3u8,m3u8-stream");
AddOutputFile("", TRUE);

ParseCommandLine(argc, argv, DownloadQueue, &OverrideType);
CheckSettings();
if (StrLen(Proxy)) 
{
	if (! SetGlobalConnectionChain(Proxy))
	{
		printf("ERROR: Failed to set proxy settings to '%s'\n",Proxy);
		exit(1);
	}
}



if (Flags & FLAG_PRINT_USAGE) PrintUsage();
else if (Flags & FLAG_PRINT_VERSION) PrintVersion();
else if (! (Flags & FLAG_STDIN))
{
	if (ListSize(DownloadQueue)==0) PrintUsage();
}


while (1)
{
	if ((Flags & FLAG_STDIN) && (ListSize(DownloadQueue)==0) )
	{
		Tempstr=STREAMReadLine(Tempstr,StdIn);
		StripTrailingWhitespace(Tempstr);
		ListAddItem(DownloadQueue,CopyStr(NULL,Tempstr));
	}

	Curr=ListGetNext(DownloadQueue);
	while (Curr)
	{
		if (Flags & FLAG_TEST_SITES)
		{
			fprintf(stderr,"Checking %-20s ",Curr->Tag);
			fflush(NULL);
		}


		result=GrabMovie((char *) Curr->Item,OverrideType);
		Next=ListGetNext(Curr); //must do this after grab movie
																//incase more items added while grabbing

			if (Flags & FLAG_TEST_SITES) 
			{
				if (result) fprintf(stderr," okay\n");
				else fprintf(stderr," BROKEN\n");
			}
			
		ListDeleteNode(Curr);

		Curr=Next;
	}

	if (Flags & FLAG_TEST_SITES) break;
	if (! (Flags & FLAG_STDIN)) break;
}

}
Exemple #22
0
void ParseCommandLine(int argc, char *argv[], ListNode *DL_List, int *OverrideType)
{
int i,j, DebugLevel=0;
char *ptr;

ProgName=CopyStr(ProgName,argv[0]);
CmdLine=argv[0];


for (i=1; i < argc; i++)
{
	if (strcmp(argv[i],"-p")==0) Proxy=CopyStr(Proxy,argv[++i]);
	else if (strcmp(argv[i],"-proxy")==0) Proxy=CopyStr(Proxy,argv[++i]);
	else if (strcmp(argv[i],"-a")==0)
	{
			ptr=GetToken(argv[++i],":",&Username,0);
			ptr=GetToken(ptr,":",&Password,0);
	}
	else if (strcmp(argv[i],"-v")==0)
	{
		DebugLevel++;
	}
	else if (strcmp(argv[i],"-o")==0)
	{
		i++;
		AddOutputFile(argv[i], TRUE);
		if (strcmp(argv[i],"-")==0) Flags |= FLAG_STDOUT;
	}
	else if (strcmp(argv[i],"+o")==0)
	{
		i++;
		AddOutputFile(argv[i], FALSE);
		if (strcmp(argv[i],"-")==0) Flags |= FLAG_STDOUT;
	}
	else if (strcmp(argv[i],"-n")==0)
	{
		ItemSelectionArg=CopyStr(ItemSelectionArg,argv[++i]);
	}
	else if (strcmp(argv[i],"-t")==0) *OverrideType=ParseType(argv[++i]);
	else if (strcmp(argv[i],"-f")==0) FormatPreference=CopyStr(FormatPreference,argv[++i]);
	else if (strcmp(argv[i],"-q")==0) Flags |= FLAG_QUIET;
	else if (strcmp(argv[i],"-b")==0) Flags |= FLAG_BACKGROUND;
	else if (strcmp(argv[i],"-r")==0) Flags |= FLAG_RESUME;
	else if (strcmp(argv[i],"-x")==0) Flags |= FLAG_PORN;
	else if (strcmp(argv[i],"-T")==0) Flags |= FLAG_TEST;
	else if (strcmp(argv[i],"-w")==0) Flags |= FLAG_STDIN;
	else if (strcmp(argv[i],"-dt")==0) DisplayTitleWidth=atoi(argv[++i]);
	else if (strcmp(argv[i],"-st")==0) STREAMTimeout=atoi(argv[++i]);
	else if (strcmp(argv[i],"-P")==0) Player=CopyStr(Player,argv[++i]);
	else if (strcmp(argv[i],"-Pp")==0) PlayerLaunchPercent=atoi(argv[++i]);
	else if (strcmp(argv[i],"-?")==0) Flags |= FLAG_PRINT_USAGE;
	else if (strcmp(argv[i],"-h")==0) Flags |= FLAG_PRINT_USAGE;
	else if (strcmp(argv[i],"-help")==0) Flags |= FLAG_PRINT_USAGE;
	else if (strcmp(argv[i],"--help")==0) Flags |= FLAG_PRINT_USAGE;
	else if (strcmp(argv[i],"-version")==0) Flags |= FLAG_PRINT_VERSION;
	else if (strcmp(argv[i],"--version")==0) Flags |= FLAG_PRINT_VERSION;
	else if (strcmp(argv[i],"-test-sites")==0) 
	{
		Flags |= FLAG_TEST_SITES | FLAG_QUIET;
		for (j=1; TestLinks[j] !=NULL; j++)
		{
		if (StrLen(TestLinks[j])) ListAddNamedItem(DL_List,DownloadTypes[j],CopyStr(NULL,TestLinks[j]));
			
		}
		ItemSelectionArg=CopyStr(ItemSelectionArg,"0");
	}
	else
	{
		ListAddItem(DL_List,CopyStr(NULL,argv[i]));
	}	

}


if (Flags & FLAG_BACKGROUND) 
{
Flags |= FLAG_QUIET;
demonize();
}

if (Flags & FLAG_QUIET) DebugLevel=0;

if (DebugLevel==1) Flags |= FLAG_DEBUG1;
if (DebugLevel==2) Flags |= FLAG_DEBUG2;
if (DebugLevel > 2) Flags |= FLAG_DEBUG3;
}