Exemple #1
0
static void test_autocreation(void)
{
    HKEY key, eventkey;
    DWORD type, size;
    LONG ret;
    int i;
    char *p;
    char sources[sizeof(eventsources)];
    char sysdir[MAX_PATH];
    void *redir = 0;

    RegOpenKeyA(HKEY_LOCAL_MACHINE, eventlogsvc, &key);
    RegOpenKeyA(key, eventlogname, &eventkey);

    size = sizeof(sources);
    sources[0] = 0;
    ret = RegQueryValueExA(eventkey, "Sources", NULL, &type, (LPBYTE)sources, &size);
    if (ret == ERROR_SUCCESS)
    {
        char sources_verify[sizeof(eventsources)];

        ok(type == REG_MULTI_SZ, "Expected a REG_MULTI_SZ, got %d\n", type);

        /* Build the expected string */
        memset(sources_verify, 0, sizeof(sources_verify));
        p = sources_verify;
        for (i = sizeof(eventsources)/sizeof(eventsources[0]); i > 0; i--)
        {
            lstrcpyA(p, eventsources[i - 1]);
            p += (lstrlenA(eventsources[i - 1]) + 1);
        }
        lstrcpyA(p, eventlogname);

        ok(!memcmp(sources, sources_verify, size),
           "Expected a correct 'Sources' value (size : %d)\n", size);
    }

    RegCloseKey(eventkey);
    RegCloseKey(key);

    /* The directory that holds the eventlog files could be redirected */
    if (pWow64DisableWow64FsRedirection)
        pWow64DisableWow64FsRedirection(&redir);

    /* On Windows we also automatically get an eventlog file */
    GetSystemDirectoryA(sysdir, sizeof(sysdir));

    /* NT4 - W2K3 */
    lstrcpyA(eventlogfile, sysdir);
    lstrcatA(eventlogfile, "\\config\\");
    lstrcatA(eventlogfile, eventlogname);
    lstrcatA(eventlogfile, ".evt");

    if (GetFileAttributesA(eventlogfile) == INVALID_FILE_ATTRIBUTES)
    {
        /* Vista+ */
        lstrcpyA(eventlogfile, sysdir);
        lstrcatA(eventlogfile, "\\winevt\\Logs\\");
        lstrcatA(eventlogfile, eventlogname);
        lstrcatA(eventlogfile, ".evtx");
    }

    todo_wine
    ok(GetFileAttributesA(eventlogfile) != INVALID_FILE_ATTRIBUTES,
       "Expected an eventlog file\n");

    if (pWow64RevertWow64FsRedirection)
        pWow64RevertWow64FsRedirection(redir);
}
Exemple #2
0
static int wpa_set_associate(PSDevice pDevice,
				     struct viawget_wpa_param *param)
{
    PSMgmtObject    pMgmt = pDevice->pMgmt;
    PWLAN_IE_SSID   pItemSSID;
    unsigned char abyNullAddr[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    unsigned char abyWPAIE[64];
    int ret = 0;
    bool bWepEnabled=false;

	// set key type & algorithm
    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pairwise_suite = %d\n", param->u.wpa_associate.pairwise_suite);
    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "group_suite = %d\n", param->u.wpa_associate.group_suite);
    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "key_mgmt_suite = %d\n", param->u.wpa_associate.key_mgmt_suite);
    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "auth_alg = %d\n", param->u.wpa_associate.auth_alg);
    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "mode = %d\n", param->u.wpa_associate.mode);
    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "wpa_ie_len = %d\n", param->u.wpa_associate.wpa_ie_len);

	if (param->u.wpa_associate.wpa_ie_len) {
		if (!param->u.wpa_associate.wpa_ie)
			return -EINVAL;
		if (param->u.wpa_associate.wpa_ie_len > sizeof(abyWPAIE))
			return -EINVAL;
		if (copy_from_user(&abyWPAIE[0], param->u.wpa_associate.wpa_ie, param->u.wpa_associate.wpa_ie_len))
			return -EFAULT;
	}

	if (param->u.wpa_associate.mode == 1)
	    pMgmt->eConfigMode = WMAC_CONFIG_IBSS_STA;
	else
	    pMgmt->eConfigMode = WMAC_CONFIG_ESS_STA;
    // set ssid
	memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
    pItemSSID = (PWLAN_IE_SSID)pMgmt->abyDesireSSID;
    pItemSSID->byElementID = WLAN_EID_SSID;
	pItemSSID->len = param->u.wpa_associate.ssid_len;
	memcpy(pItemSSID->abySSID, param->u.wpa_associate.ssid, pItemSSID->len);
	// set bssid
    if (memcmp(param->u.wpa_associate.bssid, &abyNullAddr[0], 6) != 0)
        memcpy(pMgmt->abyDesireBSSID, param->u.wpa_associate.bssid, 6);
else
{
   bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, pItemSSID->abySSID);
}

    if (param->u.wpa_associate.wpa_ie_len == 0) {
	    if (param->u.wpa_associate.auth_alg & AUTH_ALG_SHARED_KEY)
            pMgmt->eAuthenMode = WMAC_AUTH_SHAREKEY;
	    else
            pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
	} else if (abyWPAIE[0] == RSN_INFO_ELEM) {
		if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_PSK)
			pMgmt->eAuthenMode = WMAC_AUTH_WPA2PSK;
		else
			pMgmt->eAuthenMode = WMAC_AUTH_WPA2;
	} else {
		if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_WPA_NONE)
			pMgmt->eAuthenMode = WMAC_AUTH_WPANONE;
		else if (param->u.wpa_associate.key_mgmt_suite == KEY_MGMT_PSK)
		    pMgmt->eAuthenMode = WMAC_AUTH_WPAPSK;
		else
		    pMgmt->eAuthenMode = WMAC_AUTH_WPA;
	}

	switch (param->u.wpa_associate.pairwise_suite) {
	case CIPHER_CCMP:
		pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
		break;
	case CIPHER_TKIP:
		pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
		break;
	case CIPHER_WEP40:
	case CIPHER_WEP104:
		pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
		bWepEnabled=true;
		break;
	case CIPHER_NONE:
		if (param->u.wpa_associate.group_suite == CIPHER_CCMP)
			pDevice->eEncryptionStatus = Ndis802_11Encryption3Enabled;
		else
			pDevice->eEncryptionStatus = Ndis802_11Encryption2Enabled;
		break;
	default:
		pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
	}

//DavidWang add for WPA_supplicant support open/share mode

      if (pMgmt->eAuthenMode == WMAC_AUTH_SHAREKEY) {
            pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
            //pMgmt->eAuthenMode = WMAC_AUTH_SHAREKEY;
            pMgmt->bShareKeyAlgorithm = true;
             }
     else if (pMgmt->eAuthenMode == WMAC_AUTH_OPEN) {
          if(!bWepEnabled)  pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
	else pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
            //pMgmt->eAuthenMode = WMAC_AUTH_OPEN;
            //pMgmt->bShareKeyAlgorithm = false; //20080717-06,<Modify> by chester//Fix Open mode, WEP encrytion
           }
//mike save old encryption status
	pDevice->eOldEncryptionStatus = pDevice->eEncryptionStatus;

    if (pDevice->eEncryptionStatus !=  Ndis802_11EncryptionDisabled)
        pDevice->bEncryptionEnable = true;
    else
        pDevice->bEncryptionEnable = false;
if (!((pMgmt->eAuthenMode == WMAC_AUTH_SHAREKEY) ||
      ((pMgmt->eAuthenMode == WMAC_AUTH_OPEN) && (bWepEnabled==true))) )  //DavidWang  //20080717-06,<Modify> by chester//Not to initial WEP
    KeyvInitTable(&pDevice->sKey, pDevice->PortOffset);
    spin_lock_irq(&pDevice->lock);
    pDevice->bLinkPass = false;
    memset(pMgmt->abyCurrBSSID, 0, 6);
    pMgmt->eCurrState = WMAC_STATE_IDLE;
    netif_stop_queue(pDevice->dev);
	//20080701-02,<Add> by Mike Liu
/*******search if ap_scan=2 ,which is associating request in hidden ssid mode ****/
{
   PKnownBSS       pCurr = NULL;
    pCurr = BSSpSearchBSSList(pDevice,
                              pMgmt->abyDesireBSSID,
                              pMgmt->abyDesireSSID,
                              pMgmt->eConfigPHYMode
                              );

    if (pCurr == NULL){
    printk("wpa_set_associate---->hidden mode site survey before associate.......\n");
    bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
  }
}
/****************************************************************/
    bScheduleCommand((void *) pDevice, WLAN_CMD_SSID, NULL);
    spin_unlock_irq(&pDevice->lock);

    return ret;
}
Exemple #3
0
int modes_test(void)
{
   unsigned char pt[64], ct[64], tmp[64], key[16], iv[16], iv2[16];
   int cipher_idx;
#ifdef LTC_CBC_MODE
   symmetric_CBC cbc;
#endif
#ifdef LTC_CFB_MODE
   symmetric_CFB cfb;
#endif
#ifdef LTC_OFB_MODE
   symmetric_OFB ofb;
#endif
   unsigned long l;
   
   /* make a random pt, key and iv */
   yarrow_read(pt,  64, &yarrow_prng);
   yarrow_read(key, 16, &yarrow_prng);
   yarrow_read(iv,  16, &yarrow_prng);
   
   /* get idx of AES handy */
   cipher_idx = find_cipher("aes");
   if (cipher_idx == -1) {
      fprintf(stderr, "test requires AES");
      return 1;
   }
   
#ifdef LTC_F8_MODE
   DO(f8_test_mode());
#endif   
   
#ifdef LTC_LRW_MODE
   DO(lrw_test());
#endif

#ifdef LTC_CBC_MODE
   /* test CBC mode */
   /* encode the block */
   DO(cbc_start(cipher_idx, iv, key, 16, 0, &cbc));
   l = sizeof(iv2);
   DO(cbc_getiv(iv2, &l, &cbc));
   if (l != 16 || memcmp(iv2, iv, 16)) {
      fprintf(stderr, "cbc_getiv failed");
      return 1;
   }
   DO(cbc_encrypt(pt, ct, 64, &cbc));
   
   /* decode the block */
   DO(cbc_setiv(iv2, l, &cbc));
   zeromem(tmp, sizeof(tmp));
   DO(cbc_decrypt(ct, tmp, 64, &cbc));
   if (memcmp(tmp, pt, 64) != 0) {
      fprintf(stderr, "CBC failed");
      return 1;
   }
#endif

#ifdef LTC_CFB_MODE
   /* test CFB mode */
   /* encode the block */
   DO(cfb_start(cipher_idx, iv, key, 16, 0, &cfb));
   l = sizeof(iv2);
   DO(cfb_getiv(iv2, &l, &cfb));
   /* note we don't memcmp iv2/iv since cfb_start processes the IV for the first block */
   if (l != 16) {
      fprintf(stderr, "cfb_getiv failed");
      return 1;
   }
   DO(cfb_encrypt(pt, ct, 64, &cfb));
   
   /* decode the block */
   DO(cfb_setiv(iv, l, &cfb));
   zeromem(tmp, sizeof(tmp));
   DO(cfb_decrypt(ct, tmp, 64, &cfb));
   if (memcmp(tmp, pt, 64) != 0) {
      fprintf(stderr, "CFB failed");
      return 1;
   }
#endif
   
#ifdef LTC_OFB_MODE
   /* test OFB mode */
   /* encode the block */
   DO(ofb_start(cipher_idx, iv, key, 16, 0, &ofb));
   l = sizeof(iv2);
   DO(ofb_getiv(iv2, &l, &ofb));
   if (l != 16 || memcmp(iv2, iv, 16)) {
      fprintf(stderr, "ofb_getiv failed");
      return 1;
   }
   DO(ofb_encrypt(pt, ct, 64, &ofb));
   
   /* decode the block */
   DO(ofb_setiv(iv2, l, &ofb));
   zeromem(tmp, sizeof(tmp));
   DO(ofb_decrypt(ct, tmp, 64, &ofb));
   if (memcmp(tmp, pt, 64) != 0) {
      fprintf(stderr, "OFB failed");
      return 1;
   }
#endif

#ifdef LTC_CTR_MODE   
   DO(ctr_test());
#endif

#ifdef LTC_XTS_MODE
   DO(xts_test());
#endif
         
   return 0;
}
Exemple #4
0
/*-
 * ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
 * connection. It is only called by servers.
 *
 *   hello: The parsed ClientHello data
 *
 * Returns:
 *   -1: fatal error
 *    0: no session found
 *    1: a session may have been found.
 *
 * Side effects:
 *   - If a session is found then s->session is pointed at it (after freeing an
 *     existing session if need be) and s->verify_result is set from the session.
 *   - Both for new and resumed sessions, s->ext.ticket_expected is set to 1
 *     if the server should issue a new session ticket (to 0 otherwise).
 */
