Beispiel #1
0
int CDataFileWriter::Finish()
{
	if(!m_File) return 1;

	int ItemSize = 0;
	int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize;
	int DataSize = 0;
	CDatafileHeader Header;

	// we should now write this file!
	if(DEBUG)
		dbg_msg("datafile", "writing");

	// calculate sizes
	for(int i = 0; i < m_NumItems; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "item=%d size=%d (%d)", i, m_pItems[i].m_Size, int(m_pItems[i].m_Size+sizeof(CDatafileItem)));
		ItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem);
	}


	for(int i = 0; i < m_NumDatas; i++)
		DataSize += m_pDatas[i].m_CompressedSize;

	// calculate the complete size
	TypesSize = m_NumItemTypes*sizeof(CDatafileItemType);
	HeaderSize = sizeof(CDatafileHeader);
	OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes
	FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize;
	SwapSize = FileSize - DataSize;

	(void)SwapSize;

	if(DEBUG)
		dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize);

	// construct Header
	{
		Header.m_aID[0] = 'D';
		Header.m_aID[1] = 'A';
		Header.m_aID[2] = 'T';
		Header.m_aID[3] = 'A';
		Header.m_Version = 4;
		Header.m_Size = FileSize - 16;
		Header.m_Swaplen = SwapSize - 16;
		Header.m_NumItemTypes = m_NumItemTypes;
		Header.m_NumItems = m_NumItems;
		Header.m_NumRawData = m_NumDatas;
		Header.m_ItemSize = ItemSize;
		Header.m_DataSize = DataSize;

		// write Header
		if(DEBUG)
			dbg_msg("datafile", "HeaderSize=%d", (int)sizeof(Header));
#if defined(CONF_ARCH_ENDIAN_BIG)
		swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));
#endif
		io_write(m_File, &Header, sizeof(Header));
	}

	// write types
	for(int i = 0, Count = 0; i < 0xffff; i++)
	{
		if(m_pItemTypes[i].m_Num)
		{
			// write info
			CDatafileItemType Info;
			Info.m_Type = i;
			Info.m_Start = Count;
			Info.m_Num = m_pItemTypes[i].m_Num;
			if(DEBUG)
				dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num);
#if defined(CONF_ARCH_ENDIAN_BIG)
			swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int));
#endif
			io_write(m_File, &Info, sizeof(Info));
			Count += m_pItemTypes[i].m_Num;
		}
	}

	// write item offsets
	for(int i = 0, Offset = 0; i < 0xffff; i++)
	{
		if(m_pItemTypes[i].m_Num)
		{
			// write all m_pItems in of this type
			int k = m_pItemTypes[i].m_First;
			while(k != -1)
			{
				if(DEBUG)
					dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset);
				int Temp = Offset;
#if defined(CONF_ARCH_ENDIAN_BIG)
				swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));
#endif
				io_write(m_File, &Temp, sizeof(Temp));
				Offset += m_pItems[k].m_Size + sizeof(CDatafileItem);

				// next
				k = m_pItems[k].m_Next;
			}
		}
	}

	// write data offsets
	for(int i = 0, Offset = 0; i < m_NumDatas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset);
		int Temp = Offset;
#if defined(CONF_ARCH_ENDIAN_BIG)
		swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));
#endif
		io_write(m_File, &Temp, sizeof(Temp));
		Offset += m_pDatas[i].m_CompressedSize;
	}

	// write data uncompressed sizes
	for(int i = 0; i < m_NumDatas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_pDatas[i].m_UncompressedSize);
		int UncompressedSize = m_pDatas[i].m_UncompressedSize;
#if defined(CONF_ARCH_ENDIAN_BIG)
		swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int));
#endif
		io_write(m_File, &UncompressedSize, sizeof(UncompressedSize));
	}

	// write m_pItems
	for(int i = 0; i < 0xffff; i++)
	{
		if(m_pItemTypes[i].m_Num)
		{
			// write all m_pItems in of this type
			int k = m_pItemTypes[i].m_First;
			while(k != -1)
			{
				CDatafileItem Item;
				Item.m_TypeAndID = (i<<16)|m_pItems[k].m_ID;
				Item.m_Size = m_pItems[k].m_Size;
				if(DEBUG)
					dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size);

#if defined(CONF_ARCH_ENDIAN_BIG)
				swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int));
				swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int));
#endif
				io_write(m_File, &Item, sizeof(Item));
				io_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size);

				// next
				k = m_pItems[k].m_Next;
			}
		}
	}

	// write data
	for(int i = 0; i < m_NumDatas; i++)
	{
		if(DEBUG)
			dbg_msg("datafile", "writing data id=%d size=%d", i, m_pDatas[i].m_CompressedSize);
		io_write(m_File, m_pDatas[i].m_pCompressedData, m_pDatas[i].m_CompressedSize);
	}

	// free data
	for(int i = 0; i < m_NumItems; i++)
		mem_free(m_pItems[i].m_pData);
	for(int i = 0; i < m_NumDatas; ++i)
		mem_free(m_pDatas[i].m_pCompressedData);

	io_close(m_File);
	m_File = 0;

	if(DEBUG)
		dbg_msg("datafile", "done");
	return 0;
}
Beispiel #2
0
/** Verify one certificate in the server certificate chain.
 * This callback is documented in SSL_set_verify(3).  */
static int
verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
	X509 *cert;
	SSL *ssl;
	struct socket *socket;
	struct connection *conn;
	unsigned char *host_in_uri;
	GENERAL_NAMES *alts;
	int saw_dns_name = 0;
	int matched = 0;

	/* If OpenSSL already found a problem, keep that.  */
	if (!preverify_ok)
		return 0;

	/* Examine only the server certificate, not CA certificates.  */
	if (X509_STORE_CTX_get_error_depth(ctx) != 0)
		return preverify_ok;

	cert = X509_STORE_CTX_get_current_cert(ctx);
	ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
	socket = (struct socket *)SSL_get_ex_data(ssl, socket_SSL_ex_data_idx);
	conn = (struct connection *)socket->conn;
	host_in_uri = get_uri_string(conn->uri, URI_HOST | URI_IDN);
	if (!host_in_uri)
		return 0;

	/* RFC 5280 section 4.2.1.6 describes the subjectAltName extension.
	 * RFC 2818 section 3.1 says Common Name must not be used
	 * if dNSName is present.  */
	alts = (GENERAL_NAMES *)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
	if (alts != NULL) {
		int alt_count;
		int alt_pos;
		GENERAL_NAME *alt;

		alt_count = sk_GENERAL_NAME_num(alts);
		for (alt_pos = 0; !matched && alt_pos < alt_count; ++alt_pos) {
			alt = sk_GENERAL_NAME_value(alts, alt_pos);
			if (alt->type == GEN_DNS) {
				saw_dns_name = 1;
				matched = match_uri_host_name(host_in_uri,
							      alt->d.dNSName);
			} else if (alt->type == GEN_IPADD) {
				matched = match_uri_host_ip(host_in_uri,
							    alt->d.iPAddress);
			}
		}

		/* Free the GENERAL_NAMES list and each element.  */
		sk_GENERAL_NAME_pop_free(alts, GENERAL_NAME_free);
	}

	if (!matched && !saw_dns_name) {
		X509_NAME *name;
		int cn_index;
		X509_NAME_ENTRY *entry = NULL;

		name = X509_get_subject_name(cert);
		cn_index = X509_NAME_get_index_by_NID(name, NID_commonName, -1);
		if (cn_index >= 0)
			entry = X509_NAME_get_entry(name, cn_index);
		if (entry != NULL)
			matched = match_uri_host_name(host_in_uri,
						      X509_NAME_ENTRY_get_data(entry));
	}

	mem_free(host_in_uri);
	return matched;
}
Beispiel #3
0
/*
 * XDR an array of arbitrary elements
 * *addrp is a pointer to the array, *sizep is the number of elements.
 * If addrp is NULL (*sizep * elsize) bytes are allocated.
 * elsize is the size (in bytes) of each element, and elproc is the
 * xdr procedure to call to handle each element of the array.
 */