int ssl_get_prev_session(SSL *s, CLIENTHELLO_MSG *hello)
{
    /* This is used only by servers. */

    SSL_SESSION *ret = NULL;
    int fatal = 0, discard;
    int try_session_cache = 0;
    TICKET_RETURN r;

    if (SSL_IS_TLS13(s)) {
        if (!tls_parse_extension(s, TLSEXT_IDX_psk_kex_modes,
                                 SSL_EXT_CLIENT_HELLO, hello->pre_proc_exts,
                                 NULL, 0)
                || !tls_parse_extension(s, TLSEXT_IDX_psk, SSL_EXT_CLIENT_HELLO,
                                        hello->pre_proc_exts, NULL, 0))
            return -1;

        ret = s->session;
    } else {
        /* sets s->ext.ticket_expected */
        r = tls_get_ticket_from_client(s, hello, &ret);
        switch (r) {
        case TICKET_FATAL_ERR_MALLOC:
        case TICKET_FATAL_ERR_OTHER:
            fatal = 1;
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_GET_PREV_SESSION,
                     ERR_R_INTERNAL_ERROR);
            goto err;
        case TICKET_NONE:
        case TICKET_EMPTY:
            if (hello->session_id_len > 0)
                try_session_cache = 1;
            break;
        case TICKET_NO_DECRYPT:
        case TICKET_SUCCESS:
        case TICKET_SUCCESS_RENEW:
            break;
        }
    }

    if (try_session_cache &&
        ret == NULL &&
        !(s->session_ctx->session_cache_mode &
          SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
        SSL_SESSION data;

        data.ssl_version = s->version;
        memcpy(data.session_id, hello->session_id, hello->session_id_len);
        data.session_id_length = hello->session_id_len;

        CRYPTO_THREAD_read_lock(s->session_ctx->lock);
        ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
        if (ret != NULL) {
            /* don't allow other threads to steal it: */
            SSL_SESSION_up_ref(ret);
        }
        CRYPTO_THREAD_unlock(s->session_ctx->lock);
        if (ret == NULL)
            CRYPTO_atomic_add(&s->session_ctx->stats.sess_miss, 1, &discard,
                              s->session_ctx->lock);
    }

    if (try_session_cache &&
        ret == NULL && s->session_ctx->get_session_cb != NULL) {
        int copy = 1;

        ret = s->session_ctx->get_session_cb(s, hello->session_id,
                                             hello->session_id_len,
                                             &copy);

        if (ret != NULL) {
            CRYPTO_atomic_add(&s->session_ctx->stats.sess_cb_hit, 1, &discard,
                              s->session_ctx->lock);

            /*
             * Increment reference count now if the session callback asks us
             * to do so (note that if the session structures returned by the
             * callback are shared between threads, it must handle the
             * reference count itself [i.e. copy == 0], or things won't be
             * thread-safe).
             */
            if (copy)
                SSL_SESSION_up_ref(ret);

            /*
             * Add the externally cached session to the internal cache as
             * well if and only if we are supposed to.
             */
            if (!
                (s->session_ctx->session_cache_mode &
                 SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
                /*
                 * Either return value of SSL_CTX_add_session should not
                 * interrupt the session resumption process. The return
                 * value is intentionally ignored.
                 */
                SSL_CTX_add_session(s->session_ctx, ret);
            }
        }
    }

    if (ret == NULL)
        goto err;

    /* Now ret is non-NULL and we own one of its reference counts. */

    /* Check TLS version consistency */
    if (ret->ssl_version != s->version)
        goto err;

    if (ret->sid_ctx_length != s->sid_ctx_length
        || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {
        /*
         * We have the session requested by the client, but we don't want to
         * use it in this context.
         */
        goto err;               /* treat like cache miss */
    }

    if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
        /*
         * We can't be sure if this session is being used out of context,
         * which is especially important for SSL_VERIFY_PEER. The application
         * should have used SSL[_CTX]_set_session_id_context. For this error
         * case, we generate an error instead of treating the event like a
         * cache miss (otherwise it would be easy for applications to
         * effectively disable the session cache by accident without anyone
         * noticing).
         */

        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL_GET_PREV_SESSION,
                 SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
        fatal = 1;
        goto err;
    }

    if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */
        CRYPTO_atomic_add(&s->session_ctx->stats.sess_timeout, 1, &discard,
                          s->session_ctx->lock);
        if (try_session_cache) {
            /* session was from the cache, so remove it */
            SSL_CTX_remove_session(s->session_ctx, ret);
        }
        goto err;
    }

    /* Check extended master secret extension consistency */
    if (ret->flags & SSL_SESS_FLAG_EXTMS) {
        /* If old session includes extms, but new does not: abort handshake */
        if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS)) {
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_SSL_GET_PREV_SESSION,
                     SSL_R_INCONSISTENT_EXTMS);
            fatal = 1;
            goto err;
        }
    } else if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) {
        /* If new session includes extms, but old does not: do not resume */
        goto err;
    }

    if (!SSL_IS_TLS13(s)) {
        /* We already did this for TLS1.3 */
        SSL_SESSION_free(s->session);
        s->session = ret;
    }

    CRYPTO_atomic_add(&s->session_ctx->stats.sess_hit, 1, &discard,
                      s->session_ctx->lock);
    s->verify_result = s->session->verify_result;
    return 1;

 err:
    if (ret != NULL) {
        SSL_SESSION_free(ret);
        /* In TLSv1.3 s->session was already set to ret, so we NULL it out */
        if (SSL_IS_TLS13(s))
            s->session = NULL;

        if (!try_session_cache) {
            /*
             * The session was from a ticket, so we should issue a ticket for
             * the new session
             */
            s->ext.ticket_expected = 1;
        }
    }
    if (fatal)
        return -1;

    return 0;
}
Exemple #5
0
static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  if( n1!=n2 ) return 1;
  return memcmp(pKey1,pKey2,n1);
}
static gboolean
complete_connection (NMDevice *device,
                     NMConnection *connection,
                     const char *specific_object,
                     const GSList *existing_connections,
                     GError **error)
{
	NMDeviceBtPrivate *priv = NM_DEVICE_BT_GET_PRIVATE (device);
	NMSettingBluetooth *s_bt;
	const GByteArray *setting_bdaddr;
	struct ether_addr *devaddr = ether_aton (priv->bdaddr);
	const char *ctype;
	gboolean is_dun = FALSE, is_pan = FALSE;
	NMSettingGsm *s_gsm;
	NMSettingCdma *s_cdma;
	NMSettingSerial *s_serial;
	NMSettingPPP *s_ppp;
	const char *format = NULL, *preferred = NULL;

	s_gsm = nm_connection_get_setting_gsm (connection);
	s_cdma = nm_connection_get_setting_cdma (connection);
	s_serial = nm_connection_get_setting_serial (connection);
	s_ppp = nm_connection_get_setting_ppp (connection);

	s_bt = nm_connection_get_setting_bluetooth (connection);
	if (!s_bt) {
		s_bt = (NMSettingBluetooth *) nm_setting_bluetooth_new ();
		nm_connection_add_setting (connection, NM_SETTING (s_bt));
	}

	ctype = nm_setting_bluetooth_get_connection_type (s_bt);
	if (ctype) {
		if (!strcmp (ctype, NM_SETTING_BLUETOOTH_TYPE_DUN))
			is_dun = TRUE;
		else if (!strcmp (ctype, NM_SETTING_BLUETOOTH_TYPE_PANU))
			is_pan = TRUE;
	} else {
		if (s_gsm || s_cdma)
			is_dun = TRUE;
		else if (priv->capabilities & NM_BT_CAPABILITY_NAP)
			is_pan = TRUE;
	}

	if (is_pan) {
		/* Make sure the device supports PAN */
		if (!(priv->capabilities & NM_BT_CAPABILITY_NAP)) {
			g_set_error_literal (error,
			                     NM_SETTING_BLUETOOTH_ERROR,
			                     NM_SETTING_BLUETOOTH_ERROR_INVALID_PROPERTY,
			                     "PAN required but Bluetooth device does not support NAP");
			return FALSE;
		}

		/* PAN can't use any DUN-related settings */
		if (s_gsm || s_cdma || s_serial || s_ppp) {
			g_set_error_literal (error,
			                     NM_SETTING_BLUETOOTH_ERROR,
			                     NM_SETTING_BLUETOOTH_ERROR_INVALID_PROPERTY,
			                     "PAN incompatible with GSM, CDMA, or serial settings");
			return FALSE;
		}

		g_object_set (G_OBJECT (s_bt),
		              NM_SETTING_BLUETOOTH_TYPE, NM_SETTING_BLUETOOTH_TYPE_PANU,
		              NULL);

		format = _("PAN connection %d");
	} else if (is_dun) {
		/* Make sure the device supports PAN */
		if (!(priv->capabilities & NM_BT_CAPABILITY_DUN)) {
			g_set_error_literal (error,
			                     NM_SETTING_BLUETOOTH_ERROR,
			                     NM_SETTING_BLUETOOTH_ERROR_INVALID_PROPERTY,
			                     "DUN required but Bluetooth device does not support DUN");
			return FALSE;
		}

		/* Need at least a GSM or a CDMA setting */
		if (!s_gsm && !s_cdma) {
			g_set_error_literal (error,
			                     NM_SETTING_BLUETOOTH_ERROR,
			                     NM_SETTING_BLUETOOTH_ERROR_INVALID_PROPERTY,
			                     "Setting requires DUN but no GSM or CDMA setting is present");
			return FALSE;
		}

		g_object_set (G_OBJECT (s_bt),
		              NM_SETTING_BLUETOOTH_TYPE, NM_SETTING_BLUETOOTH_TYPE_DUN,
		              NULL);

		if (s_gsm) {
			format = _("GSM connection %d");
			if (!nm_setting_gsm_get_number (s_gsm))
				g_object_set (G_OBJECT (s_gsm), NM_SETTING_GSM_NUMBER, "*99#", NULL);
		} else if (s_cdma) {
			format = _("CDMA connection %d");
			if (!nm_setting_cdma_get_number (s_cdma))
				g_object_set (G_OBJECT (s_cdma), NM_SETTING_GSM_NUMBER, "#777", NULL);
		} else
			format = _("DUN connection %d");
	} else {
		g_set_error_literal (error,
		                     NM_SETTING_BLUETOOTH_ERROR,
		                     NM_SETTING_BLUETOOTH_ERROR_INVALID_PROPERTY,
		                     "Unknown/unhandled Bluetooth connection type");
		return FALSE;
	}

	nm_utils_complete_generic (connection,
	                           NM_SETTING_BLUETOOTH_SETTING_NAME,
	                           existing_connections,
	                           format,
	                           preferred,
	                           is_dun ? FALSE : TRUE); /* No IPv6 yet for DUN */

	setting_bdaddr = nm_setting_bluetooth_get_bdaddr (s_bt);
	if (setting_bdaddr) {
		/* Make sure the setting BT Address (if any) matches the device's */
		if (memcmp (setting_bdaddr->data, devaddr->ether_addr_octet, ETH_ALEN)) {
			g_set_error_literal (error,
			                     NM_SETTING_BLUETOOTH_ERROR,
			                     NM_SETTING_BLUETOOTH_ERROR_INVALID_PROPERTY,
			                     NM_SETTING_BLUETOOTH_BDADDR);
			return FALSE;
		}
	} else {
		GByteArray *bdaddr;
		const guint8 null_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };

		/* Lock the connection to this device by default */
		if (memcmp (devaddr->ether_addr_octet, null_mac, ETH_ALEN)) {
			bdaddr = g_byte_array_sized_new (ETH_ALEN);
			g_byte_array_append (bdaddr, devaddr->ether_addr_octet, ETH_ALEN);
			g_object_set (G_OBJECT (s_bt), NM_SETTING_BLUETOOTH_BDADDR, bdaddr, NULL);
			g_byte_array_free (bdaddr, TRUE);
		}
	}

	return TRUE;
}
Exemple #7
0
enum nss_status _nss_myhostname_gethostbyaddr2_r(
                const void* addr, socklen_t len,
                int af,
                struct hostent *host,
                char *buffer, size_t buflen,
                int *errnop, int *h_errnop,
                int32_t *ttlp) {

        const char *canonical = NULL, *additional = NULL;
        uint32_t local_address_ipv4 = LOCALADDRESS_IPV4;
        _cleanup_free_ struct local_address *addresses = NULL;
        _cleanup_free_ char *hn = NULL;
        int n_addresses = 0;
        struct local_address *a;
        unsigned n;

        assert(addr);
        assert(host);
        assert(buffer);
        assert(errnop);
        assert(h_errnop);

        if (!IN_SET(af, AF_INET, AF_INET6)) {
                *errnop = EAFNOSUPPORT;
                *h_errnop = NO_DATA;
                return NSS_STATUS_UNAVAIL;
        }

        if (len != FAMILY_ADDRESS_SIZE(af)) {
                *errnop = EINVAL;
                *h_errnop = NO_RECOVERY;
                return NSS_STATUS_UNAVAIL;
        }

        if (af == AF_INET) {

                if ((*(uint32_t*) addr) == LOCALADDRESS_IPV4)
                        goto found;

                if ((*(uint32_t*) addr) == htonl(INADDR_LOOPBACK)) {
                        canonical = "localhost";
                        local_address_ipv4 = htonl(INADDR_LOOPBACK);
                        goto found;
                }

        } else {
                assert(af == AF_INET6);

                if (memcmp(addr, LOCALADDRESS_IPV6, 16) == 0) {
                        additional = "localhost";
                        goto found;
                }

        }

        n_addresses = local_addresses(NULL, 0, &addresses);
        if (n_addresses < 0)
                n_addresses = 0;

        for (a = addresses, n = 0; (int) n < n_addresses; n++, a++) {
                if (af != a->family)
                        continue;

                if (memcmp(addr, &a->address, FAMILY_ADDRESS_SIZE(af)) == 0)
                        goto found;
        }

        *errnop = ENOENT;
        *h_errnop = HOST_NOT_FOUND;

        return NSS_STATUS_NOTFOUND;

found:
        if (!canonical) {
                hn = gethostname_malloc();
                if (!hn) {
                        *errnop = ENOMEM;
                        *h_errnop = NO_RECOVERY;
                        return NSS_STATUS_TRYAGAIN;
                }

                canonical = hn;
        }

        return fill_in_hostent(
                        canonical, additional,
                        af,
                        addresses, n_addresses,
                        local_address_ipv4,
                        host,
                        buffer, buflen,
                        errnop, h_errnop,
                        ttlp,
                        NULL);

}
Exemple #8
0
static int nand_bch_write_page(struct mtd_info *mtd, struct nand_chip *chip,
			   const uint8_t *buf, int oob_required, int page, int cached, int raw)
{
#ifdef CONFIG_MTD_NAND_VERIFY_WRITE
	int ret = 0;
#endif
	int status;

	DBGOUT("%s page %d, raw=%d\n", __func__, page, raw);
	chip->cmdfunc(mtd, NAND_CMD_SEQIN, 0x00, page);

	/* not verify */
	if (raw)
		chip->ecc.write_page_raw(mtd, chip, buf, oob_required);
	else
		chip->ecc.write_page(mtd, chip, buf, oob_required);

	/*
	 * Cached progamming disabled for now, Not sure if its worth the
	 * trouble. The speed gain is not very impressive. (2.3->2.6Mib/s)
	 */
	cached = 0;

	if (!cached || !(chip->options & NAND_CACHEPRG)) {

		chip->cmdfunc(mtd, NAND_CMD_PAGEPROG, -1, -1);
		status = chip->waitfunc(mtd, chip);
		/*
		 * See if operation failed and additional status checks are
		 * available
		 */
		if ((status & NAND_STATUS_FAIL) && (chip->errstat))
			status = chip->errstat(mtd, chip, FL_WRITING, status,
					       page);

		if (status & NAND_STATUS_FAIL)
			return -EIO;
	} else {
		chip->cmdfunc(mtd, NAND_CMD_CACHEDPROG, -1, -1);
		status = chip->waitfunc(mtd, chip);
	}

#ifdef CONFIG_MTD_NAND_VERIFY_WRITE
	if (raw)
		return 0;

	/* Send command to read back the data */
	chip->cmdfunc(mtd, NAND_CMD_READ0, 0, page);
	chip->ecc.read_page(mtd, chip, (uint8_t *)verify_page, oob_required, page);
	if (ret < 0)
		return -EIO;

	if (memcmp (verify_page, buf, mtd->writesize))
	{
		ERROUT ("%s fail verify %d page\n", __func__, page);
		return -EIO;
	}

	chip->cmdfunc(mtd, NAND_CMD_STATUS, -1, -1);
#endif
	return 0; // mtd->ecc_stats.corrected - stats.corrected ? -EUCLEAN : 0
}
Exemple #9
0
static void id_file(char *f){
  FILE *test;
  unsigned char buffer[80];
  int ret;
  int tmp_video_hzn = -1,
      tmp_video_hzd = -1,
      tmp_video_an = -1,
      tmp_video_ad = -1;
  int extra_hdr_bytes;

  /* open it, look for magic */

  if(!strcmp(f,"-")){
    /* stdin */
    test=stdin;
  }else{
    test=fopen(f,"rb");
    if(!test){
      fprintf(stderr,"Unable to open file %s.\n",f);
      exit(1);
    }
  }

  ret=fread(buffer,1,4,test);
  if(ret<4){
    fprintf(stderr,"EOF determining file type of file %s.\n",f);
    exit(1);
  }

  if(!memcmp(buffer,"RIFF",4)){
    /* possible WAV file */

    if(audio){
      /* umm, we already have one */
      fprintf(stderr,"Multiple RIFF WAVE files specified on command line.\n");
      exit(1);
    }

    /* Parse the rest of the header */

    ret=fread(buffer,1,4,test);
    ret=fread(buffer,1,4,test);
    if(ret<4)goto riff_err;
    if(!memcmp(buffer,"WAVE",4)){

      while(!feof(test)){
        ret=fread(buffer,1,4,test);
        if(ret<4)goto riff_err;
        if(!memcmp("fmt",buffer,3)){

          /* OK, this is our audio specs chunk.  Slurp it up. */

          ret=fread(buffer,1,20,test);
          if(ret<20)goto riff_err;

          extra_hdr_bytes = (buffer[0]  + (buffer[1] << 8) +
                            (buffer[2] << 16) + (buffer[3] << 24)) - 16;

          if(memcmp(buffer+4,"\001\000",2)){
            fprintf(stderr,"The WAV file %s is in a compressed format; "
                    "can't read it.\n",f);
            exit(1);
          }

          audio=test;
          audio_ch=buffer[6]+(buffer[7]<<8);
          audio_hz=buffer[8]+(buffer[9]<<8)+
            (buffer[10]<<16)+(buffer[11]<<24);

          if(buffer[18]+(buffer[19]<<8)!=16){
            fprintf(stderr,"Can only read 16 bit WAV files for now.\n");
            exit(1);
          }

          /* read past extra header bytes */
          while(extra_hdr_bytes){
            int read_size = (extra_hdr_bytes > sizeof(buffer)) ?
             sizeof(buffer) : extra_hdr_bytes;
            ret = fread(buffer, 1, read_size, test);

            if (ret < read_size)
              goto riff_err;
            else
              extra_hdr_bytes -= read_size;
          }

          /* Now, align things to the beginning of the data */
          /* Look for 'dataxxxx' */
          while(!feof(test)){
            ret=fread(buffer,1,4,test);
            if(ret<4)goto riff_err;
            if(!memcmp("data",buffer,4)){
              /* We're there.  Ignore the declared size for now. */
              ret=fread(buffer,1,4,test);
              if(ret<4)goto riff_err;

              fprintf(stderr,"File %s is 16 bit %d channel %d Hz RIFF WAV audio.\n",
                      f,audio_ch,audio_hz);

              return;
            }
          }
        }
      }
    }

    fprintf(stderr,"Couldn't find WAVE data in RIFF file %s.\n",f);
    exit(1);

  }
  if(!memcmp(buffer,"YUV4",4)){
    /* possible YUV2MPEG2 format file */
    /* read until newline, or 80 cols, whichever happens first */
    /* NB the mjpegtools spec doesn't define a length limit */
    int i,j;
    for(i=0;i<79;i++){
      ret=fread(buffer+i,1,1,test);
      if(ret<1)goto yuv_err;
      if(buffer[i]=='\n')break;
    }
    if(i==79){
      fprintf(stderr,"Error parsing %s header; not a YUV2MPEG2 file?\n",f);
    }
    buffer[i]='\0';

    if(!memcmp(buffer,"MPEG",4)){
      char interlace = '?';

      if(video){
        /* umm, we already have one */
        fprintf(stderr,"Multiple video files specified on command line.\n");
        exit(1);
      }

      if(buffer[4]!='2'){
        fprintf(stderr,"Incorrect YUV input file version; YUV4MPEG2 required.\n");
      }

      /* parse the frame header */
      j = 5;
      while (j < i) {
        if ((buffer[j] != ' ') && (buffer[j-1] == ' ')) 
          switch (buffer[j]) {
            case 'W': frame_x = atoi((char*)&buffer[j+1]); break;
            case 'H': frame_y = atoi((char*)&buffer[j+1]); break;
            case 'C': /* chroma subsampling */ break;
            case 'I': interlace = buffer[j+1]; break;
            case 'F': /* frame rate ratio */
              tmp_video_hzn = atoi((char*)&buffer[j+1]);
	      while ((buffer[j] != ':') && (j < i)) j++;
              tmp_video_hzd = atoi((char*)&buffer[j+1]);
              break;
            case 'A': /* sample aspect ratio */
              tmp_video_an = atoi((char*)&buffer[j+1]);
	      while ((buffer[j] != ':') && (j < i)) j++;
              tmp_video_ad = atoi((char*)&buffer[j+1]);
              break;
            case 'X': /* metadata */ break;
            default:
              fprintf(stderr, "unrecognized stream header tag '%c'\n", buffer[j]);
              break;
          }
        j++;
      }
      /* verify data from the stream header */
      if (frame_x <= 0) {
        fprintf(stderr,"Error parsing YUV4MPEG2 header:"
                " missing width tag in file %s.\n", f);
        exit(1);
      }
      if (frame_y <= 0) {
        fprintf(stderr,"Error parsing YUV4MPEG2 header:"
                " missing height tag in file %s.\n", f);
        exit(1);
      }
      if (tmp_video_hzn < 0 || tmp_video_hzd < 0) {
	/* default to 30 fps */
	tmp_video_hzn = 30; tmp_video_hzd = 1;
        fprintf(stderr,"Warning: no framerate defined in file %s.\n", f);
      }
      if (tmp_video_an < 0 || tmp_video_ad < 0) {
	/* default to unknown */
	tmp_video_an = 0; tmp_video_ad = 0;
      }

      /* update fps and aspect ratio globals if not specified in the command line */
      if (video_hzn==-1) video_hzn = tmp_video_hzn;
      if (video_hzd==-1) video_hzd = tmp_video_hzd;
      if (video_an==-1) video_an = tmp_video_an;
      if (video_ad==-1) video_ad = tmp_video_ad;

      if(interlace=='?'){
        fprintf(stderr,"Warning: input video isn't marked for interlacing;"
          " treating this\nas progressive scan video."
          " Deinterlace first if you get poor results.\n");
      }else if(interlace!='p'){
        fprintf(stderr,"Input video is interlaced; Theora handles only progressive scan\n");
        exit(1);
      }

      video=test;

      fprintf(stderr,"File %s is %dx%d %.02f fps YUV12 video.\n",
              f,frame_x,frame_y,(double)video_hzn/video_hzd);

      return;
    }
  }
  fprintf(stderr,"Input file %s is neither a WAV nor YUV4MPEG2 file.\n",f);
  exit(1);

 riff_err:
  fprintf(stderr,"EOF parsing RIFF file %s.\n",f);
  exit(1);
 yuv_err:
  fprintf(stderr,"EOF parsing YUV4MPEG2 file %s.\n",f);
  exit(1);

}
xed_uint_t disas_decode_encode_binary(const xed_state_t* dstate,
                                      const xed_uint8_t* decode_text_binary,
                                      const unsigned int bytes,
                                      xed_decoded_inst_t* xedd, 
                                      xed_uint64_t runtime_address)   {
    // decode then encode
    unsigned int retval_olen = 0;
    // decode it...
    xed_bool_t decode_okay =  disas_decode_binary(dstate, decode_text_binary,
                                                  bytes, xedd, 
                                                  runtime_address);
    if (decode_okay)     {
        xed_error_enum_t encode_okay;
        unsigned int enc_olen, ilen = XED_MAX_INSTRUCTION_BYTES;
        xed_uint8_t array[XED_MAX_INSTRUCTION_BYTES];
        // they are basically the same now
        xed_encoder_request_t* enc_req = xedd; 
        // convert decode structure to proper encode structure
        xed_encoder_request_init_from_decode(xedd);
        
        // encode it again...
        encode_okay =  xed_encode(enc_req, array, ilen, &enc_olen);
        if (encode_okay != XED_ERROR_NONE) {
            if (CLIENT_VERBOSE) {
                char buf[XED_TMP_BUF_LEN];
                char buf2[XED_TMP_BUF_LEN];
                int blen=XED_TMP_BUF_LEN;
                xed_encode_request_print(enc_req, buf, XED_TMP_BUF_LEN);
                blen = xed_strncpy(buf2,"Could not re-encode: ", blen);
                blen = xed_strncat(buf2, buf, blen);
                blen = xed_strncat(buf2,"\nError code was: ",blen);
                blen = xed_strncat(buf2,
                                   xed_error_enum_t2str(encode_okay),blen);
                blen = xed_strncat(buf2, "\n",blen);
                xedex_dwarn(buf2);
            }
        }
        else         {
            retval_olen = enc_olen;
            // See if it matched the original...
            if (CLIENT_VERBOSE) {
                char buf[XED_HEX_BUFLEN];
                xed_uint_t dec_length; 
                xed_print_hex_line(buf,array, enc_olen, XED_HEX_BUFLEN);
                printf("Encodable! %s\n",buf);
                dec_length = xed_decoded_inst_get_length(xedd);
                if ((enc_olen != dec_length ||
                     memcmp(decode_text_binary, array, enc_olen)  )) {
                    char buf2[XED_TMP_BUF_LEN];
                    char buf3[XED_TMP_BUF_LEN];
                    printf("Discrepenacy after re-encoding. dec_len= " 
                           XED_FMT_U " ", dec_length);
                    xed_print_hex_line(buf, decode_text_binary, 
                                       dec_length,XED_HEX_BUFLEN);
                    printf("[%s] ", buf);
                    printf("enc_olen= " XED_FMT_U "", enc_olen);
                    xed_print_hex_line(buf, array, enc_olen, XED_HEX_BUFLEN);
                    printf(" [%s] ", buf);
                    printf("for instruction: ");
                    xed_decoded_inst_dump(xedd, buf3,XED_TMP_BUF_LEN);
                    printf("%s\n", buf3);
                    printf("vs Encode  request: ");
                    xed_encode_request_print(enc_req, buf2, XED_TMP_BUF_LEN);
                    printf("%s\n", buf2);
                }
                else 
                    printf("Identical re-encoding\n");
            }
        }
    }
    return retval_olen;
}
Exemple #11
0
//=================================================================================================
bool eve::thr::equal_ID(DWORD inLeft, DWORD inRight)
{
	return(memcmp(&inLeft, &inRight, sizeof(inLeft)) == 0);
}
Exemple #12
0
int
disrsl_(int stream, int *negate, unsigned long *value, unsigned long count, int recursv)
{
	int		c;
	unsigned long	locval;
	unsigned long	ndigs;
	char		*cp;

	assert(negate != NULL);
	assert(value != NULL);
	assert(count);
	assert(stream >= 0);
	assert(dis_getc != NULL);
	assert(dis_gets != NULL);

	if (++recursv > DIS_RECURSIVE_LIMIT)
		return (DIS_PROTO);

	switch (c = (*dis_getc)(stream)) {
		case '-':
		case '+':
			if (count > ulmaxdigs)
				goto overflow;
			*negate = c == '-';
			if ((*dis_gets)(stream, dis_buffer, count) != count)
				return (DIS_EOD);
			if (count == ulmaxdigs) {
				if (memcmp(dis_buffer, ulmax, ulmaxdigs) > 0)
					goto overflow;
			}
			cp = dis_buffer;
			locval = 0;
			do {
				if ((c = *cp++) < '0' || c > '9')
					return (DIS_NONDIGIT);
				locval = 10 * locval + c - '0';
			} while (--count);
			*value = locval;
			return (DIS_SUCCESS);
		case '0':
			return (DIS_LEADZRO);
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			ndigs = c - '0';
			if (count > 1) {
				if (count > ulmaxdigs)
					break;
				if ((*dis_gets)(stream, dis_buffer + 1, count - 1) !=
					count - 1)
					return (DIS_EOD);
				cp = dis_buffer;
				if (count == ulmaxdigs) {
					*cp = c;
					if (memcmp(dis_buffer, ulmax, ulmaxdigs) > 0)
						break;
				}
				while (--count) {
					if ((c = *++cp) < '0' || c > '9')
						return (DIS_NONDIGIT);
					ndigs = 10 * ndigs + c - '0';
				}
			}
			return (disrsl_(stream, negate, value, ndigs, recursv));
		case -1:
			return (DIS_EOD);
		case -2:
			return (DIS_EOF);
		default:
			return (DIS_NONDIGIT);
	}
	*negate = FALSE;
overflow:
	*value = ULONG_MAX;
	return (DIS_OVERFLOW);
}
Exemple #13
0
static void ndpi_rtp_search(struct ndpi_detection_module_struct *ndpi_struct,
			    struct ndpi_flow_struct *flow,
			    const u_int8_t * payload, const u_int16_t payload_len)
{
	struct ndpi_packet_struct *packet = &flow->packet;
	
	u_int8_t stage;
	u_int16_t seqnum = ntohs(get_u_int16_t(payload, 2));

	NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "search rtp.\n");

	if (payload_len == 4 && get_u_int32_t(packet->payload, 0) == 0 && flow->packet_counter < 8) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "need next packet, maybe ClearSea out calls.\n");
		return;
	}

	if (payload_len == 5 && memcmp(payload, "hello", 5) == 0) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG,
				"need next packet, initial hello packet of SIP out calls.\n");
		return;
	}

	if (payload_len == 1 && payload[0] == 0) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG,
				"need next packet, payload_packet_len == 1 && payload[0] == 0.\n");
		return;
	}

	if (payload_len == 3 && memcmp(payload, "png", 3) == 0) {
		/* weird packet found in Ninja GlobalIP trace */
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "skipping packet with len = 3 and png payload.\n");
		return;
	}

	if (payload_len < 12) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "minimal packet size for rtp packets: 12.\n");
		goto exclude_rtp;
	}

	if (payload_len == 12 && get_u_int32_t(payload, 0) == 0 && get_u_int32_t(payload, 4) == 0 && get_u_int32_t(payload, 8) == 0) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "skipping packet with len = 12 and only 0-bytes.\n");
		return;
	}

	if ((payload[0] & 0xc0) == 0xc0 || (payload[0] & 0xc0) == 0x40 || (payload[0] & 0xc0) == 0x00) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "version = 3 || 1 || 0, maybe first rtp packet.\n");
		return;
	}

	if ((payload[0] & 0xc0) != 0x80) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct,
				NDPI_LOG_DEBUG, "rtp version must be 2, first two bits of a packets must be 10.\n");
		goto exclude_rtp;
	}

	/* rtp_payload_type are the last seven bits of the second byte */
	if (flow->rtp_payload_type[packet->packet_direction] != (payload[1] & 0x7F)) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "payload_type has changed, reset stages.\n");
		packet->packet_direction == 0 ? (flow->rtp_stage1 = 0) : (flow->rtp_stage2 = 0);
	}
	/* first bit of first byte is not part of payload_type */
	flow->rtp_payload_type[packet->packet_direction] = payload[1] & 0x7F;

	stage = (packet->packet_direction == 0 ? flow->rtp_stage1 : flow->rtp_stage2);

	if (stage > 0) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct,
				NDPI_LOG_DEBUG, "stage = %u.\n", packet->packet_direction == 0 ? flow->rtp_stage1 : flow->rtp_stage2);
		if (flow->rtp_ssid[packet->packet_direction] != get_u_int32_t(payload, 8)) {
			NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "ssid has changed, goto exclude rtp.\n");
			goto exclude_rtp;
		}

		if (seqnum == flow->rtp_seqnum[packet->packet_direction]) {
			NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "maybe \"retransmission\", need next packet.\n");
			return;
		} else if ((u_int16_t) (seqnum - flow->rtp_seqnum[packet->packet_direction]) < RTP_MAX_OUT_OF_ORDER) {
			NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG,
					"new packet has larger sequence number (within valid range)\n");
			update_seq(ndpi_struct, flow, packet->packet_direction, seqnum);
		} else if ((u_int16_t) (flow->rtp_seqnum[packet->packet_direction] - seqnum) < RTP_MAX_OUT_OF_ORDER) {
			NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG,
					"new packet has smaller sequence number (within valid range)\n");
			init_seq(ndpi_struct, flow, packet->packet_direction, seqnum, 1);
		} else {
			NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG,
					"sequence number diff is too big, goto exclude rtp.\n");
			goto exclude_rtp;
		}
	} else {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct,
				NDPI_LOG_DEBUG, "rtp_ssid[%u] = %u.\n", packet->packet_direction,
				flow->rtp_ssid[packet->packet_direction]);
		flow->rtp_ssid[packet->packet_direction] = get_u_int32_t(payload, 8);
		if (flow->packet_counter < 3) {
			NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "packet_counter < 3, need next packet.\n");
		}
		init_seq(ndpi_struct, flow, packet->packet_direction, seqnum, 1);
	}
	if (seqnum <= 3) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct,
				NDPI_LOG_DEBUG, "sequence_number = %u, too small, need next packet, return.\n", seqnum);
		return;
	}

	if (stage == 3) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "add connection I.\n");
		ndpi_int_rtp_add_connection(ndpi_struct, flow);
	} else {
		packet->packet_direction == 0 ? flow->rtp_stage1++ : flow->rtp_stage2++;
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "stage[%u]++; need next packet.\n",
				packet->packet_direction);
	}
	return;

  exclude_rtp:
#ifdef NDPI_PROTOCOL_STUN
	if (packet->detected_protocol_stack[0] == NDPI_PROTOCOL_STUN
		|| packet->real_protocol_read_only == NDPI_PROTOCOL_STUN) {
		NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "STUN: is detected, need next packet.\n");
		return;
	}
#endif							/*  NDPI_PROTOCOL_STUN */
	NDPI_LOG(NDPI_PROTOCOL_RTP, ndpi_struct, NDPI_LOG_DEBUG, "exclude rtp.\n");
	NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_RTP);
}
Exemple #14
0
static int test_pp(unsigned char *b)
{
	return memcmp(b, "PP20", 4) == 0;
}
Exemple #15
0
static void receive_udppacket(node_t *n, vpn_packet_t *inpkt) {
	vpn_packet_t pkt1, pkt2;
	vpn_packet_t *pkt[] = { &pkt1, &pkt2, &pkt1, &pkt2 };
	int nextpkt = 0;
	vpn_packet_t *outpkt = pkt[0];
	int outlen, outpad;
	unsigned char hmac[EVP_MAX_MD_SIZE];
	int i;

	if(!n->inkey) {
		ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got packet from %s (%s) but he hasn't got our key yet",
					n->name, n->hostname);
		return;
	}

	/* Check packet length */

	if(inpkt->len < sizeof(inpkt->seqno) + n->inmaclength) {
		ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got too short packet from %s (%s)",
					n->name, n->hostname);
		return;
	}

	/* Check the message authentication code */

	if(n->indigest && n->inmaclength) {
		inpkt->len -= n->inmaclength;
		HMAC(n->indigest, n->inkey, n->inkeylength,
			 (unsigned char *) &inpkt->seqno, inpkt->len, (unsigned char *)hmac, NULL);

		if(memcmp(hmac, (char *) &inpkt->seqno + inpkt->len, n->inmaclength)) {
			ifdebug(TRAFFIC) logger(LOG_DEBUG, "Got unauthenticated packet from %s (%s)",
					   n->name, n->hostname);
			return;
		}
	}

	/* Decrypt the packet */

	if(n->incipher) {
		outpkt = pkt[nextpkt++];

		if(!EVP_DecryptInit_ex(&n->inctx, NULL, NULL, NULL, NULL)
				|| !EVP_DecryptUpdate(&n->inctx, (unsigned char *) &outpkt->seqno, &outlen,
					(unsigned char *) &inpkt->seqno, inpkt->len)
				|| !EVP_DecryptFinal_ex(&n->inctx, (unsigned char *) &outpkt->seqno + outlen, &outpad)) {
			ifdebug(TRAFFIC) logger(LOG_DEBUG, "Error decrypting packet from %s (%s): %s",
						n->name, n->hostname, ERR_error_string(ERR_get_error(), NULL));
			return;
		}
		
		outpkt->len = outlen + outpad;
		inpkt = outpkt;
	}

	/* Check the sequence number */

	inpkt->len -= sizeof(inpkt->seqno);
	inpkt->seqno = ntohl(inpkt->seqno);

	if(replaywin) {
		if(inpkt->seqno != n->received_seqno + 1) {
			if(inpkt->seqno >= n->received_seqno + replaywin * 8) {
				if(n->farfuture++ < replaywin >> 2) {
					logger(LOG_WARNING, "Packet from %s (%s) is %d seqs in the future, dropped (%u)",
						n->name, n->hostname, inpkt->seqno - n->received_seqno - 1, n->farfuture);
					return;
				}
				logger(LOG_WARNING, "Lost %d packets from %s (%s)",
					   	inpkt->seqno - n->received_seqno - 1, n->name, n->hostname);
				memset(n->late, 0, replaywin);
			} else if (inpkt->seqno <= n->received_seqno) {
				if((n->received_seqno >= replaywin * 8 && inpkt->seqno <= n->received_seqno - replaywin * 8) || !(n->late[(inpkt->seqno / 8) % replaywin] & (1 << inpkt->seqno % 8))) {
					logger(LOG_WARNING, "Got late or replayed packet from %s (%s), seqno %d, last received %d",
					   	n->name, n->hostname, inpkt->seqno, n->received_seqno);
					return;
				}
			} else {
				for(i = n->received_seqno + 1; i < inpkt->seqno; i++)
					n->late[(i / 8) % replaywin] |= 1 << i % 8;
			}
		}

		n->farfuture = 0;
		n->late[(inpkt->seqno / 8) % replaywin] &= ~(1 << inpkt->seqno % 8);
	}