bool_t
xdr_array(XDR *xdrs,
    caddr_t *addrp,		/* array pointer */
    u_int *sizep,		/* number of elements */
    u_int maxsize,		/* max numberof elements */
    u_int elsize,		/* size in bytes of each element */
    xdrproc_t elproc)		/* xdr routine to handle each element */
{
	u_int i;
	caddr_t target = *addrp;
	u_int c;  /* the actual element count */
	bool_t stat = TRUE;
	u_int nodesize;

	/* like strings, arrays are really counted arrays */
	if (!xdr_u_int(xdrs, sizep)) {
		return (FALSE);
	}
	c = *sizep;
	if ((c > maxsize || UINT_MAX/elsize < c) &&
	    (xdrs->x_op != XDR_FREE)) {
		return (FALSE);
	}
	nodesize = c * elsize;

	/*
	 * if we are deserializing, we may need to allocate an array.
	 * We also save time by checking for a null array if we are freeing.
	 */
	if (target == NULL)
		switch (xdrs->x_op) {
		case XDR_DECODE:
			if (c == 0)
				return (TRUE);
			*addrp = target = mem_alloc(nodesize);
			if (target == NULL) {
				printf("xdr_array: out of memory");
				return (FALSE);
			}
			memset(target, 0, nodesize);
			break;

		case XDR_FREE:
			return (TRUE);

		case XDR_ENCODE:
			break;
	}
	
	/*
	 * now we xdr each element of array
	 */
	for (i = 0; (i < c) && stat; i++) {
		stat = (*elproc)(xdrs, target);
		target += elsize;
	}

	/*
	 * the array may need freeing
	 */
	if (xdrs->x_op == XDR_FREE) {
		mem_free(*addrp, nodesize);
		*addrp = NULL;
	}
	return (stat);
}
Beispiel #4
0
bool    resolve_symvar_functions( char * buf )
{
    static const char   ampchar = '&';
    inp_line        *   in_wk;
    char            *   workb;
    char            *   pw;
    char            *   pwend;
    char            *   p2;
    char            *   pchar;
    char            *   varstart;
    sub_index           var_ind;
    symvar              symvar_entry;
    symsub          *   symsubval;
    size_t              buf_lg;
    int                 rc;
    bool                functions_found;
    bool                anything_substituted;

    char            *   var_unresolved; // ptr for resume search
    char            *   var_unresolved2;// ptr for resume search

    ProcFlags.substituted = false;
    ProcFlags.unresolved  = false;

    if( NULL == strchr( buf, ampchar ) ) {  // look for & in buffer
        return( false );              // no ampchar found, nothing to resolve
    }

    anything_substituted = false;
    var_unresolved = NULL;
    var_unresolved2 = NULL;
    functions_found = false;

    in_wk = mem_alloc( sizeof( inp_line ) + buf_size );// allocate workbuffer
    in_wk->next = NULL;
    workb = in_wk->value;               // allocate workbuffer

    do {                                // until no more substitutions
        strcpy( workb, buf );   // copy input buffer
        buf_lg = strlen( buf );
        pwend = workb + buf_lg - 1;
        if( var_unresolved == NULL ) {
            pw = workb;
            p2 = buf;
        } else {
            pw = workb + (var_unresolved2 - buf);
            p2 = var_unresolved2;
        }
        varstart = NULL;

        anything_substituted |= ProcFlags.substituted;
        ProcFlags.substituted = false;

        pchar = strchr( workb, ampchar ); // look for & in buffer
        while( pchar != NULL ) {        // & found
            if( *(pchar + 1) == ' ' ) { // not a symbol substition or function
                pchar = strchr( pchar + 1, ampchar );  // look for next & in buffer
                continue;
            }
            while( pw < pchar ) {       // copy all data preceding &
                *p2++ = *pw++;
            }
            buf_lg = strlen( buf );

            if( isalpha( *(pchar + 1) ) && *(pchar + 2) == '\''
                && *(pchar + 3) > ' ' ) {
                                        // not for .if '&*' eq '' .th ...
                                        // only    .if '&x'foo' eq '' .th
                char * * ppval = &p2;

                /***********************************************************/
                /*  Some single letter functions are resolved here:        */
                /*                                                         */
                /*  functions used within the OW doc build system:         */
                /*   &e'  existance of variable 0 or 1                     */
                /*   &l'  length of variable content                       */
                /*        or if undefined variable length of name          */
                /*   &u'  upper                                            */
                /*                                                         */
                /*   &s'  subscript                                        */
                /*   &S'  superscript                                      */
                /*                                                         */
                /*   other single letter functions are not used AFAIK      */
                /*                                                         */
                /***********************************************************/

                if( GlobalFlags.firstpass && input_cbs->fmflags & II_research ) {
                    add_single_func_research( pchar + 1 );
                }

                pw = scr_single_funcs( pchar, pwend, ppval );

                pchar = strchr( pw, ampchar );  // look for next & in buffer

                continue;
            }

            if( *(pchar + 1) == '\'' ) {// perhaps a multi letter function
                char   * pf;
                char * * ppval = &p2;
                int32_t  valsize = buf_size - (p2 - buf);

                pf = pchar + 2;
                while( is_function_char( *pf ) ) {
                    pf++;
                }
                if( *pf == '(' ) {// &'xyz( is start of multi char function

                /***********************************************************/
                /*  Some multi  letter functions are resolved here:        */
                /*                                                         */
                /*  functions used within the OW doc build system:         */
                /*                                                         */
                /*   &'delstr(          &'d2c(              &'index(       */
                /*   &'insert(          &'left(             &'length(      */
                /*   &'lower(           &'min(              &'pos(         */
                /*   &'right(           &'strip(            &'substr(      */
                /*   &'subword(         &'translate(        &'upper(       */
                /*   &'veclastpos(      &'vecpos(           &'word(        */
                /*   &'wordpos(         &'words(                           */
                /*                                                         */
                /*   Others are recognized but not processed               */
                /*   &'c2x(    is used for test output                     */
                /***********************************************************/

                    pw = scr_multi_funcs( pchar, pwend, ppval, valsize );

                    pchar = strchr( pw, ampchar );// look for next & in buffer
                    continue;
                }

                *p2++ = *pw++;          // copy &
                pchar = strchr( pw, ampchar );  // look for next & in buffer
                continue;               // and ignore this &... for now
            }

            /***************************************************************/
            /* & is neither start of single char function                  */
            /*   nor start of multi char function                          */
            /*                                                             */
            /* &  is probably start of a variable                          */
            /***************************************************************/

            varstart = pw;              // remember start of var
            pw++;                       // over &
            ProcFlags.suppress_msg = true;
            scan_err = false;

            pchar = scan_sym( pw, &symvar_entry, &var_ind );
            if( scan_err && *pchar == '(' ) {   // problem with subscript

                if( var_unresolved == NULL ) {
                    ProcFlags.unresolved  = true;
                    var_unresolved = varstart;
                    var_unresolved2 = p2;
                } else {
                    if( var_unresolved != varstart ) {
                        ProcFlags.unresolved  = true;
                    }
                }
                p2 += pchar - varstart;
                pw = pchar;
                pchar = strchr( pw, ampchar );  // look for next & in buffer

                continue;
            }

            ProcFlags.suppress_msg = false;

            if( symvar_entry.flags & local_var ) {  // lookup var in dict
                rc = find_symvar_l( &input_cbs->local_dict, symvar_entry.name,
                                    var_ind, &symsubval );
            } else {
                rc = find_symvar( &global_dict, symvar_entry.name, var_ind,
                                  &symsubval );
            }
            if( rc == 2 ) {             // variable found + resolved
                ProcFlags.substituted = true;
                if( !ProcFlags.CW_sep_ignore &&
                    symsubval->value[0] == CW_sep_char &&
                    symsubval->value[1] != CW_sep_char ) {

                                // split record at control word separator
                                // if variable starts with SINGLE cw separator
                                // and ignore cw separator

                    if( buf != buff2 ) {

                        // splitting input if not outermost buffer ++++ TBD
                        // needed ???
                        g_suicide();
                    }

                    if( *pchar == '.' ) {
                        pchar++;        // skip optional terminating dot
                    }
                    *p2 = '\0';
                    split_input_var( buf, pchar, &symsubval->value[1], true );
                    pw = pwend + 1;     // stop substitution for this record
                    varstart = NULL;

                    break;

                } else {
                    pw = symsubval->value;
                    if( symsubval->value[0] == CW_sep_char &&
                        symsubval->value[1] == CW_sep_char ) {
                        pw++;           // skip 1 CW_sep_char
                    }
                    strcpy( p2, pw );   // copy value
                    p2 += strlen(pw);
                    if( *pchar == '.' ) {
                        pchar++;        // skip optional terminating dot
                    }
                    pw = pchar;
                }
            } else {                    // variable not found
                if( (symvar_entry.flags & local_var )  // local var not found
                    ) {
                    if( (symvar_entry.name[0] == '\0') &&
                        (*pchar == ampchar) ) { // only &* as var name
                                                // followed by another var

                        if( var_unresolved == NULL ) {
                            ProcFlags.unresolved  = true;
                            var_unresolved = varstart;
                            var_unresolved2 = p2;
                        } else {
                            if( var_unresolved != varstart ) {
                                ProcFlags.unresolved  = true;
                            }
                        }
                        pw = varstart;
                        while( pw < pchar ) {   // treat var name as text
                            *p2++ = *pw++;  // and copy
                        }

                        continue;       // pchar points already to next &

                    } else {     // replace not found local var by nullstring
                        ProcFlags.substituted = true;
                        if( *pchar == '.' ) {
                            pchar++;    // skip optional terminating dot
                        }
                        pw = pchar;
                    }
                } else {                // global var not found
                                        // .. or local var outside of macro
                    /*******************************************************/
                    /*  keep trying for constructs such as                 */
                    /*                                                     */
                    /* .se prodgml = "Open Watcom GML"                     */
                    /* .se name = "GML"                                    */
                    /*                                                     */
                    /* My name is &prod&name..!                            */
                    /*                                                     */
                    /*  to become                                          */
                    /*                                                     */
                    /* My name is Open Watcom GML!                         */
                    /*                                                     */
                    /* This does not work for local variables, as these are*/
                    /* replaced by nullstring if not found                 */
                    /* My name is &*prod&*name..!                          */
                    /*  will become                                        */
                    /* My name is !                                        */
                    /*******************************************************/

                    if( var_unresolved == NULL ) {
                        ProcFlags.unresolved  = true;
                        var_unresolved = varstart;
                        var_unresolved2 = p2;
                    } else {
                        if( var_unresolved != varstart ) {
                            ProcFlags.unresolved  = true;
                        }
                    }

                    pw = varstart;
                    if( *pchar == '.' ) {
                        pchar++;        // copy terminating dot, too
                    }
                    while( pw < pchar ) {   // treat var name as text
                        *p2++ = *pw++;  // and copy
                    }
                }
            }
            pchar = strchr( pw, ampchar );  // look for next & in buffer
        }                               // while & found

        while( pw <= pwend) {           // copy remaining input
             *p2++ = *pw++;
        }
        *p2 = 0;                        // terminate string

    } while( ProcFlags.unresolved && ProcFlags.substituted );

    anything_substituted |= ProcFlags.substituted;

    mem_free( in_wk );                  // free workbuffer
    return( anything_substituted );
}
Beispiel #5
0
struct auth_entry *add_auth_entry( struct uri *uri, unsigned char *realm, unsigned char *nonce, unsigned char *opaque, unsigned int digest )
{
  int eax;
  int edx;
  struct auth_entry *entry;
  if ( find_auth_entry( uri, realm ) == 0 )
  {
    entry = (struct auth_entry*)mem_calloc( 1, 116 );
    if ( mem_calloc( 1, 116 ) == 0 )
    {
      return &entry[0];
    }
    uri->object.refcount = uri->object.refcount;
    *(int*)(mem_calloc( 1, 116 ) + 12) = uri[0];
    if ( realm )
    {
      *(int*)(mem_calloc( 1, 116 ) + 16) = stracpy( realm );
      if ( mem_calloc( 1, 116 ) + 16 == 0 )
      {
        mem_free( &ecx );
        return &entry[0];
      }
    }
    set_auth_user( &ecx, &uri[0] );
    set_auth_password( ebp_28, &uri[0] );
    *(int*)(ebp_28 + 28) = eax;
    if ( ebp_28 + 28 == 0 )
    {
      done_auth_entry( &ecx );
      return &entry[0];
    }
    *(int*)(ecx + 4) = auth_entry_list.next;
    ecx = auth_entry_list.next;
    auth_entry_list.next = &ecx;
    *(int*)(ecx + 4) = ecx;
    if ( nonce )
    {
      auth_entry_list.next[6] = stracpy( nonce );
      if ( auth_entry_list.next + 4 + 20 == 0 )
      {
        del_auth_entry( &ecx );
        return &entry[0];
      }
    }
    if ( opaque )
    {
      *(int*)(ebp_28 + 24) = stracpy( opaque );
      if ( ebp_28 + 24 == 0 )
      {
        del_auth_entry( &ecx );
        return &entry[0];
      }
    }
    auth_entry_list.next[29] = ( *(char*)(auth_entry_list.next + 4 + 112) & -5 ) | ( ( (int)digest/*.1_1of4*/ & 1 ) << 2 );
  }
  else
  {
    if ( ( ( *(char*)(find_auth_entry( uri, realm ) + 112) & 1 ) & 255 ) == 0 )
    {
      if ( (unsigned char)( realm != 0 ) == ( *(int*)(entry[0].next + 16) != 0 ) )
      {
        if ( ( ( realm != 0 ) & 255 ) && ebp_41 && stracpy( opaque ) )
          entry->realm[0] = entry->realm;
        else
        {
          if ( entry->user[0] && uri->user && uri->bits_at_40/*.3_4of4*/ )
          {
            errfile = "/home/naftali/source/elinks-0.12~pre5/src/protocol/auth/auth.c";
            errline = 185;
            if ( elinks_strlcmp( &entry->user[0], -1, uri->user, uri->bits_at_40/*.3_4of4*/ ) == 0 )
            {
              if ( entry->password[0] && uri->password && uri->bits_at_44/*.1_2of4*/ )
              {
                errfile = "/home/naftali/source/elinks-0.12~pre5/src/protocol/auth/auth.c";
                errline = 192;
                if ( elinks_strlcmp( &entry->password[0], -1, uri->password, (int)uri->bits_at_44/*.1_2of4*/ ) )
                  goto B36;
              }
B36:              entry->bits_at_112/*.1_1of4*/ &= 253;
              set_auth_password( &entry[0], &uri[0] );
            }
          }
          entry->bits_at_112/*.1_1of4*/ &= 253;
          set_auth_user( &entry[0], &uri[0] );
        }
      }
      entry->bits_at_112/*.1_1of4*/ = (int)entry->bits_at_112/*.1_1of4*/ & -3;
      if ( entry->realm )
        mem_free( (void*)entry->realm );
      entry->realm = 0;
      if ( ( realm != 0 ) & 255 )
      {
        entry->realm = stracpy( realm );
        if ( entry->realm )
        {
          if ( nonce )
          {
            if ( entry->nonce )
              mem_free( (void*)entry->nonce );
            entry->nonce = stracpy( nonce );
            if ( entry->nonce == 0 )
              goto B23;
          }
          if ( opaque )
          {
            if ( entry->opaque )
              mem_free( (void*)entry->opaque );
            entry->opaque = stracpy( opaque );
            if ( entry->opaque == 0 )
            {
              del_auth_entry( &entry[0] );
              uri = &uri[0];
              return 0;
            }
          }
          entry->bits_at_112/*.1_1of4*/ = ( *(char*)(entry[0].next + 112) & -5 ) | ( ( (int)digest/*.1_1of4*/ & 1 ) << 2 );
        }
B23:        &entry[0] = 0;
        del_auth_entry( &entry[0] );
        return &entry[0];
      }
    }
    else
    {
      return 0;
    }
  }
  if ( !( ( entry->bits_at_112/*.1_1of4*/ & 2 ) & 255 ) && entry->realm )
  {
    add_questions_entry( &do_auth_dialog, (void*)entry[0].next );
    return &entry[0];
  }
  return &entry[0];
}
Beispiel #6
0
static long mem_ctrl(BIO *b, int cmd, long num, void *ptr)
{
    long ret = 1;
    char **pptr;

    BUF_MEM *bm = (BUF_MEM *)b->ptr;

    switch (cmd) {
    case BIO_CTRL_RESET:
        if (bm->data != NULL) {
            /* For read only case reset to the start again */
            if (b->flags & BIO_FLAGS_MEM_RDONLY) {
                bm->data -= bm->max - bm->length;
                bm->length = bm->max;
            } else {
                memset(bm->data, 0, bm->max);
                bm->length = 0;
            }
        }
        break;
    case BIO_CTRL_EOF:
        ret = (long)(bm->length == 0);
        break;
    case BIO_C_SET_BUF_MEM_EOF_RETURN:
        b->num = (int)num;
        break;
    case BIO_CTRL_INFO:
        ret = (long)bm->length;
        if (ptr != NULL) {
            pptr = (char **)ptr;
            *pptr = (char *)&(bm->data[0]);
        }
        break;
    case BIO_C_SET_BUF_MEM:
        mem_free(b);
        b->shutdown = (int)num;
        b->ptr = ptr;
        break;
    case BIO_C_GET_BUF_MEM_PTR:
        if (ptr != NULL) {
            pptr = (char **)ptr;
            *pptr = (char *)bm;
        }
        break;
    case BIO_CTRL_GET_CLOSE:
        ret = (long)b->shutdown;
        break;
    case BIO_CTRL_SET_CLOSE:
        b->shutdown = (int)num;
        break;

    case BIO_CTRL_WPENDING:
        ret = 0L;
        break;
    case BIO_CTRL_PENDING:
        ret = (long)bm->length;
        break;
    case BIO_CTRL_DUP:
    case BIO_CTRL_FLUSH:
        ret = 1;
        break;
    case BIO_CTRL_PUSH:
    case BIO_CTRL_POP:
    default:
        ret = 0;
        break;
    }
    return (ret);
}
Beispiel #7
0
int main(int argc, const char *argv[]) {

	const char *socket = NULL;

	mem_init();
	atexit(mem_exit);

	terminal_init();

	// --------------------------------------------
	// parse the parameters

        // Check -v (verbose) first to enable log_debug()
        // when processing other options
        for (int i=1; i < argc; i++) if (!strcmp("-v", argv[i])) set_verbose(1);

	int p = 1;
	while (p < argc && argv[p][0]=='-') {

		switch(argv[p][1]) {
		case 0:
			// single '-' option ends parameter processing
			p++;
			goto endpars;
		case 'v':
                	assert_single_char(argv[p]);
			// verbose is already checked above
			set_verbose(1);
			break;
            	case '?':
                	assert_single_char(argv[p]);
                	usage(EXIT_SUCCESS);    /* usage() exits already */
                	break;
		case 'T':
			assert_single_char(argv[p]);
                	if (p < argc-2) {
                  		p++;
                  		socket = argv[p];
                  		log_info("main: tools socket = %s\n", socket);
                	} else {
                  		log_error("-T requires <socket name> parameter\n");
                  		exit(EXIT_RESPAWN_NEVER);
                	}
                	break;
            	default:
                	log_error("Unknown command line option %s\n", argv[p]);
                	usage(EXIT_RESPAWN_NEVER);
                	break;
		}
		p++;
	}
endpars:
	// --------------------------------------------
	// open the socket

        if (socket == NULL) {
                const char *home = os_get_home_dir();
                socket = malloc_path(home, ".xdtools");
        }

	int sockfd = socket_open(socket, 0);
	if (sockfd < 0) {
		log_errno("Could not open socket %s\n", socket);
		mem_free(socket);
		exit(1);
	}
	mem_free(socket);

	// --------------------------------------------
	// find our command either as ending part of the name of the binary ...
	

	const cmdtab_t *cmd = NULL;
	int l = strlen(argv[0]);

	for (int i = 0; i < numcmds; i++) {
		int cl = strlen(cmdtab[i].name);

		if ((cl <= l)
			&& !strcmp(cmdtab[i].name, &argv[0][l-cl])) {
			cmd = &cmdtab[i];
			break;
		}
	}
	// ... or as command line parameter
	if (p < argc) {
		l = strlen(argv[p]);
		if (cmd == NULL) {
			for (int i = 0; i < numcmds; i++) {
				int cl = strlen(cmdtab[i].name);

				if ((cl <= l)
					&& !strcmp(cmdtab[i].name, argv[p])) {
					cmd = &cmdtab[i];
					p++;
					break;
				}
			}
		}
	}

	if (cmd == NULL) {
		log_error("Could not identify any of the commands!\n");
		usage(1);
	}	

	int rv = cmd->func(sockfd, argc-p, argv+p);


	close(sockfd);

	return rv;
}
Beispiel #8
0
ULONG RES_store_resource(RF_class *RF, ULONG entry, void *source,
		RF_entry_hdr *RHDR, UWORD type) {
	WORD file;
	UBYTE *ptr;
	ULONG len;
	WORD err;

	err = 0;

	r_write(RF->file, RHDR, sizeof(RF_entry_hdr));

	len = RHDR->data_size;
	if (!len)
		return (entry);

	if (RHDR->data_attrib & DA_PLACEHOLDER)
		return (entry);

	switch (type) {
	case RTYP_HOUSECLEAN:
		file = *(WORD *) source;
		ptr = (UBYTE*) mem_alloc(BLK_SIZE);

		while (len > BLK_SIZE) {
			r_read(file, ptr, (UWORD) BLK_SIZE);
			r_write(RF->file, ptr, (UWORD) BLK_SIZE);
			len -= BLK_SIZE;
		}
		r_read(file, ptr, (UWORD) len);
		r_write(RF->file, ptr, (UWORD) len);

		mem_free(ptr);
		break;

	case RTYP_DICTIONARY:
	case RTYP_RAW_MEM:
		ptr = (UBYTE*) source;

		while (len > BLK_SIZE) {
			r_write(RF->file, ptr, (UWORD) BLK_SIZE);
			len -= BLK_SIZE;
			ptr = (UBYTE*) add_ptr(ptr, BLK_SIZE);
		}
		r_write(RF->file, ptr, (UWORD) len);
		break;

	case RTYP_RAW_FILE:
		file = open((BYTE*) source, O_RDWR);
		ptr = (UBYTE*) mem_alloc(BLK_SIZE);

		while (len > BLK_SIZE) {
			r_read(file, ptr, (UWORD) BLK_SIZE);
			r_write(RF->file, ptr, (UWORD) BLK_SIZE);
			len -= BLK_SIZE;
		}
		r_read(file, ptr, (UWORD) len);
		r_write(RF->file, ptr, (UWORD) len);

		mem_free(ptr);
		close(file);
		break;
	}

	if (!err)
		return (entry);
	else
		return ((ULONG) -1);
}
Beispiel #9
0
static status_t
control_hook(void *dev, uint32 msg, void *buf, size_t len)
{
	device_info *di = (device_info *)dev;
	status_t result = B_DEV_INVALID_IOCTL;

	switch (msg) {
		// needed by app_server to load accelerant
		case B_GET_ACCELERANT_SIGNATURE: {
			char *sig = (char *)buf;
			strcpy(sig, "radeon.accelerant");
			result = B_OK;
		} break;

		// needed to share data between kernel and accelerant		
		case RADEON_GET_PRIVATE_DATA: {
			radeon_get_private_data *gpd = (radeon_get_private_data *)buf;
			
			if (gpd->magic == RADEON_PRIVATE_DATA_MAGIC) {
				gpd->shared_info_area = di->shared_area;
				gpd->virtual_card_area = di->virtual_card_area;
				result = B_OK;
			}
		} break;

		// needed for cloning
		case RADEON_DEVICE_NAME: {
			radeon_device_name *dn = (radeon_device_name *)buf;
			
			if( dn->magic == RADEON_PRIVATE_DATA_MAGIC ) {
				strncpy( dn->name, di->name, MAX_RADEON_DEVICE_NAME_LENGTH );
				result = B_OK;
			}
		} break;
		
		// graphics mem manager
		case RADEON_ALLOC_MEM: {
			radeon_alloc_mem *am = (radeon_alloc_mem *)buf;
			memory_type_e memory_type;
			
			if( am->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			if( am->memory_type > mt_last )
				break;

			memory_type = am->memory_type == mt_nonlocal ? di->si->nonlocal_type : am->memory_type;
			
			result = mem_alloc( di->memmgr[memory_type], am->size, am->global ? 0 : dev, &am->handle, &am->offset );
		} break;
		
		case RADEON_FREE_MEM: {
			radeon_free_mem *fm = (radeon_free_mem *)buf;
			memory_type_e memory_type;
		
			if( fm->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			if( fm->memory_type > mt_last )
				break;	
				
			memory_type = fm->memory_type == mt_nonlocal ? di->si->nonlocal_type : fm->memory_type;
				
			result = mem_free( di->memmgr[memory_type], fm->handle, fm->global ? 0 : dev );
		} break;
		
		case RADEON_WAITFORIDLE: {
			radeon_wait_for_idle *wfi = (radeon_wait_for_idle *)buf;
			
			if( wfi->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			Radeon_WaitForIdle( di, true, wfi->keep_lock );
			result = B_OK;
		} break;
		
		case RADEON_WAITFORFIFO: {
			radeon_wait_for_fifo *wff = (radeon_wait_for_fifo *)buf;
			
			if( wff->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			Radeon_WaitForFifo( di, wff->entries );
			result = B_OK;
		} break;
		
		case RADEON_RESETENGINE: {
			radeon_no_arg *na = (radeon_no_arg *)buf;
			
			if( na->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			ACQUIRE_BEN( di->si->cp.lock );
			Radeon_ResetEngine( di );
			RELEASE_BEN( di->si->cp.lock );
			
			result = B_OK;
		} break;
		
		case RADEON_VIPREAD: {
			radeon_vip_read *vr = (radeon_vip_read *)buf;
			
			if( vr->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			result = Radeon_VIPRead( di, vr->channel, vr->address, &vr->data,
				vr->lock ) ? B_OK : B_ERROR;
		} break;
		
		case RADEON_VIPWRITE: {
			radeon_vip_write *vw = (radeon_vip_write *)buf;
			
			if( vw->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			result = Radeon_VIPWrite( di, vw->channel, vw->address, vw->data,
				vw->lock ) ? B_OK : B_ERROR;
		} break;
		
		case RADEON_VIPFIFOREAD: {
			radeon_vip_fifo_read *vr = (radeon_vip_fifo_read *)buf;
			
			if( vr->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			result = Radeon_VIPFifoRead( di, vr->channel, vr->address, vr->count, vr->data,
				vr->lock ) ? B_OK : B_ERROR;
		} break;
		
		case RADEON_VIPFIFOWRITE: {
			radeon_vip_fifo_write *vw = (radeon_vip_fifo_write *)buf;
			
			if( vw->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			result = Radeon_VIPFifoWrite( di, vw->channel, vw->address, vw->count, vw->data,
				vw->lock ) ? B_OK : B_ERROR;
		} break;
		
		case RADEON_FINDVIPDEVICE: {
			radeon_find_vip_device *fvd = (radeon_find_vip_device *)buf;
			
			if( fvd->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;

			fvd->channel = Radeon_FindVIPDevice( di, fvd->device_id );
			result = B_OK;
		} break;
		
		
		case RADEON_VIPRESET: {
			radeon_vip_reset *fvd = (radeon_vip_reset *)buf;

			if( fvd->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
			
			Radeon_VIPReset( di, fvd->lock );
			result = B_OK;
		} break;
		
		case RADEON_WAIT_FOR_CAP_IRQ: {
			radeon_wait_for_cap_irq *wvc = (radeon_wait_for_cap_irq *)buf;
			
			if( wvc->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			// restrict wait time to 1 sec to get not stuck here in kernel
			result = acquire_sem_etc( di->cap_sem, 1, B_RELATIVE_TIMEOUT, 
				min( wvc->timeout, 1000000 ));
	
			if( result == B_OK ) {
				cpu_status prev_irq_state = disable_interrupts();
				acquire_spinlock( &di->cap_spinlock );
				
				wvc->timestamp = di->cap_timestamp;
				wvc->int_status = di->cap_int_status;
				wvc->counter = di->cap_counter;
				
				release_spinlock( &di->cap_spinlock );
				restore_interrupts( prev_irq_state );
			}
		} break;
		
		case RADEON_DMACOPY: {
			radeon_dma_copy *dc = (radeon_dma_copy *)buf;
			
			if( dc->magic != RADEON_PRIVATE_DATA_MAGIC )
				break;
				
			result = Radeon_DMACopy( di, dc->src, dc->target, dc->size, dc->lock_mem, dc->contiguous );
		} break;
					
#ifdef ENABLE_LOGGING
#ifdef LOG_INCLUDE_STARTUP
		// interface to log data
		case RADEON_GET_LOG_SIZE:
			*(uint32 *)buf = log_getsize( di->si->log );
			result = B_OK;
			break;
			
		case RADEON_GET_LOG_DATA:
			log_getcopy( di->si->log, buf, ((uint32 *)buf)[0] );
			result = B_OK;
			break;
#endif
#endif
	}
	
	if( result == B_DEV_INVALID_IOCTL )
		SHOW_ERROR( 3, "Invalid ioctl call: code=0x%lx", msg );
		
	return result;
}
Beispiel #10
0
void TS_destroy(TS_class *TS) {
	DICT_destroy(TS->cache);

	mem_free(TS);
}
Beispiel #11
0
void CSS_destroy(CSS_class *CSS) {
	mem_free(CSS);
}
Beispiel #12
0
ULONG DICT_save(DICT_class *DICT, RF_class *RF, ULONG entry) {
	RF_entry_hdr RHDR;
	ULONG saved, total_len, nchains;
	UWORD i;
	DICT_entry *cur;
	DI_class *DI;
	BYTE *ptr, *base;
	ULONG *offset;

	nchains = 0L;
	for (i = 0; i < DICT->hash_size; i++)
		if (DICT->root[i] != NULL)
			++nchains;

	total_len = nchains * (ULONG) sizeof(UWORD);

	DI = DI_construct(DICT);

	total_len += ((ULONG) sizeof(UWORD)) + ((ULONG) sizeof(UWORD))
			+ ((ULONG) DICT->hash_size * (ULONG) sizeof(ULONG));

	while ((cur = DI_fetch(DI)) != NULL) {
		total_len += (ULONG) ((strlen(cur->tag) + 1) + (2 * sizeof(UWORD)));
		if (cur->def != NULL)
			total_len += (ULONG) (strlen((BYTE*) cur->def) + 1);
	}

	DI_destroy(DI);

	ptr = base = (BYTE*) mem_alloc(total_len);

	*(UWORD *) ptr = DICT->hash_size;
	ptr += sizeof(UWORD);

	offset = (ULONG *) ptr;
	ptr = (BYTE*) add_ptr(ptr,
			((ULONG) sizeof(ULONG) * (ULONG) DICT->hash_size));

	for (i = 0; i < DICT->hash_size; i++) {
		cur = DICT->root[i];

		if (cur == NULL) {
			offset[i] = 0L;
			continue;
		}

		offset[i] = ptr_dif((ULONG*) ptr, (ULONG*) base);

		while (cur != NULL) {
			*(UWORD *) ptr = (strlen(cur->tag) + 1);
			ptr += sizeof(UWORD);

			strcpy(ptr, cur->tag);
			ptr += (strlen(cur->tag) + 1);

			if (cur->def == NULL) {
				*(UWORD *) ptr = 0;
				ptr += sizeof(UWORD);
			} else {
				*(UWORD *) ptr = (strlen((BYTE*) cur->def) + 1);
				ptr += sizeof(UWORD);

				strcpy(ptr, (BYTE*) cur->def);
				ptr += (strlen((BYTE*) cur->def) + 1);
			}

			cur = cur->next;
			ptr = (BYTE*) norm(ptr);
		}

		*(UWORD *) ptr = 0;
		ptr += sizeof(UWORD);
	}

	*(UWORD *) ptr = 0;
	ptr += sizeof(UWORD);

	RHDR.data_size = total_len;
	RHDR.data_attrib = DA_TEMPORARY;

	if (entry == (ULONG) -1)
		saved = RF_new_entry(RF, base, &RHDR, RTYP_DICTIONARY);
	else
		RF_write_entry(RF, saved = entry, base, &RHDR, RTYP_DICTIONARY);

	mem_free(base);

	return (saved);
}
Beispiel #13
0
bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename)
{
    dbg_msg("datafile", "loading. filename='%s'", pFilename);

    IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ);
    if(!File)
    {
        dbg_msg("datafile", "could not open '%s'", pFilename);
        return false;
    }


    // take the CRC of the file and store it
    unsigned Crc = 0;
    {
        enum
        {
            BUFFER_SIZE = 64*1024
        };

        unsigned char aBuffer[BUFFER_SIZE];

        while(1)
        {
            unsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE);
            if(Bytes <= 0)
                break;
            Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention
        }

        io_seek(File, 0, IOSEEK_START);
    }


    // TODO: change this header
    CDatafileHeader Header;
    io_read(File, &Header, sizeof(Header));
    if(Header.m_aId[0] != 'A' || Header.m_aId[1] != 'T' || Header.m_aId[2] != 'A' || Header.m_aId[3] != 'D')
    {
        if(Header.m_aId[0] != 'D' || Header.m_aId[1] != 'A' || Header.m_aId[2] != 'T' || Header.m_aId[3] != 'A')
        {
            dbg_msg("datafile", "wrong signature. %x %x %x %x", Header.m_aId[0], Header.m_aId[1], Header.m_aId[2], Header.m_aId[3]);
            return 0;
        }
    }

#if defined(CONF_ARCH_ENDIAN_BIG)
    swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));
#endif
    if(Header.m_Version != 3 && Header.m_Version != 4)
    {
        dbg_msg("datafile", "wrong version. version=%x", Header.m_Version);
        return 0;
    }

    // read in the rest except the data
    unsigned Size = 0;
    Size += Header.m_NumItemTypes*sizeof(CDatafileItemType);
    Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int);
    if(Header.m_Version == 4)
        Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes aswell
    Size += Header.m_ItemSize;

    unsigned AllocSize = Size;
    AllocSize += sizeof(CDatafile); // add space for info structure
    AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers

    m_pDataFile = (CDatafile*)mem_alloc(AllocSize, 1);
    m_pDataFile->m_Header = Header;
    m_pDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size;
    m_pDataFile->m_ppDataPtrs = (char**)(m_pDataFile+1);
    m_pDataFile->m_pData = (char *)(m_pDataFile+1)+Header.m_NumRawData*sizeof(char *);
    m_pDataFile->m_File = File;
    m_pDataFile->m_Crc = Crc;

    // clear the data pointers
    mem_zero(m_pDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*));

    // read types, offsets, sizes and item data
    unsigned ReadSize = io_read(File, m_pDataFile->m_pData, Size);
    if(ReadSize != Size)
    {
        mem_free(m_pDataFile);
        m_pDataFile = 0;
        dbg_msg("datafile", "couldn't load the whole thing, wanted=%d got=%d", Size, ReadSize);
        return false;
    }

#if defined(CONF_ARCH_ENDIAN_BIG)
    swap_endian(m_pDataFile->m_pData, sizeof(int), Header.m_Swaplen / sizeof(int));
#endif

    //if(DEBUG)
    {
        dbg_msg("datafile", "allocsize=%d", AllocSize);
        dbg_msg("datafile", "readsize=%d", ReadSize);
        dbg_msg("datafile", "swaplen=%d", Header.m_Swaplen);
        dbg_msg("datafile", "item_size=%d", m_pDataFile->m_Header.m_ItemSize);
    }

    m_pDataFile->m_Info.m_pItemTypes = (CDatafileItemType *)m_pDataFile->m_pData;
    m_pDataFile->m_Info.m_pItemOffsets = (int *)&m_pDataFile->m_Info.m_pItemTypes[m_pDataFile->m_Header.m_NumItemTypes];
    m_pDataFile->m_Info.m_pDataOffsets = (int *)&m_pDataFile->m_Info.m_pItemOffsets[m_pDataFile->m_Header.m_NumItems];
    m_pDataFile->m_Info.m_pDataSizes = (int *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];

    if(Header.m_Version == 4)
        m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataSizes[m_pDataFile->m_Header.m_NumRawData];
    else
        m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];
    m_pDataFile->m_Info.m_pDataStart = m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Header.m_ItemSize;

    dbg_msg("datafile", "loading done. datafile='%s'", pFilename);

    if(DEBUG)
    {
        /*
        for(int i = 0; i < m_pDataFile->data.num_raw_data; i++)
        {
        	void *p = datafile_get_data(df, i);
        	dbg_msg("datafile", "%d %d", (int)((char*)p - (char*)(&m_pDataFile->data)), size);
        }

        for(int i = 0; i < datafile_num_items(df); i++)
        {
        	int type, id;
        	void *data = datafile_get_item(df, i, &type, &id);
        	dbg_msg("map", "\t%d: type=%x id=%x p=%p offset=%d", i, type, id, data, m_pDataFile->info.item_offsets[i]);
        	int *idata = (int*)data;
        	for(int k = 0; k < 3; k++)
        		dbg_msg("datafile", "\t\t%d=%d (%x)", k, idata[k], idata[k]);
        }

        for(int i = 0; i < m_pDataFile->data.num_m_aItemTypes; i++)
        {
        	dbg_msg("map", "\t%d: type=%x start=%d num=%d", i,
        		m_pDataFile->info.m_aItemTypes[i].type,
        		m_pDataFile->info.m_aItemTypes[i].start,
        		m_pDataFile->info.m_aItemTypes[i].num);
        	for(int k = 0; k < m_pDataFile->info.m_aItemTypes[i].num; k++)
        	{
        		int type, id;
        		datafile_get_item(df, m_pDataFile->info.m_aItemTypes[i].start+k, &type, &id);
        		if(type != m_pDataFile->info.m_aItemTypes[i].type)
        			dbg_msg("map", "\tERROR");
        	}
        }
        */
    }

    return true;
}
Beispiel #14
0
int CDataFileWriter::Finish()
{
    int ItemSize = 0;
    int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize;
    int DataSize = 0;
    CDatafileHeader Header;

    // we should now write this file!
    if(DEBUG)
        dbg_msg("datafile", "writing");

    // calculate sizes
    for(int i = 0; i < m_NumItems; i++)
    {
        if(DEBUG)
            dbg_msg("datafile", "item=%d size=%d (%d)", i, m_aItems[i].m_Size, m_aItems[i].m_Size+sizeof(CDatafileItem));
        ItemSize += m_aItems[i].m_Size + sizeof(CDatafileItem);
    }


    for(int i = 0; i < m_NumDatas; i++)
        DataSize += m_aDatas[i].m_CompressedSize;

    // calculate the complete size
    TypesSize = m_NumItemTypes*sizeof(CDatafileItemType);
    HeaderSize = sizeof(CDatafileHeader);
    OffsetSize = m_NumItems*sizeof(int) + m_NumDatas*sizeof(int);
    FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize;
    SwapSize = FileSize - DataSize;

    (void)SwapSize;

    if(DEBUG)
        dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize);

    // construct Header
    {
        Header.m_aId[0] = 'D';
        Header.m_aId[1] = 'A';
        Header.m_aId[2] = 'T';
        Header.m_aId[3] = 'A';
        Header.m_Version = 4;
        Header.m_Size = FileSize - 16;
        Header.m_Swaplen = SwapSize - 16;
        Header.m_NumItemTypes = m_NumItemTypes;
        Header.m_NumItems = m_NumItems;
        Header.m_NumRawData = m_NumDatas;
        Header.m_ItemSize = ItemSize;
        Header.m_DataSize = DataSize;

        // TODO: apply swapping
        // write Header
        if(DEBUG)
            dbg_msg("datafile", "HeaderSize=%d", sizeof(Header));
        io_write(m_File, &Header, sizeof(Header));
    }

    // write types
    for(int i = 0, Count = 0; i < 0xffff; i++)
    {
        if(m_aItemTypes[i].m_Num)
        {
            // write info
            CDatafileItemType Info;
            Info.m_Type = i;
            Info.m_Start = Count;
            Info.m_Num = m_aItemTypes[i].m_Num;
            if(DEBUG)
                dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num);
            io_write(m_File, &Info, sizeof(Info));
            Count += m_aItemTypes[i].m_Num;
        }
    }

    // write item offsets
    for(int i = 0, Offset = 0; i < 0xffff; i++)
    {
        if(m_aItemTypes[i].m_Num)
        {
            // write all m_aItems in of this type
            int k = m_aItemTypes[i].m_First;
            while(k != -1)
            {
                if(DEBUG)
                    dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset);
                io_write(m_File, &Offset, sizeof(Offset));
                Offset += m_aItems[k].m_Size + sizeof(CDatafileItem);

                // next
                k = m_aItems[k].m_Next;
            }
        }
    }

    // write data offsets
    for(int i = 0, Offset = 0; i < m_NumDatas; i++)
    {
        if(DEBUG)
            dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset);
        io_write(m_File, &Offset, sizeof(Offset));
        Offset += m_aDatas[i].m_CompressedSize;
    }

    // write data uncompressed sizes
    for(int i = 0; i < m_NumDatas; i++)
    {
        /*
        if(DEBUG)
        	dbg_msg("datafile", "writing data offset num=%d offset=%d", i, offset);
        */
        io_write(m_File, &m_aDatas[i].m_UncompressedSize, sizeof(int));
    }

    // write m_aItems
    for(int i = 0; i < 0xffff; i++)
    {
        if(m_aItemTypes[i].m_Num)
        {
            // write all m_aItems in of this type
            int k = m_aItemTypes[i].m_First;
            while(k != -1)
            {
                CDatafileItem Item;
                Item.m_TypeAndId = (i<<16)|m_aItems[k].m_Id;
                Item.m_Size = m_aItems[k].m_Size;
                if(DEBUG)
                    dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_aItems[k].m_Id, m_aItems[k].m_Size);

                io_write(m_File, &Item, sizeof(Item));
                io_write(m_File, m_aItems[k].m_pData, m_aItems[k].m_Size);

                // next
                k = m_aItems[k].m_Next;
            }
        }
    }

    // write data
    for(int i = 0; i < m_NumDatas; i++)
    {
        if(DEBUG)
            dbg_msg("datafile", "writing data id=%d size=%d", i, m_aDatas[i].m_CompressedSize);
        io_write(m_File, m_aDatas[i].m_pCompressedData, m_aDatas[i].m_CompressedSize);
    }

    // free data
    for(int i = 0; i < m_NumItems; i++)
        mem_free(m_aItems[i].m_pData);


    io_close(m_File);

    if(DEBUG)
        dbg_msg("datafile", "done");
    return 0;
}
int main(int argc, char *argv[]) {

    struct datablock_plot dbp;
    struct ip_mreq mreq;
    struct sockaddr_in addr;
//    struct hostent * pHostInfo;
//    long nHostAddress;
    int yes = 1, s, dbplen;
    socklen_t addrlen;
    bool forced_exit = false;

    startup();


    log_printf(LOG_NORMAL, "client_LNX v%s Copyright (C) 2002 - 2012 Diego Torres\n\n"
        "This program comes with ABSOLUTELY NO WARRANTY.\n"
        "This is free software, and you are welcome to redistribute it\n"
        "under certain conditions; see COPYING file for details.\n\n", VERSION);
    
//    pHostInfo = gethostbyname("localost");
//    memcpy(&nHostAddress, pHostInfo->h_addr, pHostInfo->h_length);
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(MULTICAST_PLOTS_PORT);
    if ( (s = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
	log_printf(LOG_ERROR, "socket %s\n", strerror(errno));
	exit(1);
    }
    
    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
    if ( bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
	log_printf(LOG_ERROR, "bind %s\n", strerror(errno));
	exit(1);
    }
				
    mreq.imr_interface.s_addr = inet_addr("127.0.0.1"); //nHostAddress;
    mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_PLOTS_GROUP);
    if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
	log_printf(LOG_ERROR, "setsocktperror\n");
	exit(1);
    }

    while (!forced_exit) {
	char *sac_s=0, *sic_l=0;
	dbplen = sizeof(dbp);
	addrlen = sizeof(addr);
	float diff = 0.0;

	if (recvfrom(s, &dbp, dbplen, 0, (struct sockaddr *) &addr, &addrlen) < 0) {
	    log_printf(LOG_ERROR, "recvfrom\n");
	    exit(1);
	}
	if (dbp.cat == CAT_255) {
	    log_printf(LOG_ERROR, "fin de fichero\n");
	    forced_exit = true;
	}
	if ( (dbp.cat == CAT_01) && (dbp.available & IS_TYPE)/* && (dbp.available & IS_TOD)*/ ) {
	    char *hora1,*hora2;

	    if (dbp.available & IS_TOD) 
		hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }
	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }
	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%s%s%s%s%s]%s [AZI %3.3f]"
		" [DST %03.3f] [MODEA %04o%s%s%s] [FL%03d%s%s] r%d [%s] (%5.3f) [%s] (%3.4f)\n", dbp.id, /* IFSNOP MOD */
		sac_s , sic_l, 
		(dbp.type == NO_DETECTION) ? "unk" : "",
		(dbp.type & TYPE_C1_PSR) ? "PSR" : "", 
		(dbp.type & TYPE_C1_SSR) ? "SSR" : "",
		(dbp.type & TYPE_C1_CMB) ? "CMB" : "",
		(dbp.type & FROM_C1_FIXED_TRANSPONDER) ? "-TRN" : "",
		(dbp.flag_test == 1) ? "T" : "",
		(dbp.available & IS_MEASURED_POLAR) ? dbp.theta : 0.0,
		(dbp.available & IS_MEASURED_POLAR) ? dbp.rho : 0.0,
		(dbp.available & IS_MODEA) ? dbp.modea : 0,
		(dbp.modea_status & STATUS_MODEA_GARBLED) ? "G" : "",
		(dbp.modea_status & STATUS_MODEA_NOTVALIDATED) ? "I" : "",
		(dbp.modea_status & STATUS_MODEA_SMOOTHED) ? "S" : "",
		(dbp.available & IS_MODEC) ? dbp.modec : -1,
		(dbp.modec_status & STATUS_MODEC_GARBLED) ? "G" : "",
		(dbp.modec_status & STATUS_MODEC_NOTVALIDATED) ? "I" : "",
		(dbp.radar_responses),
		(dbp.available & IS_TOD) ? hora1 : "na",
		(dbp.available & IS_TRUNCATED_TOD) ? dbp.truncated_tod : 0.0,
		hora2,
		diff);

	    if (dbp.available & IS_TOD)
	        mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
    		mem_free(sac_s);
		mem_free(sic_l);
	    }

	} else if (dbp.cat == CAT_02 ) {
	    char *hora1, *hora2;

	    hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }

	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }

	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%s%s%s%s%s%s] [%s] [%s] (%3.4f)\n", dbp.id,
		sac_s, sic_l,
		(dbp.type == NO_DETECTION) ? "unk" : "",
		(dbp.type == TYPE_C2_NORTH_MARKER) ? "NORTE" : "", 
		(dbp.type == TYPE_C2_SOUTH_MARKER) ? "SUR" : "", 
		(dbp.type == TYPE_C2_SECTOR_CROSSING) ? "SECTOR" : "", 
		(dbp.type == TYPE_C2_START_BLIND_ZONE_FILTERING) ? "START_BLIND" : "", 
		(dbp.type == TYPE_C2_STOP_BLIND_ZONE_FILTERING) ? "STOP_BLIND" : "", 
		hora1, hora2,
		(dbp.available & IS_TOD) ? diff: 0.0);
    	    mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
    		mem_free(sac_s);
		mem_free(sic_l);
	    }
	} else if (dbp.cat == CAT_10 ) {
	    char *hora1, *hora2;

	    hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }
	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }

	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%s%s%s%s] [%s%s%s%s%s%s%s%s%s] [%s] [%s] (%3.4f)\n", dbp.id,
		sac_s, sic_l,
		(dbp.type == TYPE_C10_TARGET_REPORT) ? "PLOT" : "",
		(dbp.type == TYPE_C10_START_UPDATE_CYCLE) ? "UPDATE" : "",
		(dbp.type == TYPE_C10_PERIODIC_STATUS) ? "PERIODIC" : "",
		(dbp.type == TYPE_C10_EVENT_STATUS) ? "EVENT" : "",
		(dbp.plot_type == NO_DETECTION) ? "na" : "",
		(dbp.plot_type == TYPE_C10_PLOT_SSR_MULTI) ? "SSRM" : "",
		(dbp.plot_type == TYPE_C10_PLOT_SSRS_MULTI) ? "SMMS" : "",
		(dbp.plot_type == TYPE_C10_PLOT_ADSB) ? "ADS" : "",
		(dbp.plot_type == TYPE_C10_PLOT_PSR) ? "SMR" : "",
		(dbp.plot_type == TYPE_C10_PLOT_MAGNETIC) ? "MAG" : "",
		(dbp.plot_type == TYPE_C10_PLOT_HF_MULTI) ? "HFM" : "",
		(dbp.plot_type == TYPE_C10_PLOT_NOT_DEFINED) ? "und" : "",
		(dbp.plot_type == TYPE_C10_PLOT_OTHER) ? "OTHER" : "",
		hora1, hora2,
		(dbp.available & IS_TOD) ? diff : 0.0);
	    mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
		mem_free(sac_s);
		mem_free(sic_l);
	    }
	} else if (dbp.cat == CAT_19 ) {
	    char *hora1, *hora2;

	    hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }
	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }

	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%s%s%s] [%s] [%s] (%3.4f)\n", dbp.id,
		sac_s, sic_l,
		(dbp.type == TYPE_C19_START_UPDATE_CYCLE) ? "UPDATE" : "",
		(dbp.type == TYPE_C19_PERIODIC_STATUS) ? "PERIODIC" : "",
		(dbp.type == TYPE_C19_EVENT_STATUS) ? "EVENT" : "",
		hora1, hora2,
		(dbp.available & IS_TOD) ? diff : 0.0);
	    mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
		mem_free(sac_s);
		mem_free(sic_l);
	    }
	} else if (dbp.cat == CAT_20 ) {
	    char *hora1, *hora2;

	    hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }
	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }

	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%04X] [%s] [%s] (%3.4f)\n", dbp.id,
		sac_s, sic_l, dbp.type, 
		hora1, hora2,
		(dbp.available & IS_TOD) ? diff : 0.0);
	    mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
		mem_free(sac_s);
		mem_free(sic_l);
	    }
	} else if (dbp.cat == CAT_21 ) {
	    char *hora1, *hora2;

	    hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }
	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }

	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%s%s%s%s] [%s] [%s] (%3.4f)\n", dbp.id,
		sac_s, sic_l,
		(dbp.flag_test == T_YES) ? "TEST" : "",
		(dbp.flag_ground == T_YES) ? "GROUND" : "",
		(dbp.flag_sim == T_YES) ? "SIM" : "",
		(dbp.flag_fixed == T_YES) ? "FIXED" : "",
		hora1, hora2,
		(dbp.available & IS_TOD) ? diff : 0.0);
	    mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
		mem_free(sac_s);
		mem_free(sic_l);
	    }
	} else if (dbp.cat == CAT_34 ) {
	    char *hora1, *hora2;

	    hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }
	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }

	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%s%s%s%s] [%s] [%s] (%3.4f)\n", dbp.id,
		sac_s, sic_l,
		(dbp.type == TYPE_C34_NORTH_MARKER) ? "NORTE" : "",
		(dbp.type == TYPE_C34_SECTOR_CROSSING) ? "SECTOR" : "",
		(dbp.type == TYPE_C34_GEOGRAPHICAL_FILTERING) ? "FILTER" : "",
		(dbp.type == TYPE_C34_JAMMING_STROBE) ? "JAMM" : "",
		hora1, hora2,
		(dbp.available & IS_TOD) ? diff : 0.0);
	    mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
		mem_free(sac_s);
		mem_free(sic_l);
	    }
	} else if (dbp.cat == CAT_48 ) {
	    char *hora1, *hora2;

	    hora1 = parse_hora(dbp.tod);
	    hora2 = parse_hora(dbp.tod_stamp);
	    if (dbp.available & IS_SACSIC) {
		sac_s = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SAC_SHORT);
		sic_l = ast_get_SACSIC((unsigned char *) &dbp.sac, (unsigned char *) &dbp.sic, GET_SIC_LONG);
	    }
	    if (dbp.available & IS_TOD) {
		diff = dbp.tod_stamp - dbp.tod;
		if (diff <= -86000) { // cuando tod esta en el dia anterior y tod_stamp en el siguiente, la resta es negativa
		    diff += 86400;    // le sumamos un dia entero para cuadrar el calculo
		} else if (diff >=(86400-512)) {
		    diff -= 86400;
		}
	    }

	    log_printf(LOG_VERBOSE, "%ld [%s/%s] [%s] [%s] [%s] (%3.4f)\n", dbp.id,
		sac_s, sic_l, "PLOT?",
		hora1, hora2,
		(dbp.available & IS_TOD) ? diff : 0.0);
	    mem_free(hora1);
	    mem_free(hora2);
	    if (dbp.available & IS_SACSIC) {
		mem_free(sac_s);
		mem_free(sic_l);
	    }
	}
    }

    log_printf(LOG_NORMAL, "end...\n");