Exemple #16
0
int fetch_and_process_video(FILE *video,ogg_page *videopage,
                            ogg_stream_state *to,
                            theora_state *td,
                            int videoflag){
  /* You'll go to Hell for using static variables */
  static int          state=-1;
  static unsigned char *yuvframe[2];
  unsigned char        *line;
  yuv_buffer          yuv;
  ogg_packet          op;
  int i, e;

  if(state==-1){
        /* initialize the double frame buffer */
    yuvframe[0]=malloc(video_x*video_y*3/2);
    yuvframe[1]=malloc(video_x*video_y*3/2);

        /* clear initial frame as it may be larger than actual video data */
        /* fill Y plane with 0x10 and UV planes with 0X80, for black data */
    memset(yuvframe[0],0x10,video_x*video_y);
    memset(yuvframe[0]+video_x*video_y,0x80,video_x*video_y/2);
    memset(yuvframe[1],0x10,video_x*video_y);
    memset(yuvframe[1]+video_x*video_y,0x80,video_x*video_y/2);

    state=0;
  }

  /* is there a video page flushed?  If not, work until there is. */
  while(!videoflag){
    spinnit();

    if(ogg_stream_pageout(to,videopage)>0) return 1;
    if(ogg_stream_eos(to)) return 0;

    {
      /* read and process more video */
      /* video strategy reads one frame ahead so we know when we're
         at end of stream and can mark last video frame as such
         (vorbis audio has to flush one frame past last video frame
         due to overlap and thus doesn't need this extra work */

      /* have two frame buffers full (if possible) before
         proceeding.  after first pass and until eos, one will
         always be full when we get here */

      for(i=state;i<2;i++){
        char c,frame[6];
        int ret=fread(frame,1,6,video);
        
	/* match and skip the frame header */
        if(ret<6)break;
        if(memcmp(frame,"FRAME",5)){
          fprintf(stderr,"Loss of framing in YUV input data\n");
          exit(1);
        }
        if(frame[5]!='\n'){
          int j;
          for(j=0;j<79;j++)
            if(fread(&c,1,1,video)&&c=='\n')break;
          if(j==79){
            fprintf(stderr,"Error parsing YUV frame header\n");
            exit(1);
          }
        }

        /* read the Y plane into our frame buffer with centering */
        line=yuvframe[i]+video_x*frame_y_offset+frame_x_offset;
        for(e=0;e<frame_y;e++){
          ret=fread(line,1,frame_x,video);
            if(ret!=frame_x) break;
          line+=video_x;
        }
        /* now get U plane*/
        line=yuvframe[i]+(video_x*video_y)
          +(video_x/2)*(frame_y_offset/2)+frame_x_offset/2;
        for(e=0;e<frame_y/2;e++){
          ret=fread(line,1,frame_x/2,video);
            if(ret!=frame_x/2) break;
          line+=video_x/2;
        }
        /* and the V plane*/
        line=yuvframe[i]+(video_x*video_y*5/4)
                  +(video_x/2)*(frame_y_offset/2)+frame_x_offset/2;
        for(e=0;e<frame_y/2;e++){
          ret=fread(line,1,frame_x/2,video);
            if(ret!=frame_x/2) break;
          line+=video_x/2;
        }
        state++;
      }

      if(state<1){
        /* can't get here unless YUV4MPEG stream has no video */
        fprintf(stderr,"Video input contains no frames.\n");
        exit(1);
      }

      /* Theora is a one-frame-in,one-frame-out system; submit a frame
         for compression and pull out the packet */

      {
        yuv.y_width=video_x;
        yuv.y_height=video_y;
        yuv.y_stride=video_x;

        yuv.uv_width=video_x/2;
        yuv.uv_height=video_y/2;
        yuv.uv_stride=video_x/2;

        yuv.y= yuvframe[0];
        yuv.u= yuvframe[0]+ video_x*video_y;
        yuv.v= yuvframe[0]+ video_x*video_y*5/4 ;
      }

      theora_encode_YUVin(td,&yuv);

      /* if there's only one frame, it's the last in the stream */
      if(state<2)
        theora_encode_packetout(td,1,&op);
      else
        theora_encode_packetout(td,0,&op);

      ogg_stream_packetin(to,&op);

      {
        unsigned char *temp=yuvframe[0];
        yuvframe[0]=yuvframe[1];
        yuvframe[1]=temp;
        state--;
      }

    }
  }
  return videoflag;
}
/**
 * From gnutls and spice red_peer.c
 * TODO: switch to gnutls and get rid of this
 *
 * This function will check if the given certificate's subject matches
 * the given hostname.  This is a basic implementation of the matching
 * described in RFC2818 (HTTPS), which takes into account wildcards,
 * and the DNSName/IPAddress subject alternative name PKIX extension.
 *
 * Returns: 1 for a successful match, and 0 on failure.
 **/
static int verify_hostname(X509* cert, const char *hostname)
{
    GENERAL_NAMES* subject_alt_names;
    int found_dns_name = 0;
    struct in_addr addr;
    int addr_len = 0;
    int cn_match = 0;

    if (!cert) {
        SPICE_DEBUG("warning: no cert!");
        return 0;
    }

    // only IpV4 supported
    if (inet_aton(hostname, &addr)) {
        addr_len = sizeof(struct in_addr);
    }

    /* try matching against:
     *  1) a DNS name as an alternative name (subjectAltName) extension
     *     in the certificate
     *  2) the common name (CN) in the certificate
     *
     *  either of these may be of the form: *.domain.tld
     *
     *  only try (2) if there is no subjectAltName extension of
     *  type dNSName
     */

    /* Check through all included subjectAltName extensions, comparing
     * against all those of type dNSName.
     */
    subject_alt_names = (GENERAL_NAMES*)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);

    if (subject_alt_names) {
        int num_alts = sk_GENERAL_NAME_num(subject_alt_names);
        int i;
        for (i = 0; i < num_alts; i++) {
            const GENERAL_NAME* name = sk_GENERAL_NAME_value(subject_alt_names, i);
            if (name->type == GEN_DNS) {
                found_dns_name = 1;
                if (_gnutls_hostname_compare((char *)ASN1_STRING_data(name->d.dNSName),
                                             ASN1_STRING_length(name->d.dNSName),
                                             hostname)) {
                    SPICE_DEBUG("alt name match=%s", ASN1_STRING_data(name->d.dNSName));
                    GENERAL_NAMES_free(subject_alt_names);
                    return 1;
                }
            } else if (name->type == GEN_IPADD) {
                int alt_ip_len = ASN1_STRING_length(name->d.iPAddress);
                found_dns_name = 1;
                if ((addr_len == alt_ip_len)&&
                    !memcmp(ASN1_STRING_data(name->d.iPAddress), &addr, addr_len)) {
                    SPICE_DEBUG("alt name IP match=%s",
                                inet_ntoa(*((struct in_addr*)ASN1_STRING_data(name->d.dNSName))));
                    GENERAL_NAMES_free(subject_alt_names);
                    return 1;
                }
            }
        }
        GENERAL_NAMES_free(subject_alt_names);
    }

    if (found_dns_name) {
        SPICE_DEBUG("warning: SubjectAltName mismatch");
        return 0;
    }

    /* extracting commonNames */
    X509_NAME* subject = X509_get_subject_name(cert);
    if (subject) {
        int pos = -1;
        X509_NAME_ENTRY* cn_entry;
        ASN1_STRING* cn_asn1;

        while ((pos = X509_NAME_get_index_by_NID(subject, NID_commonName, pos)) != -1) {
            cn_entry = X509_NAME_get_entry(subject, pos);
            if (!cn_entry) {
                continue;
            }
            cn_asn1 = X509_NAME_ENTRY_get_data(cn_entry);
            if (!cn_asn1) {
                continue;
            }

            if (_gnutls_hostname_compare((char*)ASN1_STRING_data(cn_asn1),
                                         ASN1_STRING_length(cn_asn1),
                                         hostname)) {
                SPICE_DEBUG("common name match=%s", (char*)ASN1_STRING_data(cn_asn1));
                cn_match = 1;
                break;
            }
        }
    }

    if (!cn_match)
        SPICE_DEBUG("warning: common name mismatch");

    return cn_match;
}
Exemple #18
0
void
changepasswd(Ticketreq *tr)
{
	Ticket t;
	char tbuf[TICKETLEN+1];
	char prbuf[PASSREQLEN];
	Passwordreq pr;
	char okey[DESKEYLEN], nkey[DESKEYLEN];
	char *err;

	if(findkey(KEYDB, tr->uid, okey) == 0){
		/* make one up so caller doesn't know it was wrong */
		mkkey(okey);
		syslog(0, AUTHLOG, "cp-fail uid %s", raddr);
	}

	/* send back a ticket with a new key */
	memmove(t.chal, tr->chal, CHALLEN);
	mkkey(t.key);
	tbuf[0] = AuthOK;
	t.num = AuthTp;
	safecpy(t.cuid, tr->uid, sizeof(t.cuid));
	safecpy(t.suid, tr->uid, sizeof(t.suid));
	convT2M(&t, tbuf+1, okey);
	write(1, tbuf, sizeof(tbuf));

	/* loop trying passwords out */
	for(;;){
		if(readn(0, prbuf, PASSREQLEN) < 0)
			exits(0);
		convM2PR(prbuf, &pr, t.key);
		if(pr.num != AuthPass){
			replyerror("protocol botch1: %s", raddr);
			exits(0);
		}
		passtokey(nkey, pr.old);
		if(memcmp(nkey, okey, DESKEYLEN)){
			replyerror("protocol botch2: %s", raddr);
			continue;
		}
		if(*pr.new){
			err = okpasswd(pr.new);
			if(err){
				replyerror("%s %s", err, raddr);
				continue;
			}
			passtokey(nkey, pr.new);
		}
		if(pr.changesecret && setsecret(KEYDB, tr->uid, pr.secret) == 0){
			replyerror("can't write secret %s", raddr);
			continue;
		}
		if(*pr.new && setkey(KEYDB, tr->uid, nkey) == 0){
			replyerror("can't write key %s", raddr);
			continue;
		}
		break;
	}

	prbuf[0] = AuthOK;
	write(1, prbuf, 1);
	succeed(tr->uid);
	return;
}
Exemple #19
0
static int check(RBinArch *arch) {
	if (arch && arch->buf && arch->buf->buf)
		if (!memcmp (arch->buf->buf, RARVMHDR, 16))
			return R_TRUE;
	return R_FALSE;
}
Exemple #20
0
void
apop(Ticketreq *tr, int type)
{
	int challen, i, tries;
	char *secret, *hkey, *p;
	Ticketreq treq;
	DigestState *s;
	char sbuf[SECRETLEN], hbuf[DESKEYLEN];
	char tbuf[TICKREQLEN];
	char buf[MD5dlen*2];
	uchar digest[MD5dlen], resp[MD5dlen];
	ulong rb[4];
	char chal[256];

	USED(tr);

	/*
	 *  Create a challenge and send it.
	 */
	randombytes((uchar*)rb, sizeof(rb));
	p = chal;
	p += snprint(p, sizeof(chal), "<%lux%lux.%lux%lux@%s>",
		rb[0], rb[1], rb[2], rb[3], domainname());
	challen = p - chal;
	print("%c%-5d%s", AuthOKvar, challen, chal);

	/* give user a few attempts */
	for(tries = 0; ; tries++) {
		/*
		 *  get ticket request
		 */
		if(readn(0, tbuf, TICKREQLEN) < 0)
			exits(0);
		convM2TR(tbuf, &treq);
		tr = &treq;
		if(tr->type != type)
			exits(0);

		/*
		 * read response
		 */
		if(readn(0, buf, MD5dlen*2) < 0)
			exits(0);
		for(i = 0; i < MD5dlen; i++)
			resp[i] = (h2b(buf[2*i])<<4)|h2b(buf[2*i+1]);

		/*
		 * lookup
		 */
		secret = findsecret(KEYDB, tr->uid, sbuf);
		hkey = findkey(KEYDB, tr->hostid, hbuf);
		if(hkey == 0 || secret == 0){
			replyerror("apop-fail bad response %s", raddr);
			logfail(tr->uid);
			if(tries > 5)
				return;
			continue;
		}

		/*
		 *  check for match
		 */
		if(type == AuthCram){
			hmac_md5((uchar*)chal, challen,
				(uchar*)secret, strlen(secret),
				digest, nil);
		} else {
			s = md5((uchar*)chal, challen, 0, 0);
			md5((uchar*)secret, strlen(secret), digest, s);
		}
		if(memcmp(digest, resp, MD5dlen) != 0){
			replyerror("apop-fail bad response %s", raddr);
			logfail(tr->uid);
			if(tries > 5)
				return;
			continue;
		}
		break;
	}

	succeed(tr->uid);

	/*
	 *  reply with ticket & authenticator
	 */
	if(tickauthreply(tr, hkey) < 0)
		exits(0);

	if(debug){
		if(type == AuthCram)
			syslog(0, AUTHLOG, "cram-ok %s %s", tr->uid, raddr);
		else
			syslog(0, AUTHLOG, "apop-ok %s %s", tr->uid, raddr);
	}
}
Exemple #21
0
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b)
{
    return memcmp(a->sha1_hash, b->sha1_hash, 20);
}
Exemple #22
0
void
vnc(Ticketreq *tr)
{
	uchar chal[VNCchallen+6];
	uchar reply[VNCchallen];
	char *secret, *hkey;
	char sbuf[SECRETLEN], hbuf[DESKEYLEN];
	DESstate s;
	int i;

	/*
	 *  Create a challenge and send it.
	 */
	randombytes(chal+6, VNCchallen);
	chal[0] = AuthOKvar;
	snprint((char*)chal+1, sizeof chal - 1, "%-5d", VNCchallen);
	if(write(1, chal, sizeof(chal)) != sizeof(chal))
		return;

	/*
	 *  lookup keys (and swizzle bits)
	 */
	memset(sbuf, 0, sizeof(sbuf));
	secret = findsecret(KEYDB, tr->uid, sbuf);
	if(secret == 0){
		randombytes((uchar*)sbuf, sizeof(sbuf));
		secret = sbuf;
	}
	for(i = 0; i < 8; i++)
		secret[i] = swizzletab[(uchar)secret[i]];

	hkey = findkey(KEYDB, tr->hostid, hbuf);
	if(hkey == 0){
		randombytes((uchar*)hbuf, sizeof(hbuf));
		hkey = hbuf;
	}

	/*
	 *  get response
	 */
	if(readn(0, reply, sizeof(reply)) != sizeof(reply))
		return;

	/*
	 *  decrypt response and compare
	 */
	setupDESstate(&s, (uchar*)secret, nil);
	desECBdecrypt(reply, sizeof(reply), &s);
	if(memcmp(reply, chal+6, VNCchallen) != 0){
		replyerror("vnc-fail bad response %s", raddr);
		logfail(tr->uid);
		return;
	}
	succeed(tr->uid);

	/*
	 *  reply with ticket & authenticator
	 */
	if(tickauthreply(tr, hkey) < 0)
		exits(0);

	if(debug)
		syslog(0, AUTHLOG, "vnc-ok %s %s", tr->uid, raddr);
}
Exemple #23
0
static char *FindNextContent(char *ptr,
			     char *content_end,
			     interesting_mime_headers *SubMimeHeaders,
			     interesting_mime_headers *m)
{
	char *next_boundary;
	char  tmp;

	if (IsAsciiEncoding(SubMimeHeaders)) {
		tmp = *content_end;
		*content_end = '\0';

		/** 
		 * ok, if we have a content length of the mime part, 
		 * try skipping the content on the search for the next
		 * boundary. since we don't trust the content_length
		 * to be all accurate, and suspect it to lose one digit 
		 * per line with a line length of 80 chars, we need 
		 * to start searching a little before..
		 */
				   
		if ((SubMimeHeaders->content_length != -1) &&
		    (SubMimeHeaders->content_length > 10))
		{
			char *pptr;
			long lines;
					
			lines = SubMimeHeaders->content_length / 80;
			pptr = ptr + SubMimeHeaders->content_length - lines - 10;
			if (pptr < content_end)
				ptr = pptr;
		}
			
		next_boundary = strstr(ptr, m->b[startary].Key);
		*content_end = tmp;
	}
	else {
		char *srch;
		/** 
		 * ok, if we have a content length of the mime part, 
		 * try skipping the content on the search for the next
		 * boundary. since we don't trust the content_length
		 * to be all accurate, start searching a little before..
		 */
				   
		if ((SubMimeHeaders->content_length != -1) &&
		    (SubMimeHeaders->content_length > 10))
		{
			char *pptr;
			pptr = ptr + SubMimeHeaders->content_length - 10;
			if (pptr < content_end)
				ptr = pptr;
		}
		

		srch = next_boundary = NULL;
		for (srch = memchr(ptr, '-',  content_end - ptr);
		     (srch != NULL) && (srch < content_end); 
		     srch = memchr(srch, '-',  content_end - srch)) 
		{
			if (!memcmp(srch, 
				    m->b[startary].Key, 
				    m->b[startary].len)) 
			{
				next_boundary = srch;
				srch = content_end;
			}
			else srch ++;

		}

	}
	return next_boundary;
}
Exemple #24
0
void
mschap(Ticketreq *tr)
{

	char *secret, *hkey;
	char sbuf[SECRETLEN], hbuf[DESKEYLEN];
	uchar chal[CHALLEN];
	uchar hash[MShashlen];
	uchar hash2[MShashlen];
	uchar resp[MSresplen];
	OMSchapreply reply;
	int dupe, lmok, ntok;
	DigestState *s;
	uchar digest[SHA1dlen];

	/*
	 *  Create a challenge and send it.
	 */
	randombytes((uchar*)chal, sizeof(chal));
	write(1, chal, sizeof(chal));

	/*
	 *  get chap reply
	 */
	if(readn(0, &reply, sizeof(reply)) < 0)
		exits(0);

	safecpy(tr->uid, reply.uid, sizeof(tr->uid));
	/*
	 * lookup
	 */
	secret = findsecret(KEYDB, tr->uid, sbuf);
	hkey = findkey(KEYDB, tr->hostid, hbuf);
	if(hkey == 0 || secret == 0){
		replyerror("mschap-fail bad response %s/%s(%s)",
			tr->uid, tr->hostid, raddr);
		logfail(tr->uid);
		exits(0);
	}

	lmhash(hash, secret);
	mschalresp(resp, hash, chal);
	lmok = memcmp(resp, reply.LMresp, MSresplen) == 0;
	nthash(hash, secret);
	mschalresp(resp, hash, chal);
	ntok = memcmp(resp, reply.NTresp, MSresplen) == 0;
	dupe = memcmp(reply.LMresp, reply.NTresp, MSresplen) == 0;

	/*
	 * It is valid to send the same response in both the LM and NTLM 
	 * fields provided one of them is correct, if neither matches,
	 * or the two fields are different and either fails to match, 
	 * the whole sha-bang fails.
	 *
	 * This is an improvement in security as it allows clients who
	 * wish to do NTLM auth (which is insecure) not to send
	 * LM tokens (which is very insecure).
	 *
	 * Windows servers supports clients doing this also though
	 * windows clients don't seem to use the feature.
	 */
	if((!ntok && !lmok) || ((!ntok || !lmok) && !dupe)){
		replyerror("mschap-fail bad response %s/%s(%s) %d,%d,%d",
			tr->uid, tr->hostid, raddr, dupe, lmok, ntok);
		logfail(tr->uid);
		exits(0);
	}

	succeed(tr->uid);

	/*
	 *  reply with ticket & authenticator
	 */
	if(tickauthreply(tr, hkey) < 0)
		exits(0);

	if(debug)
		replyerror("mschap-ok %s/%s(%s) %ux",
			tr->uid, tr->hostid, raddr);

	nthash(hash, secret);
	md4(hash, 16, hash2, 0);
	s = sha1(hash2, 16, 0, 0);
	sha1(hash2, 16, 0, s);
	sha1(chal, 8, digest, s);

	if(write(1, digest, 16) < 0)
		exits(0);
}
Exemple #25
0
int quicktime_read_asf(quicktime_t *file)
{
	quicktime_asf_t *asf = calloc(1, sizeof(quicktime_asf_t));
	int got_header = 0;
	int debug = 1;
	int i;

	file->asf = asf;
	quicktime_set_position(file, 16 + 14);
	
	while(1)
	{
		quicktime_guid_t guid;
		int64_t guid_size;
		int64_t guid_start = quicktime_position(file);

		bzero(&guid, sizeof(guid));
		quicktime_read_guid(file, &guid);
		guid_size = quicktime_read_int64_le(file);

		printf("quicktime_read_asf start=0x%llx size=0x%llx\n", guid_start, guid_size);

// Glitch
		if(guid_size < 24) return 1;
		
		
		if(!memcmp(&guid, &file_header, sizeof(guid)))
		{
			quicktime_guid_t leaf_guid;
			got_header = 1;
			quicktime_read_guid(file, &leaf_guid);
			asf->header.file_size = quicktime_read_int64_le(file);
			asf->header.create_time = quicktime_read_int64_le(file);
			asf->header.total_packets = quicktime_read_int64_le(file);
			asf->header.send_time = quicktime_read_int64_le(file);
			asf->header.play_time = quicktime_read_int64_le(file);
			asf->header.preroll = quicktime_read_int32_le(file);
			asf->header.ignore = quicktime_read_int32_le(file);
			asf->header.flags = quicktime_read_int32_le(file);
			asf->header.min_packet = quicktime_read_int32_le(file);
			asf->header.max_packet = quicktime_read_int32_le(file);
			asf->header.max_bitrate = quicktime_read_int32_le(file);
			asf->header.packet_size = asf->header.max_packet;
		}
		else
		if(!memcmp(&guid, &index_guid, sizeof(guid)))
		{
			quicktime_guid_t leaf_guid;
			int max;
			int count;
			int total_packets = 0;

// Leaf Guid
			quicktime_read_guid(file, &leaf_guid);
// indexed interval
			quicktime_read_int64_le(file);
// max
			max = quicktime_read_int32_le(file);
// count
			asf->index_size = quicktime_read_int32_le(file);
			asf->index = calloc(sizeof(quicktime_asfpacket_t), asf->index_size);

			for(i = 0; i < asf->index_size; i++)
			{
				asf->index[i].number = quicktime_read_int32_le(file);
				asf->index[i].count = quicktime_read_int16_le(file);
			}
		}
		else
		if(!memcmp(&guid, &stream_header, sizeof(guid)))
		{
			quicktime_asfstream_t *stream = 
				asf->streams[asf->total_streams++] = 
				new_asfstream();
			quicktime_guid_t leaf_guid;
			quicktime_read_guid(file, &leaf_guid);
			if(!memcmp(&leaf_guid, &audio_stream, sizeof(leaf_guid)))
				stream->is_audio = 1;
			else
			if(!memcmp(&leaf_guid, &video_stream, sizeof(leaf_guid)))
				stream->is_video = 1;
			else
			if(!memcmp(&leaf_guid, &ext_stream_embed_stream_header, sizeof(leaf_guid)))
				stream->is_ext_audio = 1;
			quicktime_read_guid(file, &leaf_guid);
			
			stream->total_size = quicktime_read_int64_le(file);
			stream->type_specific_size = quicktime_read_int32_le(file);
			quicktime_read_int32_le(file);
			stream->id = quicktime_read_int16_le(file) & 0x7f;
			quicktime_read_int32_le(file);
			if(stream->is_ext_audio)
			{
				quicktime_read_guid(file, &leaf_guid);
                if (!memcmp(&leaf_guid, &ext_stream_audio_stream, sizeof(leaf_guid)))
				{
                    stream->is_audio = 1;
					stream->is_ext_audio = 0;
                    quicktime_read_guid(file, &leaf_guid);
                    quicktime_read_int32_le(file);
                    quicktime_read_int32_le(file);
                    quicktime_read_int32_le(file);
                    quicktime_read_guid(file, &leaf_guid);
                    quicktime_read_int32_le(file);
                }
			}
			
			
			if(stream->is_audio)
			{
// Get WAV header
				stream->codec_tag = quicktime_read_int16_le(file);
				stream->channels = quicktime_read_int16_le(file);
				stream->samplerate = quicktime_read_int32_le(file);
				stream->bitrate = quicktime_read_int32_le(file);
				stream->block_align = quicktime_read_int16_le(file);
				if(stream->type_specific_size == 14)
					stream->bits_per_sample = 8;
				else
					stream->bits_per_sample = quicktime_read_int16_le(file);
				if(stream->type_specific_size > 16)
				{
					stream->extradata_size = quicktime_read_int16_le(file);
        			if (stream->extradata_size > 0) 
					{
            			if (stream->extradata_size > stream->type_specific_size - 18)
                			stream->extradata_size = stream->type_specific_size - 18;
            			stream->extradata = calloc(1, stream->extradata_size + 1024);
            			quicktime_read_data(file, stream->extradata, stream->extradata_size);
        			}
					else
            			stream->extradata_size = 0;
					
					if(stream->type_specific_size - stream->extradata_size - 18 > 0)
						quicktime_set_position(file,
							quicktime_position(file) + 
							stream->type_specific_size - 
							stream->extradata_size - 18);
				}

// Make fourcc from codec_tag and bits_per_sample
			}
			else
			if(stream->is_video)
			{
				int size1;
				int size2;
				quicktime_read_int32_le(file);
				quicktime_read_int32_le(file);
				quicktime_read_char(file);
				size1 = quicktime_read_int16_le(file);
				size2 = quicktime_read_int32_le(file);
				stream->width = quicktime_read_int32_le(file);
				stream->height = quicktime_read_int32_le(file);
				quicktime_read_int16_le(file);
				stream->bits_per_sample = quicktime_read_int16_le(file);
				stream->codec_tag = quicktime_read_int32_le(file);
				quicktime_set_position(file, quicktime_position(file) + 20);
				if(size1 > 40)
				{
					stream->extradata_size = size1 - 40;
					stream->extradata = calloc(1, stream->extradata_size + 1024);
					quicktime_read_data(file, stream->extradata, stream->extradata_size);
				}

// Make fourcc from codec_tag
				stream->fourcc[0] = (stream->codec_tag & 0xff);
				stream->fourcc[1] = (stream->codec_tag & 0xff00) >> 8;
				stream->fourcc[2] = (stream->codec_tag & 0xff0000) >> 16;
				stream->fourcc[3] = (stream->codec_tag & 0xff000000) >> 24;
			}
		}
Exemple #26
0
void cmd_sdiotest(void) {
  uint32_t i = 0;
  FRESULT err = 0;
  bool_t format = FALSE;


  chThdSleepMilliseconds(100);

  if (!sdioConnect ()) {
    sdioDebug ("   FAIL\r\n ");
    return;
  }

  if (TRUE) {
    sdioDebug ("OK\r\n");
    sdioDebug ("*** Card CSD content is: ");
    sdioDebug ("%X %X %X %X \r\n", (&SDCD1)->csd[3], (&SDCD1)->csd[2],
        (&SDCD1)->csd[1], (&SDCD1)->csd[0]);


    sdioDebug ("capacity = %d sectors of 512 bytes = %d Mo\r\n",
        SDCD1.capacity, SDCD1.capacity / 2048);

    sdioDebug ("Single aligned read...");
    chThdSleepMilliseconds(100);
    if (sdcRead(&SDCD1, 0, inbuf, 1))
      goto error;
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);


    sdioDebug ("Single unaligned read...");
    chThdSleepMilliseconds(100);
    if (sdcRead(&SDCD1, 0, inbuf + 1, 1))
      goto error;
    if (sdcRead(&SDCD1, 0, inbuf + 2, 1))
      goto error;
    if (sdcRead(&SDCD1, 0, inbuf + 3, 1))
      goto error;
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);


    sdioDebug ("Multiple aligned reads...");
    chThdSleepMilliseconds(100);
    fillbuffers(0x55);
    /* fill reference buffer from SD card */
    if (sdcRead(&SDCD1, 0, inbuf, SDC_BURST_SIZE))
      goto error;
    for (i=0; i<1000; i++){
      if (sdcRead(&SDCD1, 0, outbuf, SDC_BURST_SIZE))
        goto error;
      if (memcmp(inbuf, outbuf, SDC_BURST_SIZE * MMCSD_BLOCK_SIZE) != 0)
        goto error;
    }
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);


    sdioDebug ("Multiple unaligned reads...");
    chThdSleepMilliseconds(100);
    fillbuffers(0x55);
    /* fill reference buffer from SD card */
    if (sdcRead(&SDCD1, 0, inbuf + 1, SDC_BURST_SIZE))
      goto error;
    for (i=0; i<1000; i++){
      if (sdcRead(&SDCD1, 0, outbuf + 1, SDC_BURST_SIZE))
        goto error;
      if (memcmp(inbuf, outbuf, SDC_BURST_SIZE * MMCSD_BLOCK_SIZE) != 0)
        goto error;
    }
    sdioDebug (" OK\r\n");
    chThdSleepMilliseconds(100);

#if SDC_DATA_DESTRUCTIVE_TEST
    if (format) {

      sdioDebug ("Single aligned write...");
      chThdSleepMilliseconds(100);
      fillbuffer(0xAA, inbuf);
      if (sdcWrite(&SDCD1, 0, inbuf, 1))
        goto error;
      fillbuffer(0, outbuf);
      if (sdcRead(&SDCD1, 0, outbuf, 1))
        goto error;
      if (memcmp(inbuf, outbuf, MMCSD_BLOCK_SIZE) != 0)
        goto error;
      sdioDebug (" OK\r\n");

      sdioDebug ("Running badblocks at 0x10000 offset...");
      chThdSleepMilliseconds(100);
      if(badblocks(0x10000, 0x11000, SDC_BURST_SIZE, 0xAA))
        goto error;
      sdioDebug (" OK\r\n");
    } else {

    }
#endif /* !SDC_DATA_DESTRUCTIVE_TEST */


    /**
     * Now perform some FS tests.
     */

    DWORD clusters=0;
    FATFS *fsp=NULL;
    FIL FileObject;
    uint32_t bytes_written=0;
    uint32_t bytes_read=0;
    FILINFO fno ;
#if _USE_LFN
    char lfn[_MAX_LFN + 1];
    fno.lfname = lfn;
    fno.lfsize = sizeof lfn;
#endif

    const uint8_t teststring[] = {"This is test file\r\n"} ;
    /* FS object.*/
    static FATFS SDC_FS;




#if SDC_DATA_DESTRUCTIVE_TEST
    if (format) {
      sdioDebug ("Formatting... ");
      chThdSleepMilliseconds(100);

      sdioDebug ("Register working area for filesystem... ");
      chThdSleepMilliseconds(100);
      err = f_mount(0, &SDC_FS);
      if (err != FR_OK){
        goto error;
      }
      else{
        sdioDebug ("OK\r\n");
      }
    }

    if (format) {
      sdioDebug ("f_mkfs starting ... ");
      chThdSleepMilliseconds(100);
      err = f_mkfs (0,0,0);
      if (err != FR_OK){
        goto error;
      }  else {
        sdioDebug ("OK\r\n");
      }
    }
#endif /* SDC_DATA_DESTRUCTIVE_TEST */


    sdioDebug ("get free space on filesystem... ");
    chThdSleepMilliseconds(100);
    err =  f_getfree(NULL, &clusters, &fsp);

    if (err != FR_OK)
      goto error;

    sdioDebug ("OK\r\n");
    sdioDebug ("FS: %lu free clusters, %lu sectors per cluster, %lu bytes free\r\n",
        clusters, (uint32_t)SDC_FS.csize,
        clusters * (uint32_t)SDC_FS.csize * (uint32_t)MMCSD_BLOCK_SIZE);


    sdioDebug ("Create file \"chtest.txt\"... ");
    chThdSleepMilliseconds(100);
    err = f_open(&FileObject, "chtest.txt", FA_WRITE | FA_OPEN_ALWAYS);
    if (err != FR_OK) {
      goto error;
    }
    sdioDebug ("OK\r\n");
    sdioDebug ("Write some data in it... ");
    chThdSleepMilliseconds(100);
    err = f_write(&FileObject, teststring, sizeof(teststring), (void *)&bytes_written);
    if (err != FR_OK) {
      goto error;
    }
    else
      sdioDebug ("OK\r\n");

    sdioDebug ("Close file \"chtest.txt\"... ");
    err = f_close(&FileObject);
    if (err != FR_OK) {
      goto error;
    }
    else
      sdioDebug ("OK\r\n");


    sdioDebug ("Check file size \"chtest.txt\"... ");
    chThdSleepMilliseconds(10);
    err = f_stat("chtest.txt", &fno);
    chThdSleepMilliseconds(100);
    if (err != FR_OK) {
      goto error;
    } else {
      if (fno.fsize == sizeof(teststring)) {
        sdioDebug ("OK\r\n");
      }
      else
        goto error;
    }


    sdioDebug ("Check file content \"chtest.txt\"... ");
    err = f_open(&FileObject, "chtest.txt", FA_READ | FA_OPEN_EXISTING);
    chThdSleepMilliseconds(100);
    if (err != FR_OK) {
      goto error;
    }
    uint8_t buf[sizeof(teststring)];
    err = f_read(&FileObject, buf, sizeof(teststring), (void *)&bytes_read);
    if (err != FR_OK) {
      goto error;
    } else {
      if (memcmp(teststring, buf, sizeof(teststring)) != 0){
        goto error;
      } else {
        sdioDebug ("OK\r\n");
      }
    }

    {
      FILINFO fno;
      DIR dir;
      //    char *fn;   /* This function is assuming non-Unicode cfg. */
#if _USE_LFN
      char lfn[_MAX_LFN + 1];
      fno.lfname = lfn;
      fno.lfsize = sizeof lfn;
#endif
      const char *path = "";
      FRESULT res =0;

      res = f_opendir(&dir, path);                       /* Open the directory */
      if (res == FR_OK) {
        for (;;) {
          res = f_readdir(&dir, &fno);                   /* Read a directory item */
          if (res != FR_OK || fno.fname[0] == 0) break;  /* Break on error or end of dir */
          if (fno.fname[0] == '.') continue;             /* Ignore dot entry */
#if _USE_LFN
          // fn = fno.lfname;
#else
          // fn = fno.fname;
#endif
          /* It is a file. */
          //chprintf(chp, "readdir %s/%s\r\n", path, fn);
        }
      }
    }

    sdioDebug ("Umount filesystem... ");
    f_mount(0, NULL);
    sdioDebug ("OK\r\n");

    sdioDebug ("Disconnecting from SDIO...");
    chThdSleepMilliseconds(100);
    if (!sdioDisconnect())
      goto error;
    sdioDebug (" OK\r\n");
    sdioDebug ("------------------------------------------------------\r\n");
    sdioDebug ("All tests passed successfully.\r\n");
    chThdSleepMilliseconds(100);


    sdioDisconnect();
    return;
  }