//    log_flush();

    exit(0);
}
Beispiel #16
0
			~ptr_wrapper_t() { if(o_) mem_free(o_); }
Beispiel #17
0
void my_mem_free(int num) {
    mem_free(allocs[num]);
}
Beispiel #18
0
static void
download_dialog_layouter(struct dialog_data *dlg_data)
{
	struct file_download *file_download = dlg_data->dlg->udata;
	struct terminal *term = dlg_data->win->term;
	int w = dialog_max_width(term);
	int rw = w;
	int x, y = 0;
	int url_len;
	unsigned char *url;
	struct download *download = &file_download->download;
	struct color_pair *dialog_text_color = get_bfu_color(term, "dialog.text");
	unsigned char *msg = get_download_msg(download, term, 1, 1, "\n");
	int show_meter = (download_is_progressing(download)
			  && download->progress->size >= 0);
#if CONFIG_BITTORRENT
	int bittorrent = (file_download->uri->protocol == PROTOCOL_BITTORRENT
			  && (show_meter || is_in_state(download->state, S_RESUME)));
#endif

	redraw_windows(REDRAW_BEHIND_WINDOW, dlg_data->win);
	file_download->dlg_data = dlg_data;

	if (!msg) return;

	url = get_uri_string(file_download->uri, URI_PUBLIC);
	if (!url) {
		mem_free(msg);
		return;
	}
#ifdef CONFIG_UTF8
	if (term->utf8_cp)
		decode_uri(url);
	else
#endif /* CONFIG_UTF8 */
		decode_uri_for_display(url);
	url_len = strlen(url);

	if (show_meter) {
		int_lower_bound(&w, DOWN_DLG_MIN);
	}

	dlg_format_text_do(dlg_data, url, 0, &y, w, &rw,
			dialog_text_color, ALIGN_LEFT, 1);

	y++;
	if (show_meter) y += 2;

#if CONFIG_BITTORRENT
	if (bittorrent) y += 2;
#endif
	dlg_format_text_do(dlg_data, msg, 0, &y, w, &rw,
			dialog_text_color, ALIGN_LEFT, 1);

	y++;
	dlg_format_buttons(dlg_data, dlg_data->widgets_data,
			   dlg_data->number_of_widgets, 0, &y, w,
			   &rw, ALIGN_CENTER, 1);

	draw_dialog(dlg_data, w, y);

	w = rw;
	if (url_len > w) {
		/* Truncate too long urls */
		url_len = w;
		url[url_len] = '\0';
		if (url_len > 4) {
			url[--url_len] = '.';
			url[--url_len] = '.';
			url[--url_len] = '.';
		}
	}

	y = dlg_data->box.y + DIALOG_TB + 1;
	x = dlg_data->box.x + DIALOG_LB;
	dlg_format_text_do(dlg_data, url, x, &y, w, NULL,
			dialog_text_color, ALIGN_LEFT, 0);

	if (show_meter) {
		y++;
		draw_progress_bar(download->progress, term, x, y, w, NULL, NULL);
		y++;
	}

#if CONFIG_BITTORRENT
	if (bittorrent) {
		y++;
		draw_bittorrent_piece_progress(download, term, x, y, w, NULL, NULL);
		y++;
	}
#endif
	y++;
	dlg_format_text_do(dlg_data, msg, x, &y, w, NULL,
			dialog_text_color, ALIGN_LEFT, 0);

	y++;
	dlg_format_buttons(dlg_data, dlg_data->widgets_data,
			   dlg_data->number_of_widgets, x, &y, w,
			   NULL, ALIGN_CENTER, 0);

	mem_free(url);
	mem_free(msg);
}
int main() {
	
	COMMAND cmd;
	ARG args = {0,0};
	void *res, *addr;
	ID id;
	size_t size;	

  
	init(); /* initialisation de l'interpreteur */
    	
	while(1) {
#ifdef DEBUG
		printf("memshell-main: debut de la boucle de l'interpreteur\n");
#endif
      		
		printf(PROMPT);
		
		cmd = read_command(&args);
		switch(cmd) {
			
		case INIT:
				
			printf("Réinitialisation de la mémoire (%d octets)...", HEAP_SIZE);
			mem_init();
			printf("OK\n");			
			break;
			
		case SHOW:			
			printf("Mémoire initialement disponible : %d octets débutant en %p\n", HEAP_SIZE, zone_memoire);
			break;

		case USED:
			used();
			break;
			
		case ALLOC:

			res = mem_alloc(args.size);
			/* si une erreur a lieu, on affiche 0 */
			if (res == NULL) {
				printf("Erreur : échec de l'allocation (fonction mem_alloc, retour=NULL)\n");
			} else {
				id = get_id(res, args.size);
				if (id == 0) {
					/* s'il ne reste pas d'id libre
					   on affiche 0 et on libere le bloc */
					printf("Erreur : nombre maximum d'allocations atteint/n");
					mem_free(res, args.size);
				} else { /* pas de probleme, affichage de la zone allouée */
					printf("%ld 0x%lX\n", id, (unsigned long)(res - (void*)zone_memoire));
				}
			}
			break;
				

		case DESTROY: 
			mem_destroy();
			break;

		case FREE:
						
			if (get_info_from_id(args.id, &addr, &size) == -1)
				/* erreur dans la valeur de l'id */
				printf("Erreur : identificateur de bloc incorrect\n"); 
			else {
							
							
				/* liberation du bloc concerne */
				mem_free(addr, size);
									
				/* liberation de l'id */
				remove_id(args.id);
								
				/* NB : dans le cas normal, on n'affiche rien */
			}
			break;
				
				
		case HELP:
			help();
			break;
				
		case EXIT:
			mem_destroy();
			goto end;	
			
		case ERROR:
			
			printf("Commande incorrecte\n");
			break;
		}
			
	}
end: return 0;
}
Beispiel #20
0
int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser)
{
	CSkins *pSelf = (CSkins *)pUser;
	int l = str_length(pName);
	if(l < 4 || IsDir || str_comp(pName+l-4, ".png") != 0)
		return 0;

	char aBuf[512];
	str_format(aBuf, sizeof(aBuf), "skins/%s", pName);
	CImageInfo Info;
	if(!pSelf->Graphics()->LoadPNG(&Info, aBuf, DirType))
	{
		str_format(aBuf, sizeof(aBuf), "failed to load skin from %s", pName);
		pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf);
		return 0;
	}

	CSkin Skin;
	Skin.m_OrgTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);

	int BodySize = 96; // body size
	unsigned char *d = (unsigned char *)Info.m_pData;
	int Pitch = Info.m_Width*4;

	// dig out blood color
	{
		int aColors[3] = {0};
		for(int y = 0; y < BodySize; y++)
			for(int x = 0; x < BodySize; x++)
			{
				if(d[y*Pitch+x*4+3] > 128)
				{
					aColors[0] += d[y*Pitch+x*4+0];
					aColors[1] += d[y*Pitch+x*4+1];
					aColors[2] += d[y*Pitch+x*4+2];
				}
			}

		Skin.m_BloodColor = normalize(vec3(aColors[0], aColors[1], aColors[2]));
	}

	// create colorless version
	int Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3;

	// make the texture gray scale
	for(int i = 0; i < Info.m_Width*Info.m_Height; i++)
	{
		int v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3;
		d[i*Step] = v;
		d[i*Step+1] = v;
		d[i*Step+2] = v;
	}


	int Freq[256] = {0};
	int OrgWeight = 0;
	int NewWeight = 192;

	// find most common frequence
	for(int y = 0; y < BodySize; y++)
		for(int x = 0; x < BodySize; x++)
		{
			if(d[y*Pitch+x*4+3] > 128)
				Freq[d[y*Pitch+x*4]]++;
		}

	for(int i = 1; i < 256; i++)
	{
		if(Freq[OrgWeight] < Freq[i])
			OrgWeight = i;
	}

	// reorder
	int InvOrgWeight = 255-OrgWeight;
	int InvNewWeight = 255-NewWeight;
	for(int y = 0; y < BodySize; y++)
		for(int x = 0; x < BodySize; x++)
		{
			int v = d[y*Pitch+x*4];
			if(v <= OrgWeight)
				v = (int)(((v/(float)OrgWeight) * NewWeight));
			else
				v = (int)(((v-OrgWeight)/(float)InvOrgWeight)*InvNewWeight + NewWeight);
			d[y*Pitch+x*4] = v;
			d[y*Pitch+x*4+1] = v;
			d[y*Pitch+x*4+2] = v;
		}

	Skin.m_ColorTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);
	mem_free(Info.m_pData);

	// set skin data
	str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-3));
	if(g_Config.m_Debug)
	{
		str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName);
		pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf);
	}
	pSelf->m_aSkins.add(Skin);

	return 0;
}
Beispiel #21
0
_export
void scr_close(struct scr_t *scr)
{
	scr_impl_close(scr->impl);
	mem_free(scr);
}
Beispiel #22
0
bool evaluate_top()
{
    if(!optic_stack.size())
    {
        out() << "Instruction stack is empty, cannot evaluate expression." << std::endl;
        clear_stack();
        return false;
    }

//    std::cout << "evaluate_top()" << std::endl;
    object obj = optic_stack.back();
    optic_stack.pop_back();
    bool result = true;
    bool free_obj = true;

    switch(obj.type)
    {
    case OPERATION:
        result = evaluate_binary_operator(obj);
        break;

    case NO_EXPANSION_OPERATION:
        result = evaluate_binary_operator(obj, false);
        break;

    case UNARY_OPERATION:
        result = evaluate_unary_operator(obj);
        break;

    case UNARY_NO_EXPANSION_OPERATION:
        result = evaluate_unary_operator(obj, false);
        break;

//    case FUNCTION_BODY:
    case OPERATION_TREE:
        result = resolve_stack_from_parser(obj, false);
        break;

    case VARIABLE:
    case UNDECLARED_VARIABLE:
        result = evaluate_variable(obj);
        break;

    case ASSIGNMENT:
        result = evaluate_assignment();
        break;

    case VOID: // don't return
        break;

    default:
        optic_stack.push_back(obj);
        free_obj = false;
        break;
    }

    if(free_obj)
        mem_free(obj);

    return result;
}
Beispiel #23
0
char * 
regexp_replace(char * from, char *to, char *text)
{
	int nmat, offset = 0, textlen;
	int ovec[MAXCAPTURE];
	char *res, *ret, *pom;
	const char *overfl = NULL;	/* warning, go away */
	int global, i;
#ifdef HAVE_PCRE
	const char *er_ptr;
	int erroffset;
#else
	regmatch_t pmat[MAXCAPTURE/3];
	regex_t ppat_data;
	regex_t *ppat;
#endif

	if( from == NULL || to == NULL || text == NULL)
	{
		if(text == NULL) return NULL;
		ret = (unsigned char *)js_mem_alloc(strlen(text)+1);
		strcpy(ret,text);
		return ret;
	}
	while(*from == ' ' || *from == '\t') from++;
#ifdef HAVE_PCRE
	pom = pcre_malloc(strlen(from)+1);
#else /* HAVE_PCRE */
	pom = mem_alloc(strlen(from)+1);
#endif /* HAVE_PCRE */
	if(*from != '/')
	{
		strcpy(pom, from);
		global = 0;
	}
	else
	{
		for( i = strlen(from)-1; i > 1 && (from[i] == ' ' || from[i] == '\t'); i--);
		if( from[i] == '/')
		{
			strncpy(pom, from+1, i-1);
			pom[i-1] = '\0';
			global = 0;
		}else if( i > 1 && from[i] == 'g' && from[i-1] == '/')
		{
			strncpy(pom, from+1, i-2);
			pom[i-2] = '\0';
			global = 1;
		}else
		{
			strncpy(pom, from, i+1);
			pom[i+1] = '\0';
			global = 0;
		}
	}
#ifdef REGEX_DEBUG
	printf("Search pattern is '%s', global = %d\n",pom,global);
#endif /* REGEX_DEBUG */
	
#ifdef HAVE_PCRE
	pcre *ppat = pcre_compile(pom, 0/*PCRE_ANCHORED*/, &er_ptr, &erroffset, NULL);
	pcre_free(pom);
#else /* HAVE_PCRE */
	ppat = &ppat_data;
	if (regcomp(ppat, pom, REG_EXTENDED)) ppat = NULL;
	mem_free(pom);
#endif /* HAVE_PCRE */
	if (ppat == NULL)
	{
		if(text == NULL) return NULL;
		ret = (unsigned char *)js_mem_alloc(strlen(text)+1);
		strcpy(ret,text);
		return ret;
	}
	textlen = strlen(text);
#ifdef HAVE_PCRE
	res = pcre_malloc(MAXCAPTURE+textlen);
#else /* HAVE_PCRE */
	res = mem_alloc(MAXCAPTURE+textlen);
#endif /* HAVE_PCRE */
	cp = res;
	ep = res+MAXCAPTURE+textlen;
	if(global)
	{
		do {
#ifdef HAVE_PCRE
			nmat = pcre_exec(ppat, NULL, text, textlen, offset, 0, ovec, sizeof(ovec)/sizeof(int));
#else /* HAVE_PCRE */
			if (regexec(ppat, text+offset, MAXCAPTURE/3, pmat, 0))
				nmat = 0;
			else
				for( nmat = 0; nmat < MAXCAPTURE/3; nmat++ )
					if((ovec[nmat<<1] = pmat[nmat].rm_so) == -1 ||
						(ovec[(nmat<<1)+1] = pmat[nmat].rm_eo) == -1) break;
#endif /* HAVE_PCRE */
#ifdef HAVE_PCRE
			for(i = 0; i < nmat*2; i++)
				ovec[i]-=offset;
#endif /* HAVE_PCRE */
#ifdef REGEX_DEBUG
			dumpmatch(text+offset, textlen-offset, to, nmat, ovec);
#endif /* REGEX_DEBUG */
			if(nmat > 0)
			{
				overfl = edit(text+offset, textlen - offset, to, nmat, ovec, res);
				offset += ovec[1];
			}
		} while (nmat >0 && overfl);
	}
	else
	{
#ifdef HAVE_PCRE
		nmat = pcre_exec(ppat, NULL, text, textlen, 0, 0, ovec, sizeof(ovec)/sizeof(int));
#else /* HAVE_PCRE */
		 if (regexec(ppat, text, MAXCAPTURE/3, pmat, 0))
			 nmat = 0;
		 else
			 for( nmat = 0; nmat < MAXCAPTURE/3; nmat++ )
				 if((ovec[nmat<<1] = pmat[nmat].rm_so) == -1 ||
					(ovec[(nmat<<1)+1] = pmat[nmat].rm_eo) == -1) break;
#endif /* HAVE_PCRE */

#ifdef REGEX_DEBUG
		dumpmatch(text+offset, textlen-offset, to, nmat, ovec);
#endif /* REGEX_DEBUG */
		if(nmat > 0)
		{
			overfl = edit(text+offset, textlen - offset, to, nmat, ovec, res);
			offset += ovec[1];
		}
	}
	
	if ( textlen >= offset && cp + textlen - offset < ep)
	{
		strncpy(cp, text+offset, textlen - offset);
		*(cp +textlen - offset) = '\0';
	}
	else
		*(ep-1) = '\0';
	ret = (unsigned char *)js_mem_alloc(strlen(res)+1);
	strcpy(ret,res);
#ifdef HAVE_PCRE
	pcre_free(res);
	pcre_free(ppat);
#else /* HAVE_PCRE */
	mem_free(res);
	regfree(ppat);
#endif /* HAVE_PCRE */
	return ret;
}
Beispiel #24
0
void
recipe_list_delete(recipe_list_ty *rlp)
{
    recipe_list_destructor(rlp);
    mem_free(rlp);
}
Beispiel #25
0
static int
verify_certificates(struct socket *socket)
{
	gnutls_x509_crt_t cert;
	gnutls_session_t session = *(ssl_t *)socket->ssl;
	struct connection *conn = socket->conn;
	const gnutls_datum_t *cert_list;
	unsigned char *hostname;
	int ret;
	unsigned int cert_list_size, status;


	ret = gnutls_certificate_verify_peers2(session, &status);
	if (ret) return ret;
	if (status) return status;

	/* If the certificate is of a type for which verification has
	 * not yet been implemented, then reject it.  This way, a fake
	 * server cannot avoid verification by using a strange type of
	 * certificate.
	 *
	 * OpenPGP certificates shouldn't even get this far anyway,
	 * because init_ssl_connection() tells GnuTLS to disable
	 * OpenPGP, and ELinks never calls
	 * gnutls_certificate_set_openpgp_keyring_file, so status
	 * should have been GNUTLS_CERT_SIGNER_NOT_FOUND.  */
	if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
		return -7;

	if (gnutls_x509_crt_init(&cert) < 0) {
		return -1;
	}

	cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
	if (!cert_list) {
		return -2;
	}

	if (gnutls_x509_crt_import(cert, &cert_list[0],
		GNUTLS_X509_FMT_DER) < 0) {
		return -3;
	}
	if (gnutls_x509_crt_get_expiration_time(cert) < time(NULL)) {
		gnutls_x509_crt_deinit(cert);
		return -4;
	}

	if (gnutls_x509_crt_get_activation_time(cert) > time(NULL)) {
		gnutls_x509_crt_deinit(cert);
		return -5;
	}

	/* Because RFC 5280 defines dNSName as an IA5String, it can
	 * only contain ASCII characters.  Internationalized domain
	 * names must thus be in Punycode form.  Because GnuTLS 2.8.6
	 * does not itself support IDN, ELinks must convert.  */
	hostname = get_uri_string(conn->uri, URI_HOST | URI_IDN);
	if (!hostname) return -6;

	ret = !gnutls_x509_crt_check_hostname(cert, hostname);
	gnutls_x509_crt_deinit(cert);
	mem_free(hostname);
	return ret;
}
Beispiel #26
0
/**
 * Allocate and initialize memory, buffers, pages, PWM, DMA, and GPIO.
 *
 * @param    ws2811  ws2811 instance pointer.
 *
 * @returns  0 on success, -1 otherwise.
 */
int ws2811_init(ws2811_t *ws2811)
{
    ws2811_device_t *device = NULL;
    int chan;

    // Zero mbox; non-zero values indicate action needed on cleanup
    memset(&mbox, 0, sizeof(mbox));

    ws2811->device = malloc(sizeof(*ws2811->device));
    if (!ws2811->device)
    {
        return -1;
    }
    device = ws2811->device;

    // Determine how much physical memory we need for DMA
    mbox.size = PWM_BYTE_COUNT(max_channel_led_count(ws2811), ws2811->freq) +
               + sizeof(dma_cb_t);
    // Round up to page size multiple
    mbox.size = (mbox.size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);

    // Use the mailbox interface to request memory from the VideoCore
    // We specifiy (-1) for the handle rather than calling mbox_open()
    // so multiple users can share the resource.
    mbox.handle = -1; // mbox_open();
    mbox.mem_ref = mem_alloc(mbox.handle, mbox.size, PAGE_SIZE,
            board_info_sdram_address() == 0x40000000 ? 0xC : 0x4);
    if (mbox.mem_ref == (unsigned) ~0)
    {
       return -1;
    }
    mbox.bus_addr = mem_lock(mbox.handle, mbox.mem_ref);
    if (mbox.bus_addr == (unsigned) ~0)
    {
       mem_free(mbox.handle, mbox.size);
       return -1;
    }
    mbox.virt_addr = mapmem(BUS_TO_PHYS(mbox.bus_addr), mbox.size);

    // Initialize all pointers to NULL.  Any non-NULL pointers will be freed on cleanup.
    device->pwm_raw = NULL;
    device->dma_cb = NULL;
    for (chan = 0; chan < RPI_PWM_CHANNELS; chan++)
    {
        ws2811->channel[chan].leds = NULL;
    }

    // Allocate the LED buffers
    for (chan = 0; chan < RPI_PWM_CHANNELS; chan++)
    {
        ws2811_channel_t *channel = &ws2811->channel[chan];

        channel->leds = malloc(sizeof(ws2811_led_t) * channel->count);
        if (!channel->leds)
        {
            goto err;
        }

        memset(channel->leds, 0, sizeof(ws2811_led_t) * channel->count);
    }

    device->dma_cb = (dma_cb_t *)mbox.virt_addr;
    device->pwm_raw = (uint8_t *)mbox.virt_addr + sizeof(dma_cb_t);

    pwm_raw_init(ws2811);

    memset((dma_cb_t *)device->dma_cb, 0, sizeof(dma_cb_t));

    // Cache the DMA control block bus address
    device->dma_cb_addr = addr_to_bus(device->dma_cb);

    // Map the physical registers into userspace
    if (map_registers(ws2811))
    {
        goto err;
    }

    // Initialize the GPIO pins
    if (gpio_init(ws2811))
    {
        unmap_registers(ws2811);
        goto err;
    }

    // Setup the PWM, clocks, and DMA
    if (setup_pwm(ws2811))
    {
        unmap_registers(ws2811);
        goto err;
    }

    return 0;

err:
    ws2811_cleanup(ws2811);

    return -1;
}
Beispiel #27
0
int CSound::LoadWV(const char *pFilename)
{
	CSample *pSample;
	int SampleID = -1;
	char aError[100];
	WavpackContext *pContext;

	// don't waste memory on sound when we are stress testing
	if(g_Config.m_DbgStress)
		return -1;

	// no need to load sound when we are running with no sound
	if(!m_SoundEnabled)
		return 1;

	if(!m_pStorage)
		return -1;

	ms_File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);
	if(!ms_File)
	{
		dbg_msg("sound/wv", "failed to open file. filename='%s'", pFilename);
		return -1;
	}

	SampleID = AllocID();
	if(SampleID < 0)
		return -1;
	pSample = &m_aSamples[SampleID];

	pContext = WavpackOpenFileInput(ReadData, aError);
	if (pContext)
	{
		int m_aSamples = WavpackGetNumSamples(pContext);
		int BitsPerSample = WavpackGetBitsPerSample(pContext);
		unsigned int SampleRate = WavpackGetSampleRate(pContext);
		int m_aChannels = WavpackGetNumChannels(pContext);
		int *pData;
		int *pSrc;
		short *pDst;
		int i;

		pSample->m_Channels = m_aChannels;
		pSample->m_Rate = SampleRate;

		if(pSample->m_Channels > 2)
		{
			dbg_msg("sound/wv", "file is not mono or stereo. filename='%s'", pFilename);
			return -1;
		}

		/*
		if(snd->rate != 44100)
		{
			dbg_msg("sound/wv", "file is %d Hz, not 44100 Hz. filename='%s'", snd->rate, filename);
			return -1;
		}*/

		if(BitsPerSample != 16)
		{
			dbg_msg("sound/wv", "bps is %d, not 16, filname='%s'", BitsPerSample, pFilename);
			return -1;
		}

		pData = (int *)mem_alloc(4*m_aSamples*m_aChannels, 1);
		WavpackUnpackSamples(pContext, pData, m_aSamples); // TODO: check return value
		pSrc = pData;

		pSample->m_pData = (short *)mem_alloc(2*m_aSamples*m_aChannels, 1);
		pDst = pSample->m_pData;

		for (i = 0; i < m_aSamples*m_aChannels; i++)
			*pDst++ = (short)*pSrc++;

		mem_free(pData);

		pSample->m_NumFrames = m_aSamples;
		pSample->m_LoopStart = -1;
		pSample->m_LoopEnd = -1;
		pSample->m_PausedAt = 0;
	}
	else
	{
		dbg_msg("sound/wv", "failed to open %s: %s", pFilename, aError);
	}

	io_close(ms_File);
	ms_File = NULL;

	if(g_Config.m_Debug)
		dbg_msg("sound/wv", "loaded %s", pFilename);

	RateConvert(SampleID);
	return SampleID;
}
Beispiel #28
0
/*
 * Create a new transport for a socket optained via soaccept().
 */