error:
  sdioDebug ("SDC error [%d] occurs\r\n", err);
  sdioDisconnect();
}
Exemple #27
0
int crt_memcmp(const void *ptr1, const void *ptr2, size_t len)
{
	return memcmp(ptr1, ptr2, len);
}
static void rs_packet_process(uint64_t count, rs_event_t *event, struct pcap_pkthdr const *header, uint8_t const *data)
{
	rs_stats_t		*stats = event->stats;
	struct timeval		elapsed;
	struct timeval		latency;

	/*
	 *	Pointers into the packet data we just received
	 */
	size_t len;
	uint8_t const		*p = data;
	struct ip_header const	*ip = NULL;	/* The IP header */
	struct ip_header6 const	*ip6 = NULL;	/* The IPv6 header */
	struct udp_header const	*udp;		/* The UDP header */
	uint8_t			version;	/* IP header version */
	bool			response;	/* Was it a response code */

	decode_fail_t		reason;		/* Why we failed decoding the packet */
	static uint64_t		captured = 0;

	RADIUS_PACKET *current;			/* Current packet were processing */
	rs_request_t *original;

	if (!start_pcap.tv_sec) {
		start_pcap = header->ts;
	}

	if (header->caplen <= 5) {
		INFO("Packet too small, captured %i bytes", header->caplen);
		return;
	}

	/*
	 *	Loopback header
	 */
	if ((p[0] == 2) && (p[1] == 0) && (p[2] == 0) && (p[3] == 0)) {
		p += 4;
	/*
	 *	Ethernet header
	 */
	} else {
		p += sizeof(struct ethernet_header);
	}

	version = (p[0] & 0xf0) >> 4;
	switch (version) {
	case 4:
		ip = (struct ip_header const *)p;
		len = (0x0f & ip->ip_vhl) * 4;	/* ip_hl specifies length in 32bit words */
		p += len;
		break;

	case 6:
		ip6 = (struct ip_header6 const *)p;
		p += sizeof(struct ip_header6);

		break;

	default:
		DEBUG("IP version invalid %i", version);
		return;
	}

	/*
	 *	End of variable length bits, do basic check now to see if packet looks long enough
	 */
	len = (p - data) + sizeof(struct udp_header) + (sizeof(radius_packet_t) - 1);	/* length value */
	if (len > header->caplen) {
		DEBUG("Packet too small, we require at least %zu bytes, captured %i bytes",
		      (size_t) len, header->caplen);
		return;
	}

	udp = (struct udp_header const *)p;
	p += sizeof(struct udp_header);

	/*
	 *	With artificial talloc memory limits there's a good chance we can
	 *	recover once some requests timeout, so make an effort to deal
	 *	with allocation failures gracefully.
	 */
	current = rad_alloc(conf, 0);
	if (!current) {
		ERROR("Failed allocating memory to hold decoded packet");
		rs_tv_add_ms(&header->ts, conf->stats.timeout, &stats->quiet);
		return;
	}
	current->timestamp = header->ts;
	current->data_len = header->caplen - (p - data);
	memcpy(&current->data, &p, sizeof(current->data));

	/*
	 *	Populate IP/UDP fields from PCAP data
	 */
	if (ip) {
		current->src_ipaddr.af = AF_INET;
		current->src_ipaddr.ipaddr.ip4addr.s_addr = ip->ip_src.s_addr;

		current->dst_ipaddr.af = AF_INET;
		current->dst_ipaddr.ipaddr.ip4addr.s_addr = ip->ip_dst.s_addr;
	} else {
		current->src_ipaddr.af = AF_INET6;
		memcpy(&current->src_ipaddr.ipaddr.ip6addr.s6_addr, &ip6->ip_src.s6_addr,
		       sizeof(current->src_ipaddr.ipaddr.ip6addr.s6_addr));

		current->dst_ipaddr.af = AF_INET6;
		memcpy(&current->dst_ipaddr.ipaddr.ip6addr.s6_addr, &ip6->ip_dst.s6_addr,
		       sizeof(current->dst_ipaddr.ipaddr.ip6addr.s6_addr));
	}

	current->src_port = ntohs(udp->udp_sport);
	current->dst_port = ntohs(udp->udp_dport);

	if (!rad_packet_ok(current, 0, &reason)) {
		RIDEBUG("(%" PRIu64 ") ** %s **", count, fr_strerror());
		RIDEBUG("(%" PRIu64 ") %s Id %i %s:%s:%d -> %s:%d\t+%u.%03u", count,
			fr_packet_codes[current->code], current->id,
			event->in->name,
			fr_inet_ntop(current->src_ipaddr.af, &current->src_ipaddr.ipaddr), current->src_port,
			fr_inet_ntop(current->dst_ipaddr.af, &current->dst_ipaddr.ipaddr), current->dst_port,
			(unsigned int) elapsed.tv_sec, ((unsigned int) elapsed.tv_usec / 1000));

		rad_free(&current);
		return;
	}

	switch (current->code) {
	case PW_CODE_ACCOUNTING_RESPONSE:
	case PW_CODE_AUTHENTICATION_REJECT:
	case PW_CODE_AUTHENTICATION_ACK:
	case PW_CODE_COA_NAK:
	case PW_CODE_COA_ACK:
	case PW_CODE_DISCONNECT_NAK:
	case PW_CODE_DISCONNECT_ACK:
	case PW_CODE_STATUS_CLIENT:
		{
			rs_request_t search;
			struct timeval when;

			rs_tv_add_ms(&header->ts, conf->stats.timeout, &when);

			/* look for a matching request and use it for decoding */
			search.packet = current;
			original = rbtree_finddata(request_tree, &search);

			/*
			 *	Only decode attributes if we want to print them or filter on them
			 *	rad_packet_ok does checks to verify the packet is actually valid.
			 */
			if (filter_vps || conf->print_packet) {
				if (rad_decode(current, original ? original->packet : NULL,
					       conf->radius_secret) != 0) {
					rad_free(&current);
					fr_perror("decode");
					return;
				}
			}

			/*
			 *	Check if we've managed to link it to a request
			 */
			if (original) {
				/*
				 *	Is this a retransmit?
				 */
				if (!original->linked) {
					original->stats_rsp = &stats->exchange[current->code];
				} else {
					RDEBUG("(%" PRIu64 ") ** RETRANSMISSION **", count);
					original->rt_rsp++;

					rad_free(&original->linked);
					fr_event_delete(event->list, &original->event);
				}

				original->linked = talloc_steal(original, current);

				/*
				 *	Some RADIUS servers and proxy servers may not cache
				 *	Accounting-Responses (and possibly other code),
				 *	and may immediately re-use a RADIUS packet src
				 *	port/id combination on receipt of a response.
				 */
				if (conf->dequeue[current->code]) {
					fr_event_delete(event->list, &original->event);
					rbtree_deletebydata(request_tree, original);
				} else {
					if (!fr_event_insert(event->list, rs_packet_cleanup, original, &when,
						    	     &original->event)) {
						ERROR("Failed inserting new event");
						/*
						 *	Delete the original request/event, it's no longer valid
						 *	for statistics.
						 */
						original->forced_cleanup = true;
						fr_event_delete(event->list, &original->event);
						rbtree_deletebydata(request_tree, original);

						return;
					}
				}
			/*
			 *	No request seen, or request was dropped by attribute filter
			 */
			} else {
				/*
				 *	If filter_vps are set assume the original request was dropped,
				 *	the alternative is maintaining another 'filter', but that adds
				 *	complexity, reduces max capture rate, and is generally a PITA.
				 */
				if (filter_vps) {
					rad_free(&current);
					RDEBUG2("(%" PRIu64 ") Dropped by attribute filter", count);
					return;
				}

				RDEBUG("(%" PRIu64 ") ** UNLINKED **", count);
				stats->exchange[current->code].interval.unlinked_total++;
			}

			response = true;
		}
			break;
	case PW_CODE_ACCOUNTING_REQUEST:
	case PW_CODE_AUTHENTICATION_REQUEST:
	case PW_CODE_COA_REQUEST:
	case PW_CODE_DISCONNECT_REQUEST:
	case PW_CODE_STATUS_SERVER:
		{
			rs_request_t search;
			struct timeval when;

			/*
			 *	Only decode attributes if we want to print them or filter on them
			 *	rad_packet_ok does checks to verify the packet is actually valid.
			 */
			if (filter_vps || conf->print_packet) {
				if (rad_decode(current, NULL, conf->radius_secret) != 0) {
					rad_free(&current);
					fr_perror("decode");
					return;
				}
			}

			/*
			 *	Now verify the packet passes the attribute filter
			 */
			if (filter_vps && !pairvalidate_relaxed(filter_vps, current->vps)) {
				rad_free(&current);
				RDEBUG2("(%" PRIu64 ") Dropped by attribute filter", count);
				return;
			}

			/*
			 *	save the request for later matching
			 */
			search.packet = rad_alloc_reply(conf, current);
			if (!search.packet) {
				ERROR("Failed allocating memory to hold expected reply");
				rs_tv_add_ms(&header->ts, conf->stats.timeout, &stats->quiet);
				rad_free(&current);
				return;
			}
			search.packet->code = current->code;

			rs_tv_add_ms(&header->ts, conf->stats.timeout, &when);

			original = rbtree_finddata(request_tree, &search);

			/*
			 *	Upstream device re-used src/dst ip/port id without waiting
			 *	for the timeout period to expire, or a response.
			 */
			if (original && memcmp(original->packet->vector, current->vector,
					       sizeof(original->packet->vector) != 0)) {
				RDEBUG2("(%" PRIu64 ") ** PREMATURE ID RE-USE **", count);
				stats->exchange[current->code].interval.reused_total++;
				original->forced_cleanup = true;

				fr_event_delete(event->list, &original->event);
				rbtree_deletebydata(request_tree, original);
				original = NULL;
			}

			if (original) {
				RDEBUG("(%" PRIu64 ") ** RETRANSMISSION **", count);
				original->rt_req++;

				rad_free(&original->packet);
				original->packet = talloc_steal(original, search.packet);

				/* We may of seen the response, but it may of been lost upstream */
				rad_free(&original->linked);
				fr_event_delete(event->list, &original->event);
			} else {
				original = talloc_zero(conf, rs_request_t);
				talloc_set_destructor(original, _request_free);

				original->id = count;
				original->in = event->in;
				original->stats_req = &stats->exchange[current->code];
				original->packet = talloc_steal(original, search.packet);

				rbtree_insert(request_tree, original);
			}

			/* update the timestamp in either case */
			original->packet->timestamp = header->ts;

			if (!fr_event_insert(event->list, rs_packet_cleanup, original, &when, &original->event)) {
				ERROR("Failed inserting new event");
				rbtree_deletebydata(request_tree, original);

				return;
			}
			response = false;
		}
			break;
		default:
			RDEBUG("** Unsupported code %i **", current->code);
			rad_free(&current);

			return;
	}

	if (event->out) {
		pcap_dump((void *) (event->out->dumper), header, data);
	}

	rs_tv_sub(&header->ts, &start_pcap, &elapsed);

	/*
	 *	Increase received count
	 */
	stats->exchange[current->code].interval.received_total++;

	/*
	 *	It's a linked response
	 */
	if (original && original->linked) {
		rs_tv_sub(&current->timestamp, &original->packet->timestamp, &latency);

		/*
		 *	Update stats for both the request and response types.
		 *
		 *	This isn't useful for things like Access-Requests, but will be useful for
		 *	CoA and Disconnect Messages, as we get the average latency across both
		 *	response types.
		 *
		 *	It also justifies allocating 255 instances rs_latency_t.
		 */
		rs_stats_update_latency(&stats->exchange[current->code], &latency);
		rs_stats_update_latency(&stats->exchange[original->packet->code], &latency);


		/*
		 *	Print info about the request/response.
		 */
		RIDEBUG("(%" PRIu64 ") %s Id %i %s:%s:%d %s %s:%d\t+%u.%03u\t+%u.%03u", count,
			fr_packet_codes[current->code], current->id,
			event->in->name,
			fr_inet_ntop(current->src_ipaddr.af, &current->src_ipaddr.ipaddr), current->src_port,
			response ? "<-" : "->",
			fr_inet_ntop(current->dst_ipaddr.af, &current->dst_ipaddr.ipaddr), current->dst_port,
			(unsigned int) elapsed.tv_sec, ((unsigned int) elapsed.tv_usec / 1000),
			(unsigned int) latency.tv_sec, ((unsigned int) latency.tv_usec / 1000));
	/*
	 *	It's the original request
	 */
	} else {
		/*
		 *	Print info about the request
		 */
		RIDEBUG("(%" PRIu64 ") %s Id %i %s:%s:%d %s %s:%d\t+%u.%03u", count,
			fr_packet_codes[current->code], current->id,
			event->in->name,
			fr_inet_ntop(current->src_ipaddr.af, &current->src_ipaddr.ipaddr), current->src_port,
			response ? "<-" : "->",
			fr_inet_ntop(current->dst_ipaddr.af, &current->dst_ipaddr.ipaddr), current->dst_port,
			(unsigned int) elapsed.tv_sec, ((unsigned int) elapsed.tv_usec / 1000));
	}

	if (conf->print_packet && (fr_debug_flag > 1) && current->vps) {
		pairsort(&current->vps, true);
		vp_printlist(log_dst, current->vps);
		pairfree(&current->vps);
	}

	if (!conf->to_stdout && (fr_debug_flag > 4)) {
		rad_print_hex(current);
	}

	fflush(log_dst);

	/*
	 *	If it's a request, a duplicate of the packet will of already been stored.
	 *	If it's a unlinked response, we need to free it explicitly, as it will
	 *	not be done by the event queue.
	 */
	if (!response || !original) {
		rad_free(&current);
	}

	captured++;
	/*
	 *	We've hit our capture limit, break out of the event loop
	 */
	if ((conf->limit > 0) && (captured >= conf->limit)) {
		INFO("Captured %" PRIu64 " packets, exiting...", captured);
		fr_event_loop_exit(events, 1);
	}
}
Exemple #29
0
VGMSTREAM * init_vgmstream_ps2_vag(STREAMFILE *streamFile) {
    VGMSTREAM * vgmstream = NULL;
    char filename[PATH_LIMIT];
	
	// used for loop points ...
	uint8_t eofVAG[16]={0x00,0x07,0x77,0x77,0x77,0x77,0x77,0x77,0x77,0x77,0x77,0x77,0x77,0x77,0x77,0x77};
	uint8_t eofVAG2[16]={0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
	uint8_t readbuf[16];

	off_t readOffset = 0x20;

	off_t loopStart = 0;
	off_t loopEnd = 0;

	uint8_t	vagID;
	off_t start_offset;
	size_t fileLength;

	size_t interleave;
	
    int loop_flag=0;
    int channel_count=1;
    int i;

    /* check extension, case insensitive */
    streamFile->get_name(streamFile,filename,sizeof(filename));
    if (strcasecmp("vag",filename_extension(filename))) goto fail;

    /* check VAG Header */
    if (((read_32bitBE(0x00,streamFile) & 0xFFFFFF00) != 0x56414700) && 
 		((read_32bitLE(0x00,streamFile) & 0xFFFFFF00) != 0x56414700))
        goto fail;

	/* Check for correct channel count */
	vagID=read_8bit(0x03,streamFile);

	switch(vagID) {
        case '1':
            channel_count=1;
            break;
        case '2':
            channel_count=2;
            break;
		case 'i':
			channel_count=2;
			break;
		case 'V':
			if(read_32bitBE(0x20,streamFile)==0x53746572) // vag Stereo
				channel_count=2;
		case 'p':
			if((read_32bitBE(0x04,streamFile)<=0x00000004) && (read_32bitBE(0x0c,streamFile)<(get_streamfile_size(streamFile)/2))) {
				loop_flag=(read_32bitBE(0x14,streamFile)!=0);
				channel_count=2;
			} else {
				/* Search for loop in VAG */
				fileLength = get_streamfile_size(streamFile);
				
				do {
					readOffset+=0x10; 
					
					// Loop Start ...
					if(read_8bit(readOffset+0x01,streamFile)==0x06) {
						if(loopStart==0) loopStart = readOffset;
					}

					// Loop End ...
					if(read_8bit(readOffset+0x01,streamFile)==0x03) {
						if(loopEnd==0) loopEnd = readOffset;
					}

					// Loop from end to beginning ...
					if((read_8bit(readOffset+0x01,streamFile)==0x01)) {
						// Check if we have the eof tag after the loop point ...
						// if so we don't loop, if not present, we loop from end to start ...
						read_streamfile(readbuf,readOffset+0x10,0x10,streamFile);
						if((readbuf[0]!=0) && (readbuf[0]!=0x0c)) {
							if(memcmp(readbuf,eofVAG,0x10) && (memcmp(readbuf,eofVAG2,0x10))) {
								loopStart = 0x40;
								loopEnd = readOffset;
							}
						}
					}

				} while (streamFile->get_offset(streamFile)<(off_t)fileLength);
				loop_flag = (loopEnd!=0);
			}
			break;
        default:
            goto fail;
	}

	/* build the VGMSTREAM */
    vgmstream = allocate_vgmstream(channel_count,loop_flag);
    if (!vgmstream) goto fail;

    /* fill in the vital statistics */
    vgmstream->channels = channel_count;

	switch(vagID) {
        case '1': // VAG1
			vgmstream->layout_type=layout_none;
			vgmstream->sample_rate = read_32bitBE(0x10,streamFile);
			vgmstream->num_samples = read_32bitBE(0x0C,streamFile)/16*28;
			interleave = read_32bitLE(0x08,streamFile);
            if (interleave != 0) goto fail;
			vgmstream->meta_type=meta_PS2_VAG1;
			start_offset=0x40;
            break;
        case '2': // VAG2
			vgmstream->layout_type=layout_interleave;
			vgmstream->sample_rate = read_32bitBE(0x10,streamFile);
			vgmstream->num_samples = read_32bitBE(0x0C,streamFile)/16*28;
			interleave = 0x800;
			vgmstream->meta_type=meta_PS2_VAG2;
			start_offset=0x40;
            break;
		case 'i': // VAGi
			vgmstream->layout_type=layout_interleave;
			vgmstream->sample_rate = read_32bitBE(0x10,streamFile);
			vgmstream->num_samples = read_32bitBE(0x0C,streamFile)/16*28;
			interleave = read_32bitLE(0x08,streamFile);
			vgmstream->meta_type=meta_PS2_VAGi;
			start_offset=0x800;
			break;
		case 'p': // VAGp
			vgmstream->sample_rate = read_32bitBE(0x10,streamFile);
			interleave=0x10; // used for loop calc

			if((read_32bitBE(0x04,streamFile)==0x00000004) && (read_32bitBE(0x0c,streamFile)<(get_streamfile_size(streamFile)/2))) {
				vgmstream->channels=2;
				vgmstream->num_samples = read_32bitBE(0x0C,streamFile);

				if(loop_flag) {
					vgmstream->loop_start_sample=read_32bitBE(0x14,streamFile);
					vgmstream->loop_end_sample =read_32bitBE(0x18,streamFile);
				}

				start_offset=0x80;
				vgmstream->layout_type=layout_interleave;
				vgmstream->meta_type=meta_PS2_VAGs;

				// Double VAG Header @ 0x0000 & 0x1000
				if(read_32bitBE(0,streamFile)==read_32bitBE(0x1000,streamFile)) {
					vgmstream->num_samples = read_32bitBE(0x0C,streamFile)/16*28;
					interleave=0x1000;
					start_offset=0;
				}

			} else {
				vgmstream->layout_type=layout_none;
				vgmstream->num_samples = read_32bitBE(0x0C,streamFile)/16*28;
				vgmstream->meta_type=meta_PS2_VAGp;
				start_offset=0x30;
			}
			break;
		case 'V': // pGAV
			vgmstream->layout_type=layout_interleave;
			interleave=0x2000;

			// Jak X hack ...
			if(read_32bitLE(0x1000,streamFile)==0x56414770)
				interleave=0x1000;

			vgmstream->sample_rate = read_32bitLE(0x10,streamFile);
			vgmstream->num_samples = read_32bitLE(0x0C,streamFile)/16*14;
			vgmstream->meta_type=meta_PS2_pGAV;
			start_offset=0;
			break;
        default:
            goto fail;
	}

	vgmstream->interleave_block_size=interleave;
	
	/* Don't add the header size to loop calc points */
	if(vgmstream->meta_type!=meta_PS2_VAGs) {
		loopStart-=start_offset;
		loopEnd-=start_offset;

		if(loop_flag!=0) {
			vgmstream->loop_start_sample = (int32_t)((loopStart/(interleave*channel_count))*interleave)/16*28;
			vgmstream->loop_start_sample += (int32_t)(loopStart%(interleave*channel_count))/16*28;
			vgmstream->loop_end_sample = (int32_t)((loopEnd/(interleave*channel_count))*interleave)/16*28;
			vgmstream->loop_end_sample += (int32_t)(loopEnd%(interleave*channel_count))/16*28;
		}
	}

    /* Compression Scheme */
    vgmstream->coding_type = coding_PSX;

    /* open the file for reading by each channel */
    {
        for (i=0;i<channel_count;i++) {
            if (vgmstream->interleave_block_size > 0) {
                vgmstream->ch[i].streamfile = streamFile->open(streamFile,filename,vgmstream->interleave_block_size);
            } else {
                vgmstream->ch[i].streamfile = streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE);
            }

            if (!vgmstream->ch[i].streamfile) goto fail;

            vgmstream->ch[i].channel_start_offset=
                vgmstream->ch[i].offset=
                (off_t)(start_offset+vgmstream->interleave_block_size*i);
        }
    }

    return vgmstream;

    /* clean up anything we may have opened */
fail:
    if (vgmstream) close_vgmstream(vgmstream);
    return NULL;
}
Exemple #30
0
static void process_alternates_response(void *callback_data)
{
	struct alternates_request *alt_req =
		(struct alternates_request *)callback_data;
	struct walker *walker = alt_req->walker;
	struct walker_data *cdata = walker->data;
	struct active_request_slot *slot = alt_req->slot;
	struct alt_base *tail = cdata->alt;
	const char *base = alt_req->base;
	const char null_byte = '\0';
	char *data;
	int i = 0;

	if (alt_req->http_specific) {
		if (slot->curl_result != CURLE_OK ||
		    !alt_req->buffer->len) {

			/* Try reusing the slot to get non-http alternates */
			alt_req->http_specific = 0;
			sprintf(alt_req->url, "%s/objects/info/alternates",
				base);
			curl_easy_setopt(slot->curl, CURLOPT_URL,
					 alt_req->url);
			active_requests++;
			slot->in_use = 1;
			if (slot->finished != NULL)
				(*slot->finished) = 0;
			if (!start_active_slot(slot)) {
				cdata->got_alternates = -1;
				slot->in_use = 0;
				if (slot->finished != NULL)
					(*slot->finished) = 1;
			}
			return;
		}
	} else if (slot->curl_result != CURLE_OK) {
		if (!missing_target(slot)) {
			cdata->got_alternates = -1;
			return;
		}
	}

	fwrite_buffer((char *)&null_byte, 1, 1, alt_req->buffer);
	alt_req->buffer->len--;
	data = alt_req->buffer->buf;

	while (i < alt_req->buffer->len) {
		int posn = i;
		while (posn < alt_req->buffer->len && data[posn] != '\n')
			posn++;
		if (data[posn] == '\n') {
			int okay = 0;
			int serverlen = 0;
			struct alt_base *newalt;
			char *target = NULL;
			if (data[i] == '/') {
				/*
				 * This counts
				 * http://git.host/pub/scm/linux.git/
				 * -----------here^
				 * so memcpy(dst, base, serverlen) will
				 * copy up to "...git.host".
				 */
				const char *colon_ss = strstr(base,"://");
				if (colon_ss) {
					serverlen = (strchr(colon_ss + 3, '/')
						     - base);
					okay = 1;
				}
			} else if (!memcmp(data + i, "../", 3)) {
				/*
				 * Relative URL; chop the corresponding
				 * number of subpath from base (and ../
				 * from data), and concatenate the result.
				 *
				 * The code first drops ../ from data, and
				 * then drops one ../ from data and one path
				 * from base.  IOW, one extra ../ is dropped
				 * from data than path is dropped from base.
				 *
				 * This is not wrong.  The alternate in
				 *     http://git.host/pub/scm/linux.git/
				 * to borrow from
				 *     http://git.host/pub/scm/linus.git/
				 * is ../../linus.git/objects/.  You need
				 * two ../../ to borrow from your direct
				 * neighbour.
				 */
				i += 3;
				serverlen = strlen(base);
				while (i + 2 < posn &&
				       !memcmp(data + i, "../", 3)) {
					do {
						serverlen--;
					} while (serverlen &&
						 base[serverlen - 1] != '/');
					i += 3;
				}
				/* If the server got removed, give up. */
				okay = strchr(base, ':') - base + 3 <
				       serverlen;
			} else if (alt_req->http_specific) {
				char *colon = strchr(data + i, ':');
				char *slash = strchr(data + i, '/');
				if (colon && slash && colon < data + posn &&
				    slash < data + posn && colon < slash) {
					okay = 1;
				}
			}
			/* skip "objects\n" at end */
			if (okay) {
				target = xmalloc(serverlen + posn - i - 6);
				memcpy(target, base, serverlen);
				memcpy(target + serverlen, data + i,
				       posn - i - 7);
				target[serverlen + posn - i - 7] = 0;
				if (walker->get_verbosely)
					fprintf(stderr,
						"Also look at %s\n", target);
				newalt = xmalloc(sizeof(*newalt));
				newalt->next = NULL;
				newalt->base = target;
				newalt->got_indices = 0;
				newalt->packs = NULL;

				while (tail->next != NULL)
					tail = tail->next;
				tail->next = newalt;
			}
		}
		i = posn + 1;
	}

	cdata->got_alternates = 1;
}