SVCXPRT *
svc_vc_create_conn(SVCPOOL *pool, struct socket *so, struct sockaddr *raddr)
{
	SVCXPRT *xprt = NULL;
	struct cf_conn *cd = NULL;
	struct sockaddr* sa = NULL;
	struct sockopt opt;
	int one = 1;
	int error;

	bzero(&opt, sizeof(struct sockopt));
	opt.sopt_dir = SOPT_SET;
	opt.sopt_level = SOL_SOCKET;
	opt.sopt_name = SO_KEEPALIVE;
	opt.sopt_val = &one;
	opt.sopt_valsize = sizeof(one);
	error = sosetopt(so, &opt);
	if (error) {
		return (NULL);
	}

	if (so->so_proto->pr_protocol == IPPROTO_TCP) {
		bzero(&opt, sizeof(struct sockopt));
		opt.sopt_dir = SOPT_SET;
		opt.sopt_level = IPPROTO_TCP;
		opt.sopt_name = TCP_NODELAY;
		opt.sopt_val = &one;
		opt.sopt_valsize = sizeof(one);
		error = sosetopt(so, &opt);
		if (error) {
			return (NULL);
		}
	}

	cd = mem_alloc(sizeof(*cd));
	cd->strm_stat = XPRT_IDLE;

	xprt = svc_xprt_alloc();
	sx_init(&xprt->xp_lock, "xprt->xp_lock");
	xprt->xp_pool = pool;
	xprt->xp_socket = so;
	xprt->xp_p1 = cd;
	xprt->xp_p2 = NULL;
	xprt->xp_ops = &svc_vc_ops;

	/*
	 * See http://www.connectathon.org/talks96/nfstcp.pdf - client
	 * has a 5 minute timer, server has a 6 minute timer.
	 */
	xprt->xp_idletimeout = 6 * 60;

	memcpy(&xprt->xp_rtaddr, raddr, raddr->sa_len);

	CURVNET_SET(so->so_vnet);
	error = so->so_proto->pr_usrreqs->pru_sockaddr(so, &sa);
	CURVNET_RESTORE();
	if (error)
		goto cleanup_svc_vc_create;

	memcpy(&xprt->xp_ltaddr, sa, sa->sa_len);
	free(sa, M_SONAME);

	xprt_register(xprt);

	SOCKBUF_LOCK(&so->so_rcv);
	xprt->xp_upcallset = 1;
	soupcall_set(so, SO_RCV, svc_vc_soupcall, xprt);
	SOCKBUF_UNLOCK(&so->so_rcv);

	/*
	 * Throw the transport into the active list in case it already
	 * has some data buffered.
	 */
	sx_xlock(&xprt->xp_lock);
	xprt_active(xprt);
	sx_xunlock(&xprt->xp_lock);

	return (xprt);
cleanup_svc_vc_create:
	if (xprt) {
		sx_destroy(&xprt->xp_lock);
		svc_xprt_free(xprt);
	}
	if (cd)
		mem_free(cd, sizeof(*cd));
	return (NULL);
}
Beispiel #29
0
cedarx_result_e libcedarx_decoder_open(cedarx_info_t* info)
{
  cedarx_result_e result;
  vconfig_t config;
  vstream_info_t stream_info;
  cedarx_decoder_t* decoder;
  
  if (!info) 
    return CEDARX_RESULT_INVALID_ARGS;
    
  decoder = (cedarx_decoder_t*)mem_alloc(sizeof(cedarx_decoder_t));
  if (!decoder)
    return CEDARX_RESULT_NO_ENOUGH_MEMORY;

  mem_set(decoder, 0, sizeof(cedarx_decoder_t));
  cedarx_decoder = decoder;
  
  result = ve_init();
  if (CEDARX_RESULT_OK != result) 
    goto failed2;
          
  mem_set(&config, 0, sizeof(vconfig_t));
  mem_set(&stream_info, 0, sizeof(vstream_info_t));
  
  config.max_video_width  = MAX_SUPPORTED_VIDEO_WIDTH;
  config.max_video_height = MAX_SUPPORTED_VIDEO_HEIGHT;
  config.max_output_width = MAX_SUPPORTED_OUTPUT_WIDTH; 
  config.max_output_height = MAX_SUPPORTED_OUTPUT_HEIGHT;

  switch (info->stream)
  {
    case CEDARX_STREAM_FORMAT_MPEG1:
      stream_info.format = STREAM_FORMAT_MPEG2;
      stream_info.sub_format = MPEG2_SUB_FORMAT_MPEG1;
      break;    
    case CEDARX_STREAM_FORMAT_MPEG2:
      stream_info.format = STREAM_FORMAT_MPEG2;
      stream_info.sub_format = MPEG2_SUB_FORMAT_MPEG2;
      break;    
    case CEDARX_STREAM_FORMAT_XVID:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_XVID;
      break;    
    case CEDARX_STREAM_FORMAT_DIVX1:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_DIVX1;
      break;    
    case CEDARX_STREAM_FORMAT_DIVX2:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_DIVX2;
      break;    
    case CEDARX_STREAM_FORMAT_DIVX3:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_DIVX3;
      break;    
    case CEDARX_STREAM_FORMAT_DIVX4:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_DIVX4;
      break;    
    case CEDARX_STREAM_FORMAT_DIVX5:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_DIVX5;
      break;    
    case CEDARX_STREAM_FORMAT_H263:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_H263;
      break;    
    case CEDARX_STREAM_FORMAT_SORENSSON_H263:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_SORENSSON_H263;
      break;    
    case CEDARX_STREAM_FORMAT_WMV1:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_WMV1;
      break;    
    case CEDARX_STREAM_FORMAT_WMV2:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_WMV2;
      break;    
    case CEDARX_STREAM_FORMAT_VP6:
      stream_info.format = STREAM_FORMAT_MPEG4;
      stream_info.sub_format = MPEG4_SUB_FORMAT_VP6;
      break;    
    case CEDARX_STREAM_FORMAT_REALVIDEO:
      stream_info.format = STREAM_FORMAT_REALVIDEO;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      break;    
    case CEDARX_STREAM_FORMAT_H264:
      stream_info.format = STREAM_FORMAT_H264;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      decoder->greedy = 1;
      break;    
    case CEDARX_STREAM_FORMAT_AVC1:
      stream_info.format = STREAM_FORMAT_H264;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      decoder->greedy = 1;
      break;    
    case CEDARX_STREAM_FORMAT_VC1:
      stream_info.format = STREAM_FORMAT_VC1;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      break;    
    case CEDARX_STREAM_FORMAT_AVS:
      stream_info.format = STREAM_FORMAT_AVS;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      break;    
    case CEDARX_STREAM_FORMAT_MJPEG:
      stream_info.format = STREAM_FORMAT_MJPEG;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      break;    
    case CEDARX_STREAM_FORMAT_VP8:
      stream_info.format = STREAM_FORMAT_VP8;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      break;
    default:
      stream_info.format = STREAM_FORMAT_H264;
      stream_info.sub_format = STREAM_SUB_FORMAT_UNKNOW;
      break;
  } 

  switch (info->container)
  {
    case CEDARX_CONTAINER_FORMAT_AVI:
      stream_info.container_format = CONTAINER_FORMAT_AVI;
      break;
    case CEDARX_CONTAINER_FORMAT_ASF:
      stream_info.container_format = CONTAINER_FORMAT_ASF;
      break;
    case CEDARX_CONTAINER_FORMAT_DAT:
      stream_info.container_format = CONTAINER_FORMAT_DAT;
      break;
    case CEDARX_CONTAINER_FORMAT_FLV:
      stream_info.container_format = CONTAINER_FORMAT_FLV;
      break;
    case CEDARX_CONTAINER_FORMAT_MKV:
      stream_info.container_format = CONTAINER_FORMAT_MKV;
      break;
    case CEDARX_CONTAINER_FORMAT_MOV:
      stream_info.container_format = CONTAINER_FORMAT_MOV;
      break;
    case CEDARX_CONTAINER_FORMAT_MPG:
      stream_info.container_format = CONTAINER_FORMAT_MPG;
      break;
    case CEDARX_CONTAINER_FORMAT_PMP:
      stream_info.container_format = CONTAINER_FORMAT_PMP;
      break;
    case CEDARX_CONTAINER_FORMAT_RM:
      stream_info.container_format = CONTAINER_FORMAT_RM;
      break;
    case CEDARX_CONTAINER_FORMAT_TS:
      stream_info.container_format = CONTAINER_FORMAT_TS;
      stream_info.is_pts_correct = 1;
      break;
    case CEDARX_CONTAINER_FORMAT_VOB:
      stream_info.container_format = CONTAINER_FORMAT_VOB;
      break;
    case CEDARX_CONTAINER_FORMAT_WEBM:
      stream_info.container_format = CONTAINER_FORMAT_WEBM;
      break;
    case CEDARX_CONTAINER_FORMAT_OGM:
      stream_info.container_format = CONTAINER_FORMAT_OGM;
      break;
    default:
      stream_info.container_format = CONTAINER_FORMAT_UNKNOW;
      break;
  }

  stream_info.video_width = info->width;
  stream_info.video_height = info->height;
  stream_info.frame_rate = info->frame_rate;
  stream_info.frame_duration = info->frame_duration;
  stream_info.aspec_ratio = 1000;

  if (info->data && (info->data_size > 0)) {
    decoder->init_data = mem_alloc(info->data_size);
    if (!decoder->init_data)
        goto failed2;
    mem_cpy(decoder->init_data, info->data, info->data_size);
    stream_info.init_data = decoder->init_data;
    stream_info.init_data_len = info->data_size;
  } else {
    stream_info.init_data_len = 0;
    stream_info.init_data = NULL;
  }
  stream_info._3d_mode = _3D_MODE_NONE;

  mem_init(decoder->fd);
  ve_request();

  if (info->request_buffer)
    decoder->request_buffer = info->request_buffer;
  if (info->update_buffer)
    decoder->update_buffer = info->update_buffer;
  if (info->release_buffer)
    decoder->release_buffer = info->release_buffer;
  if (info->lock_buffer)
    decoder->lock_buffer = info->lock_buffer;
  if (info->unlock_buffer)
    decoder->unlock_buffer = info->unlock_buffer;
 
  decoder->sys = info->sys;
  decoder->ve = libve_open(&config, &stream_info, decoder);
  if (!decoder->ve) {
    result = CEDARX_RESULT_VE_FAILED;
    goto failed1;
  }
    
  decoder->vbv = vbv_init();
  if (!decoder->vbv) {
    result = CEDARX_RESULT_NO_ENOUGH_MEMORY;
    goto failed1;
  }
    
  libve_set_vbv(decoder->vbv, decoder->ve);
  return CEDARX_RESULT_OK; 
   
failed1:
  ve_release();
  mem_exit();
  ve_exit();
  if (decoder->init_data)
    mem_free(decoder->init_data);
failed2:
  mem_free(decoder); 
  cedarx_decoder = NULL;
  return result;    
}
/*
 * Create a client handle for a tcp/ip connection.
 * If *sockp<0, *sockp is set to a newly created TCP socket and it is
 * connected to raddr.  If *sockp non-negative then
 * raddr is ignored.  The rpc/tcp package does buffering
 * similar to stdio, so the client must pick send and receive buffer sizes,];
 * 0 => use the default.
 * If raddr->sin_port is 0, then a binder on the remote machine is
 * consulted for the right port number.
 * NB: *sockp is copied into a private area.
 * NB: It is the clients responsibility to close *sockp.
 * NB: The rpch->cl_auth is set null authentication.  Caller may wish to set this
 * something more useful.
 */
CLIENT *
clntunix_create (struct sockaddr_un *raddr, u_long prog, u_long vers,
		 int *sockp, u_int sendsz, u_int recvsz)
{
  CLIENT *h;
  struct ct_data *ct = (struct ct_data *) mem_alloc (sizeof (*ct));
  struct rpc_msg call_msg;
  int len;

  h = (CLIENT *) mem_alloc (sizeof (*h));
  if (h == NULL || ct == NULL)
    {
      struct rpc_createerr *ce = &get_rpc_createerr ();
      (void) __fxprintf (NULL, "%s: %s", __func__, _("out of memory\n"));
      ce->cf_stat = RPC_SYSTEMERROR;
      ce->cf_error.re_errno = ENOMEM;
      goto fooy;
    }

  /*
   * If no socket given, open one
   */
  if (*sockp < 0)
    {
      *sockp = __socket (AF_UNIX, SOCK_STREAM, 0);
      len = strlen (raddr->sun_path) + sizeof (raddr->sun_family) + 1;
      if (*sockp < 0
	  || __connect (*sockp, (struct sockaddr *) raddr, len) < 0)
	{
	  struct rpc_createerr *ce = &get_rpc_createerr ();
	  ce->cf_stat = RPC_SYSTEMERROR;
	  ce->cf_error.re_errno = errno;
	  if (*sockp != -1)
	    __close (*sockp);
	  goto fooy;
	}
      ct->ct_closeit = TRUE;
    }
  else
    {
      ct->ct_closeit = FALSE;
    }

  /*
   * Set up private data struct
   */
  ct->ct_sock = *sockp;
  ct->ct_wait.tv_usec = 0;
  ct->ct_waitset = FALSE;
  ct->ct_addr = *raddr;

  /*
   * Initialize call message
   */
  call_msg.rm_xid = _create_xid ();
  call_msg.rm_direction = CALL;
  call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
  call_msg.rm_call.cb_prog = prog;
  call_msg.rm_call.cb_vers = vers;

  /*
   * pre-serialize the static part of the call msg and stash it away
   */
  INTUSE(xdrmem_create) (&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE,
			 XDR_ENCODE);
  if (!INTUSE(xdr_callhdr) (&(ct->ct_xdrs), &call_msg))
    {
      if (ct->ct_closeit)
	__close (*sockp);
      goto fooy;
    }
  ct->ct_mpos = XDR_GETPOS (&(ct->ct_xdrs));
  XDR_DESTROY (&(ct->ct_xdrs));

  /*
   * Create a client handle which uses xdrrec for serialization
   * and authnone for authentication.
   */
  INTUSE(xdrrec_create) (&(ct->ct_xdrs), sendsz, recvsz,
			 (caddr_t) ct, readunix, writeunix);
  h->cl_ops = (struct clnt_ops *) &unix_ops;
  h->cl_private = (caddr_t) ct;
  h->cl_auth = INTUSE(authnone_create) ();
  return h;

fooy:
  /*
   * Something goofed, free stuff and barf
   */
  mem_free ((caddr_t) ct, sizeof (struct ct_data));
  mem_free ((caddr_t) h, sizeof (CLIENT));
  return (CLIENT *) NULL;
}