repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/mbedtls/library/x509_crt.c
/* * X.509 certificate parsing and verification * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ /* * The ITU-T X.509 standard defines a certificate format for PKI. * * http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs) * http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs) * http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10) * * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf * * [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) #include "mbedtls/x509_crt.h" #include "mbedtls/oid.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_PEM_PARSE_C) #include "mbedtls/pem.h" #endif #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" #include "mbedtls/psa_util.h" #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #include <stdlib.h> #define mbedtls_free free #define mbedtls_calloc calloc #define mbedtls_snprintf snprintf #endif #if defined(MBEDTLS_THREADING_C) #include "mbedtls/threading.h" #endif #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) #include <windows.h> #else #include <time.h> #endif #if defined(MBEDTLS_FS_IO) #include <stdio.h> #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32) #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #endif /* !_WIN32 || EFIX64 || EFI32 */ #endif /* * Item in a verification chain: cert and flags for it */ typedef struct { mbedtls_x509_crt *crt; uint32_t flags; } x509_crt_verify_chain_item; /* * Max size of verification chain: end-entity + intermediates + trusted root */ #define X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 ) /* * Default profile */ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default = { #if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES) /* Allow SHA-1 (weak, but still safe in controlled environments) */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) | #endif /* Only SHA-2 hashes */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ), 0xFFFFFFF, /* Any PK alg */ 0xFFFFFFF, /* Any curve */ 2048, }; /* * Next-default profile */ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next = { /* Hashes from SHA-256 and above */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ), 0xFFFFFFF, /* Any PK alg */ #if defined(MBEDTLS_ECP_C) /* Curves at or above 128-bit security level */ MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ), #else 0, #endif 2048, }; /* * NSA Suite B Profile */ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb = { /* Only SHA-256 and 384 */ MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ), /* Only ECDSA */ MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ), #if defined(MBEDTLS_ECP_C) /* Only NIST P-256 and P-384 */ MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) | MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ), #else 0, #endif 0, }; /* * Check md_alg against profile * Return 0 if md_alg is acceptable for this profile, -1 otherwise */ static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile, mbedtls_md_type_t md_alg ) { if( md_alg == MBEDTLS_MD_NONE ) return( -1 ); if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 ) return( 0 ); return( -1 ); } /* * Check pk_alg against profile * Return 0 if pk_alg is acceptable for this profile, -1 otherwise */ static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile, mbedtls_pk_type_t pk_alg ) { if( pk_alg == MBEDTLS_PK_NONE ) return( -1 ); if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 ) return( 0 ); return( -1 ); } /* * Check key against profile * Return 0 if pk is acceptable for this profile, -1 otherwise */ static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile, const mbedtls_pk_context *pk ) { const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk ); #if defined(MBEDTLS_RSA_C) if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS ) { if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen ) return( 0 ); return( -1 ); } #endif #if defined(MBEDTLS_ECP_C) if( pk_alg == MBEDTLS_PK_ECDSA || pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH ) { const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id; if( gid == MBEDTLS_ECP_DP_NONE ) return( -1 ); if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 ) return( 0 ); return( -1 ); } #endif return( -1 ); } /* * Like memcmp, but case-insensitive and always returns -1 if different */ static int x509_memcasecmp( const void *s1, const void *s2, size_t len ) { size_t i; unsigned char diff; const unsigned char *n1 = s1, *n2 = s2; for( i = 0; i < len; i++ ) { diff = n1[i] ^ n2[i]; if( diff == 0 ) continue; if( diff == 32 && ( ( n1[i] >= 'a' && n1[i] <= 'z' ) || ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) ) { continue; } return( -1 ); } return( 0 ); } /* * Return 0 if name matches wildcard, -1 otherwise */ static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name ) { size_t i; size_t cn_idx = 0, cn_len = strlen( cn ); /* We can't have a match if there is no wildcard to match */ if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' ) return( -1 ); for( i = 0; i < cn_len; ++i ) { if( cn[i] == '.' ) { cn_idx = i; break; } } if( cn_idx == 0 ) return( -1 ); if( cn_len - cn_idx == name->len - 1 && x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 ) { return( 0 ); } return( -1 ); } /* * Compare two X.509 strings, case-insensitive, and allowing for some encoding * variations (but not all). * * Return 0 if equal, -1 otherwise. */ static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b ) { if( a->tag == b->tag && a->len == b->len && memcmp( a->p, b->p, b->len ) == 0 ) { return( 0 ); } if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) && a->len == b->len && x509_memcasecmp( a->p, b->p, b->len ) == 0 ) { return( 0 ); } return( -1 ); } /* * Compare two X.509 Names (aka rdnSequence). * * See RFC 5280 section 7.1, though we don't implement the whole algorithm: * we sometimes return unequal when the full algorithm would return equal, * but never the other way. (In particular, we don't do Unicode normalisation * or space folding.) * * Return 0 if equal, -1 otherwise. */ static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b ) { /* Avoid recursion, it might not be optimised by the compiler */ while( a != NULL || b != NULL ) { if( a == NULL || b == NULL ) return( -1 ); /* type */ if( a->oid.tag != b->oid.tag || a->oid.len != b->oid.len || memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 ) { return( -1 ); } /* value */ if( x509_string_cmp( &a->val, &b->val ) != 0 ) return( -1 ); /* structure of the list of sets */ if( a->next_merged != b->next_merged ) return( -1 ); a = a->next; b = b->next; } /* a == NULL == b */ return( 0 ); } /* * Reset (init or clear) a verify_chain */ static void x509_crt_verify_chain_reset( mbedtls_x509_crt_verify_chain *ver_chain ) { size_t i; for( i = 0; i < MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE; i++ ) { ver_chain->items[i].crt = NULL; ver_chain->items[i].flags = (uint32_t) -1; } ver_chain->len = 0; #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) ver_chain->trust_ca_cb_result = NULL; #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ } /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } */ static int x509_get_version( unsigned char **p, const unsigned char *end, int *ver ) { int ret; size_t len; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) { *ver = 0; return( 0 ); } return( ret ); } end = *p + len; if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_VERSION + ret ); if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_VERSION + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * Validity ::= SEQUENCE { * notBefore Time, * notAfter Time } */ static int x509_get_dates( unsigned char **p, const unsigned char *end, mbedtls_x509_time *from, mbedtls_x509_time *to ) { int ret; size_t len; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_DATE + ret ); end = *p + len; if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 ) return( ret ); if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 ) return( ret ); if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_DATE + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * X.509 v2/v3 unique identifier (not parsed) */ static int x509_get_uid( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *uid, int n ) { int ret; if( *p == end ) return( 0 ); uid->tag = **p; if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( 0 ); return( ret ); } uid->p = *p; *p += uid->len; return( 0 ); } static int x509_get_basic_constraints( unsigned char **p, const unsigned char *end, int *ca_istrue, int *max_pathlen ) { int ret; size_t len; /* * BasicConstraints ::= SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL } */ *ca_istrue = 0; /* DEFAULT FALSE */ *max_pathlen = 0; /* endless */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) ret = mbedtls_asn1_get_int( p, end, ca_istrue ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *ca_istrue != 0 ) *ca_istrue = 1; } if( *p == end ) return( 0 ); if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); (*max_pathlen)++; return( 0 ); } static int x509_get_ns_cert_type( unsigned char **p, const unsigned char *end, unsigned char *ns_cert_type) { int ret; mbedtls_x509_bitstring bs = { 0, 0, NULL }; if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( bs.len != 1 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); /* Get actual bitstring */ *ns_cert_type = *bs.p; return( 0 ); } static int x509_get_key_usage( unsigned char **p, const unsigned char *end, unsigned int *key_usage) { int ret; size_t i; mbedtls_x509_bitstring bs = { 0, 0, NULL }; if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( bs.len < 1 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); /* Get actual bitstring */ *key_usage = 0; for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ ) { *key_usage |= (unsigned int) bs.p[i] << (8*i); } return( 0 ); } /* * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId * * KeyPurposeId ::= OBJECT IDENTIFIER */ static int x509_get_ext_key_usage( unsigned char **p, const unsigned char *end, mbedtls_x509_sequence *ext_key_usage) { int ret; if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); /* Sequence length must be >= 1 */ if( ext_key_usage->buf.p == NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_INVALID_LENGTH ); return( 0 ); } /* * SubjectAltName ::= GeneralNames * * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName * * GeneralName ::= CHOICE { * otherName [0] OtherName, * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, * directoryName [4] Name, * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER } * * OtherName ::= SEQUENCE { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } * * EDIPartyName ::= SEQUENCE { * nameAssigner [0] DirectoryString OPTIONAL, * partyName [1] DirectoryString } * * NOTE: we list all types, but only use dNSName and otherName * of type HwModuleName, as defined in RFC 4108, at this point. */ static int x509_get_subject_alt_name( unsigned char **p, const unsigned char *end, mbedtls_x509_sequence *subject_alt_name ) { int ret; size_t len, tag_len; mbedtls_asn1_buf *buf; unsigned char tag; mbedtls_asn1_sequence *cur = subject_alt_name; /* Get main sequence tag */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p + len != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); while( *p < end ) { mbedtls_x509_subject_alternative_name dummy_san_buf; memset( &dummy_san_buf, 0, sizeof( dummy_san_buf ) ); if( ( end - *p ) < 1 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_OUT_OF_DATA ); tag = **p; (*p)++; if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) != MBEDTLS_ASN1_CONTEXT_SPECIFIC ) { return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); } /* * Check that the SAN are structured correct. */ ret = mbedtls_x509_parse_subject_alt_name( &(cur->buf), &dummy_san_buf ); /* * In case the extension is malformed, return an error, * and clear the allocated sequences. */ if( ret != 0 && ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ) { mbedtls_x509_sequence *seq_cur = subject_alt_name->next; mbedtls_x509_sequence *seq_prv; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } subject_alt_name->next = NULL; return( ret ); } /* Allocate and assign next pointer */ if( cur->buf.p != NULL ) { if( cur->next != NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS ); cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_ALLOC_FAILED ); cur = cur->next; } buf = &(cur->buf); buf->tag = tag; buf->p = *p; buf->len = tag_len; *p += buf->len; } /* Set final sequence entry's next pointer to NULL */ cur->next = NULL; if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } * * anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 } * * certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation * * PolicyInformation ::= SEQUENCE { * policyIdentifier CertPolicyId, * policyQualifiers SEQUENCE SIZE (1..MAX) OF * PolicyQualifierInfo OPTIONAL } * * CertPolicyId ::= OBJECT IDENTIFIER * * PolicyQualifierInfo ::= SEQUENCE { * policyQualifierId PolicyQualifierId, * qualifier ANY DEFINED BY policyQualifierId } * * -- policyQualifierIds for Internet policy qualifiers * * id-qt OBJECT IDENTIFIER ::= { id-pkix 2 } * id-qt-cps OBJECT IDENTIFIER ::= { id-qt 1 } * id-qt-unotice OBJECT IDENTIFIER ::= { id-qt 2 } * * PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice ) * * Qualifier ::= CHOICE { * cPSuri CPSuri, * userNotice UserNotice } * * CPSuri ::= IA5String * * UserNotice ::= SEQUENCE { * noticeRef NoticeReference OPTIONAL, * explicitText DisplayText OPTIONAL } * * NoticeReference ::= SEQUENCE { * organization DisplayText, * noticeNumbers SEQUENCE OF INTEGER } * * DisplayText ::= CHOICE { * ia5String IA5String (SIZE (1..200)), * visibleString VisibleString (SIZE (1..200)), * bmpString BMPString (SIZE (1..200)), * utf8String UTF8String (SIZE (1..200)) } * * NOTE: we only parse and use anyPolicy without qualifiers at this point * as defined in RFC 5280. */ static int x509_get_certificate_policies( unsigned char **p, const unsigned char *end, mbedtls_x509_sequence *certificate_policies ) { int ret, parse_ret = 0; size_t len; mbedtls_asn1_buf *buf; mbedtls_asn1_sequence *cur = certificate_policies; /* Get main sequence tag */ ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ); if( ret != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( *p + len != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* * Cannot be an empty sequence. */ if( len == 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); while( *p < end ) { mbedtls_x509_buf policy_oid; const unsigned char *policy_end; /* * Get the policy sequence */ if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); policy_end = *p + len; if( ( ret = mbedtls_asn1_get_tag( p, policy_end, &len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); policy_oid.tag = MBEDTLS_ASN1_OID; policy_oid.len = len; policy_oid.p = *p; /* * Only AnyPolicy is currently supported when enforcing policy. */ if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_POLICY, &policy_oid ) != 0 ) { /* * Set the parsing return code but continue parsing, in case this * extension is critical and MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION * is configured. */ parse_ret = MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE; } /* Allocate and assign next pointer */ if( cur->buf.p != NULL ) { if( cur->next != NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS ); cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) ); if( cur->next == NULL ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_ALLOC_FAILED ); cur = cur->next; } buf = &( cur->buf ); buf->tag = policy_oid.tag; buf->p = policy_oid.p; buf->len = policy_oid.len; *p += len; /* * If there is an optional qualifier, then *p < policy_end * Check the Qualifier len to verify it doesn't exceed policy_end. */ if( *p < policy_end ) { if( ( ret = mbedtls_asn1_get_tag( p, policy_end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); /* * Skip the optional policy qualifiers. */ *p += len; } if( *p != policy_end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } /* Set final sequence entry's next pointer to NULL */ cur->next = NULL; if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( parse_ret ); } /* * X.509 v3 extensions * */ static int x509_get_crt_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_crt *crt ) { int ret; size_t len; unsigned char *end_ext_data, *end_ext_octet; if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 ) { if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) return( 0 ); return( ret ); } while( *p < end ) { /* * Extension ::= SEQUENCE { * extnID OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING } */ mbedtls_x509_buf extn_oid = {0, 0, NULL}; int is_critical = 0; /* DEFAULT FALSE */ int ext_type = 0; if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); end_ext_data = *p + len; /* Get extension ID */ if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); extn_oid.tag = MBEDTLS_ASN1_OID; extn_oid.p = *p; *p += extn_oid.len; /* Get optional critical */ if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 && ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); /* Data should be octet string type */ if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); end_ext_octet = *p + len; if( end_ext_octet != end_ext_data ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); /* * Detect supported extensions */ ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type ); if( ret != 0 ) { /* No parser found, skip extension */ *p = end_ext_octet; #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) if( is_critical ) { /* Data is marked as critical: fail */ return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ); } #endif continue; } /* Forbid repeated extensions */ if( ( crt->ext_types & ext_type ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS ); crt->ext_types |= ext_type; switch( ext_type ) { case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS: /* Parse basic constraints */ if( ( ret = x509_get_basic_constraints( p, end_ext_octet, &crt->ca_istrue, &crt->max_pathlen ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_KEY_USAGE: /* Parse key usage */ if( ( ret = x509_get_key_usage( p, end_ext_octet, &crt->key_usage ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE: /* Parse extended key usage */ if( ( ret = x509_get_ext_key_usage( p, end_ext_octet, &crt->ext_key_usage ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME: /* Parse subject alt name */ if( ( ret = x509_get_subject_alt_name( p, end_ext_octet, &crt->subject_alt_names ) ) != 0 ) return( ret ); break; case MBEDTLS_X509_EXT_NS_CERT_TYPE: /* Parse netscape certificate type */ if( ( ret = x509_get_ns_cert_type( p, end_ext_octet, &crt->ns_cert_type ) ) != 0 ) return( ret ); break; case MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES: /* Parse certificate policies type */ if( ( ret = x509_get_certificate_policies( p, end_ext_octet, &crt->certificate_policies ) ) != 0 ) { #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) if( is_critical ) return( ret ); else #endif /* * If MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE is returned, then we * cannot interpret or enforce the policy. However, it is up to * the user to choose how to enforce the policies, * unless the extension is critical. */ if( ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ) return( ret ); } break; default: /* * If this is a non-critical extension, which the oid layer * supports, but there isn't an x509 parser for it, * skip the extension. */ #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION) if( is_critical ) return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ); else #endif *p = end_ext_octet; } } if( *p != end ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); return( 0 ); } /* * Parse and fill a single X.509 certificate in DER format */ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf, size_t buflen, int make_copy ) { int ret; size_t len; unsigned char *p, *end, *crt_end; mbedtls_x509_buf sig_params1, sig_params2, sig_oid2; memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) ); memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) ); memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) ); /* * Check for valid input */ if( crt == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); /* Use the original buffer until we figure out actual length. */ p = (unsigned char*) buf; len = buflen; end = p + len; /* * Certificate ::= SEQUENCE { * tbsCertificate TBSCertificate, * signatureAlgorithm AlgorithmIdentifier, * signatureValue BIT STRING } */ if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT ); } end = crt_end = p + len; crt->raw.len = crt_end - buf; if( make_copy != 0 ) { /* Create and populate a new buffer for the raw field. */ crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len ); if( crt->raw.p == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); memcpy( crt->raw.p, buf, crt->raw.len ); crt->own_buffer = 1; p += crt->raw.len - len; end = crt_end = p + len; } else { crt->raw.p = (unsigned char*) buf; crt->own_buffer = 0; } /* * TBSCertificate ::= SEQUENCE { */ crt->tbs.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } end = p + len; crt->tbs.len = end - crt->tbs.p; /* * Version ::= INTEGER { v1(0), v2(1), v3(2) } * * CertificateSerialNumber ::= INTEGER * * signature AlgorithmIdentifier */ if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 || ( ret = mbedtls_x509_get_serial( &p, end, &crt->serial ) ) != 0 || ( ret = mbedtls_x509_get_alg( &p, end, &crt->sig_oid, &sig_params1 ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } if( crt->version < 0 || crt->version > 2 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); } crt->version++; if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1, &crt->sig_md, &crt->sig_pk, &crt->sig_opts ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } /* * issuer Name */ crt->issuer_raw.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } crt->issuer_raw.len = p - crt->issuer_raw.p; /* * Validity ::= SEQUENCE { * notBefore Time, * notAfter Time } * */ if( ( ret = x509_get_dates( &p, end, &crt->valid_from, &crt->valid_to ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } /* * subject Name */ crt->subject_raw.p = p; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret ); } if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } crt->subject_raw.len = p - crt->subject_raw.p; /* * SubjectPublicKeyInfo */ crt->pk_raw.p = p; if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } crt->pk_raw.len = p - crt->pk_raw.p; /* * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version shall be v2 or v3 * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, * -- If present, version shall be v2 or v3 * extensions [3] EXPLICIT Extensions OPTIONAL * -- If present, version shall be v3 */ if( crt->version == 2 || crt->version == 3 ) { ret = x509_get_uid( &p, end, &crt->issuer_id, 1 ); if( ret != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } } if( crt->version == 2 || crt->version == 3 ) { ret = x509_get_uid( &p, end, &crt->subject_id, 2 ); if( ret != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } } #if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3) if( crt->version == 3 ) #endif { ret = x509_get_crt_ext( &p, end, crt ); if( ret != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } } if( p != end ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } end = crt_end; /* * } * -- end of TBSCertificate * * signatureAlgorithm AlgorithmIdentifier, * signatureValue BIT STRING */ if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } if( crt->sig_oid.len != sig_oid2.len || memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 || sig_params1.len != sig_params2.len || ( sig_params1.len != 0 && memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_SIG_MISMATCH ); } if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 ) { mbedtls_x509_crt_free( crt ); return( ret ); } if( p != end ) { mbedtls_x509_crt_free( crt ); return( MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } return( 0 ); } /* * Parse one X.509 certificate in DER format from a buffer and add them to a * chained list */ static int mbedtls_x509_crt_parse_der_internal( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen, int make_copy ) { int ret; mbedtls_x509_crt *crt = chain, *prev = NULL; /* * Check for valid input */ if( crt == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); while( crt->version != 0 && crt->next != NULL ) { prev = crt; crt = crt->next; } /* * Add new certificate on the end of the chain if needed. */ if( crt->version != 0 && crt->next == NULL ) { crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ); if( crt->next == NULL ) return( MBEDTLS_ERR_X509_ALLOC_FAILED ); prev = crt; mbedtls_x509_crt_init( crt->next ); crt = crt->next; } if( ( ret = x509_crt_parse_der_core( crt, buf, buflen, make_copy ) ) != 0 ) { if( prev ) prev->next = NULL; if( crt != chain ) mbedtls_free( crt ); return( ret ); } return( 0 ); } int mbedtls_x509_crt_parse_der_nocopy( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 0 ) ); } int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { return( mbedtls_x509_crt_parse_der_internal( chain, buf, buflen, 1 ) ); } /* * Parse one or more PEM certificates from a buffer and add them to the chained * list */ int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ) { #if defined(MBEDTLS_PEM_PARSE_C) int success = 0, first_error = 0, total_failed = 0; int buf_format = MBEDTLS_X509_FORMAT_DER; #endif /* * Check for valid input */ if( chain == NULL || buf == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); /* * Determine buffer content. Buffer contains either one DER certificate or * one or more PEM certificates. */ #if defined(MBEDTLS_PEM_PARSE_C) if( buflen != 0 && buf[buflen - 1] == '\0' && strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL ) { buf_format = MBEDTLS_X509_FORMAT_PEM; } if( buf_format == MBEDTLS_X509_FORMAT_DER ) return mbedtls_x509_crt_parse_der( chain, buf, buflen ); #else return mbedtls_x509_crt_parse_der( chain, buf, buflen ); #endif #if defined(MBEDTLS_PEM_PARSE_C) if( buf_format == MBEDTLS_X509_FORMAT_PEM ) { int ret; mbedtls_pem_context pem; /* 1 rather than 0 since the terminating NULL byte is counted in */ while( buflen > 1 ) { size_t use_len; mbedtls_pem_init( &pem ); /* If we get there, we know the string is null-terminated */ ret = mbedtls_pem_read_buffer( &pem, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----", buf, NULL, 0, &use_len ); if( ret == 0 ) { /* * Was PEM encoded */ buflen -= use_len; buf += use_len; } else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA ) { return( ret ); } else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT ) { mbedtls_pem_free( &pem ); /* * PEM header and footer were found */ buflen -= use_len; buf += use_len; if( first_error == 0 ) first_error = ret; total_failed++; continue; } else break; ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen ); mbedtls_pem_free( &pem ); if( ret != 0 ) { /* * Quit parsing on a memory error */ if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED ) return( ret ); if( first_error == 0 ) first_error = ret; total_failed++; continue; } success = 1; } } if( success ) return( total_failed ); else if( first_error ) return( first_error ); else return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT ); #endif /* MBEDTLS_PEM_PARSE_C */ } #if defined(MBEDTLS_FS_IO) /* * Load one or more certificates and add them to the chained list */ int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path ) { int ret; size_t n; unsigned char *buf; if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 ) return( ret ); ret = mbedtls_x509_crt_parse( chain, buf, n ); mbedtls_platform_zeroize( buf, n ); mbedtls_free( buf ); return( ret ); } int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ) { int ret = 0; #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) int w_ret; WCHAR szDir[MAX_PATH]; char filename[MAX_PATH]; char *p; size_t len = strlen( path ); WIN32_FIND_DATAW file_data; HANDLE hFind; if( len > MAX_PATH - 3 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); memset( szDir, 0, sizeof(szDir) ); memset( filename, 0, MAX_PATH ); memcpy( filename, path, len ); filename[len++] = '\\'; p = filename + len; filename[len++] = '*'; w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir, MAX_PATH - 3 ); if( w_ret == 0 ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); hFind = FindFirstFileW( szDir, &file_data ); if( hFind == INVALID_HANDLE_VALUE ) return( MBEDTLS_ERR_X509_FILE_IO_ERROR ); len = MAX_PATH - len; do { memset( p, 0, len ); if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue; w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName, lstrlenW( file_data.cFileName ), p, (int) len - 1, NULL, NULL ); if( w_ret == 0 ) { ret = MBEDTLS_ERR_X509_FILE_IO_ERROR; goto cleanup; } w_ret = mbedtls_x509_crt_parse_file( chain, filename ); if( w_ret < 0 ) ret++; else ret += w_ret; } while( FindNextFileW( hFind, &file_data ) != 0 ); if( GetLastError() != ERROR_NO_MORE_FILES ) ret = MBEDTLS_ERR_X509_FILE_IO_ERROR; cleanup: FindClose( hFind ); #else /* _WIN32 */ int t_ret; int snp_ret; struct stat sb; struct dirent *entry; char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN]; DIR *dir = opendir( path ); if( dir == NULL ) return( MBEDTLS_ERR_X509_FILE_IO_ERROR ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 ) { closedir( dir ); return( ret ); } #endif /* MBEDTLS_THREADING_C */ while( ( entry = readdir( dir ) ) != NULL ) { snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name, "%s/%s", path, entry->d_name ); if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name ) { ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL; goto cleanup; } else if( stat( entry_name, &sb ) == -1 ) { ret = MBEDTLS_ERR_X509_FILE_IO_ERROR; goto cleanup; } if( !S_ISREG( sb.st_mode ) ) continue; // Ignore parse errors // t_ret = mbedtls_x509_crt_parse_file( chain, entry_name ); if( t_ret < 0 ) ret++; else ret += t_ret; } cleanup: closedir( dir ); #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 ) ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR; #endif /* MBEDTLS_THREADING_C */ #endif /* _WIN32 */ return( ret ); } #endif /* MBEDTLS_FS_IO */ /* * OtherName ::= SEQUENCE { * type-id OBJECT IDENTIFIER, * value [0] EXPLICIT ANY DEFINED BY type-id } * * HardwareModuleName ::= SEQUENCE { * hwType OBJECT IDENTIFIER, * hwSerialNum OCTET STRING } * * NOTE: we currently only parse and use otherName of type HwModuleName, * as defined in RFC 4108. */ static int x509_get_other_name( const mbedtls_x509_buf *subject_alt_name, mbedtls_x509_san_other_name *other_name ) { int ret = 0; size_t len; unsigned char *p = subject_alt_name->p; const unsigned char *end = p + subject_alt_name->len; mbedtls_x509_buf cur_oid; if( ( subject_alt_name->tag & ( MBEDTLS_ASN1_TAG_CLASS_MASK | MBEDTLS_ASN1_TAG_VALUE_MASK ) ) != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME ) ) { /* * The given subject alternative name is not of type "othername". */ return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); } if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); cur_oid.tag = MBEDTLS_ASN1_OID; cur_oid.p = p; cur_oid.len = len; /* * Only HwModuleName is currently supported. */ if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME, &cur_oid ) != 0 ) { return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ); } if( p + len >= end ) { mbedtls_platform_zeroize( other_name, sizeof( other_name ) ); return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } p += len; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OID ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); other_name->value.hardware_module_name.oid.tag = MBEDTLS_ASN1_OID; other_name->value.hardware_module_name.oid.p = p; other_name->value.hardware_module_name.oid.len = len; if( p + len >= end ) { mbedtls_platform_zeroize( other_name, sizeof( other_name ) ); return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } p += len; if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret ); other_name->value.hardware_module_name.val.tag = MBEDTLS_ASN1_OCTET_STRING; other_name->value.hardware_module_name.val.p = p; other_name->value.hardware_module_name.val.len = len; p += len; if( p != end ) { mbedtls_platform_zeroize( other_name, sizeof( other_name ) ); return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); } return( 0 ); } static int x509_info_subject_alt_name( char **buf, size_t *size, const mbedtls_x509_sequence *subject_alt_name, const char *prefix ) { int ret; size_t n = *size; char *p = *buf; const mbedtls_x509_sequence *cur = subject_alt_name; mbedtls_x509_subject_alternative_name san; int parse_ret; while( cur != NULL ) { memset( &san, 0, sizeof( san ) ); parse_ret = mbedtls_x509_parse_subject_alt_name( &cur->buf, &san ); if( parse_ret != 0 ) { if( parse_ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ) { ret = mbedtls_snprintf( p, n, "\n%s <unsupported>", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; } else { ret = mbedtls_snprintf( p, n, "\n%s <malformed>", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; } cur = cur->next; continue; } switch( san.type ) { /* * otherName */ case MBEDTLS_X509_SAN_OTHER_NAME: { mbedtls_x509_san_other_name *other_name = &san.san.other_name; ret = mbedtls_snprintf( p, n, "\n%s otherName :", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( MBEDTLS_OID_CMP( MBEDTLS_OID_ON_HW_MODULE_NAME, &other_name->value.hardware_module_name.oid ) != 0 ) { ret = mbedtls_snprintf( p, n, "\n%s hardware module name :", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%s hardware type : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_oid_get_numeric_string( p, n, &other_name->value.hardware_module_name.oid ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%s hardware serial number : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( other_name->value.hardware_module_name.val.len >= n ) { *p = '\0'; return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL ); } memcpy( p, other_name->value.hardware_module_name.val.p, other_name->value.hardware_module_name.val.len ); p += other_name->value.hardware_module_name.val.len; n -= other_name->value.hardware_module_name.val.len; }/* MBEDTLS_OID_ON_HW_MODULE_NAME */ } break; /* * dNSName */ case MBEDTLS_X509_SAN_DNS_NAME: { ret = mbedtls_snprintf( p, n, "\n%s dNSName : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( san.san.unstructured_name.len >= n ) { *p = '\0'; return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL ); } memcpy( p, san.san.unstructured_name.p, san.san.unstructured_name.len ); p += san.san.unstructured_name.len; n -= san.san.unstructured_name.len; } break; /* * Type not supported, skip item. */ default: ret = mbedtls_snprintf( p, n, "\n%s <unsupported>", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; break; } cur = cur->next; } *p = '\0'; *size = n; *buf = p; return( 0 ); } int mbedtls_x509_parse_subject_alt_name( const mbedtls_x509_buf *san_buf, mbedtls_x509_subject_alternative_name *san ) { int ret; switch( san_buf->tag & ( MBEDTLS_ASN1_TAG_CLASS_MASK | MBEDTLS_ASN1_TAG_VALUE_MASK ) ) { /* * otherName */ case( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME ): { mbedtls_x509_san_other_name other_name; ret = x509_get_other_name( san_buf, &other_name ); if( ret != 0 ) return( ret ); memset( san, 0, sizeof( mbedtls_x509_subject_alternative_name ) ); san->type = MBEDTLS_X509_SAN_OTHER_NAME; memcpy( &san->san.other_name, &other_name, sizeof( other_name ) ); } break; /* * dNSName */ case( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_DNS_NAME ): { memset( san, 0, sizeof( mbedtls_x509_subject_alternative_name ) ); san->type = MBEDTLS_X509_SAN_DNS_NAME; memcpy( &san->san.unstructured_name, san_buf, sizeof( *san_buf ) ); } break; /* * Type not supported */ default: return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE ); } return( 0 ); } #define PRINT_ITEM(i) \ { \ ret = mbedtls_snprintf( p, n, "%s" i, sep ); \ MBEDTLS_X509_SAFE_SNPRINTF; \ sep = ", "; \ } #define CERT_TYPE(type,name) \ if( ns_cert_type & (type) ) \ PRINT_ITEM( name ); static int x509_info_cert_type( char **buf, size_t *size, unsigned char ns_cert_type ) { int ret; size_t n = *size; char *p = *buf; const char *sep = ""; CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT, "SSL Client" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER, "SSL Server" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL, "Email" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING, "Object Signing" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED, "Reserved" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA, "SSL CA" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA, "Email CA" ); CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA, "Object Signing CA" ); *size = n; *buf = p; return( 0 ); } #define KEY_USAGE(code,name) \ if( key_usage & (code) ) \ PRINT_ITEM( name ); static int x509_info_key_usage( char **buf, size_t *size, unsigned int key_usage ) { int ret; size_t n = *size; char *p = *buf; const char *sep = ""; KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE, "Digital Signature" ); KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION, "Non Repudiation" ); KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT, "Key Encipherment" ); KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT, "Data Encipherment" ); KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT, "Key Agreement" ); KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN, "Key Cert Sign" ); KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN, "CRL Sign" ); KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY, "Encipher Only" ); KEY_USAGE( MB<KEY>_DECIPHER_ONLY, "Decipher Only" ); *size = n; *buf = p; return( 0 ); } static int x509_info_ext_key_usage( char **buf, size_t *size, const mbedtls_x509_sequence *extended_key_usage ) { int ret; const char *desc; size_t n = *size; char *p = *buf; const mbedtls_x509_sequence *cur = extended_key_usage; const char *sep = ""; while( cur != NULL ) { if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 ) desc = "???"; ret = mbedtls_snprintf( p, n, "%s%s", sep, desc ); MBEDTLS_X509_SAFE_SNPRINTF; sep = ", "; cur = cur->next; } *size = n; *buf = p; return( 0 ); } static int x509_info_cert_policies( char **buf, size_t *size, const mbedtls_x509_sequence *certificate_policies ) { int ret; const char *desc; size_t n = *size; char *p = *buf; const mbedtls_x509_sequence *cur = certificate_policies; const char *sep = ""; while( cur != NULL ) { if( mbedtls_oid_get_certificate_policies( &cur->buf, &desc ) != 0 ) desc = "???"; ret = mbedtls_snprintf( p, n, "%s%s", sep, desc ); MBEDTLS_X509_SAFE_SNPRINTF; sep = ", "; cur = cur->next; } *size = n; *buf = p; return( 0 ); } /* * Return an informational string about the certificate. */ #define BEFORE_COLON 18 #define BC "18" int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix, const mbedtls_x509_crt *crt ) { int ret; size_t n; char *p; char key_size_str[BEFORE_COLON]; p = buf; n = size; if( NULL == crt ) { ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int) ( size - n ) ); } ret = mbedtls_snprintf( p, n, "%scert. version : %d\n", prefix, crt->version ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "%sserial number : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_serial_gets( p, n, &crt->serial ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets( p, n, &crt->issuer ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_dn_gets( p, n, &crt->subject ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sissued on : " \ "%04d-%02d-%02d %02d:%02d:%02d", prefix, crt->valid_from.year, crt->valid_from.mon, crt->valid_from.day, crt->valid_from.hour, crt->valid_from.min, crt->valid_from.sec ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%sexpires on : " \ "%04d-%02d-%02d %02d:%02d:%02d", prefix, crt->valid_to.year, crt->valid_to.mon, crt->valid_to.day, crt->valid_to.hour, crt->valid_to.min, crt->valid_to.sec ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk, crt->sig_md, crt->sig_opts ); MBEDTLS_X509_SAFE_SNPRINTF; /* Key size */ if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON, mbedtls_pk_get_name( &crt->pk ) ) ) != 0 ) { return( ret ); } ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str, (int) mbedtls_pk_get_bitlen( &crt->pk ) ); MBEDTLS_X509_SAFE_SNPRINTF; /* * Optional extensions */ if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS ) { ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix, crt->ca_istrue ? "true" : "false" ); MBEDTLS_X509_SAFE_SNPRINTF; if( crt->max_pathlen > 0 ) { ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 ); MBEDTLS_X509_SAFE_SNPRINTF; } } if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { ret = mbedtls_snprintf( p, n, "\n%ssubject alt name :", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_subject_alt_name( &p, &n, &crt->subject_alt_names, prefix ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE ) { ret = mbedtls_snprintf( p, n, "\n%scert. type : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) { ret = mbedtls_snprintf( p, n, "\n%skey usage : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) { ret = mbedtls_snprintf( p, n, "\n%sext key usage : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_ext_key_usage( &p, &n, &crt->ext_key_usage ) ) != 0 ) return( ret ); } if( crt->ext_types & MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES ) { ret = mbedtls_snprintf( p, n, "\n%scertificate policies : ", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; if( ( ret = x509_info_cert_policies( &p, &n, &crt->certificate_policies ) ) != 0 ) return( ret ); } ret = mbedtls_snprintf( p, n, "\n" ); MBEDTLS_X509_SAFE_SNPRINTF; return( (int) ( size - n ) ); } struct x509_crt_verify_string { int code; const char *string; }; static const struct x509_crt_verify_string x509_crt_verify_strings[] = { { MBEDTLS_X509_BADCERT_EXPIRED, "The certificate validity has expired" }, { MBEDTLS_X509_BADCERT_REVOKED, "The certificate has been revoked (is on a CRL)" }, { MBEDTLS_X509_BADCERT_CN_MISMATCH, "The certificate Common Name (CN) does not match with the expected CN" }, { MBEDTLS_X509_BADCERT_NOT_TRUSTED, "The certificate is not correctly signed by the trusted CA" }, { MBEDTLS_X509_BADCRL_NOT_TRUSTED, "The CRL is not correctly signed by the trusted CA" }, { MBEDTLS_X509_BADCRL_EXPIRED, "The CRL is expired" }, { MBEDTLS_X509_BADCERT_MISSING, "Certificate was missing" }, { MBEDTLS_X509_BADCERT_SKIP_VERIFY, "Certificate verification was skipped" }, { MBEDTLS_X509_BADCERT_OTHER, "Other reason (can be used by verify callback)" }, { MBEDTLS_X509_BADCERT_FUTURE, "The certificate validity starts in the future" }, { MBEDTLS_X509_BADCRL_FUTURE, "The CRL is from the future" }, { MBEDTLS_X509_BADCERT_KEY_USAGE, "Usage does not match the keyUsage extension" }, { MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" }, { MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "Usage does not match the nsCertType extension" }, { MBEDTLS_X509_BADCERT_BAD_MD, "The certificate is signed with an unacceptable hash." }, { MBEDTLS_X509_BADCERT_BAD_PK, "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." }, { MBEDTLS_X509_BADCERT_BAD_KEY, "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." }, { MBEDTLS_X509_BADCRL_BAD_MD, "The CRL is signed with an unacceptable hash." }, { MBEDTLS_X509_BADCRL_BAD_PK, "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." }, { MBEDTLS_X509_BADCRL_BAD_KEY, "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." }, { 0, NULL } }; int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix, uint32_t flags ) { int ret; const struct x509_crt_verify_string *cur; char *p = buf; size_t n = size; for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ ) { if( ( flags & cur->code ) == 0 ) continue; ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string ); MBEDTLS_X509_SAFE_SNPRINTF; flags ^= cur->code; } if( flags != 0 ) { ret = mbedtls_snprintf( p, n, "%sUnknown reason " "(this should not happen)\n", prefix ); MBEDTLS_X509_SAFE_SNPRINTF; } return( (int) ( size - n ) ); } #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt, unsigned int usage ) { unsigned int usage_must, usage_may; unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY | MBEDTLS_X509_KU_DECIPHER_ONLY; if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 ) return( 0 ); usage_must = usage & ~may_mask; if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); usage_may = usage & may_mask; if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); return( 0 ); } #endif #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt, const char *usage_oid, size_t usage_len ) { const mbedtls_x509_sequence *cur; /* Extension is not mandatory, absent means no restriction */ if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 ) return( 0 ); /* * Look for the requested usage (or wildcard ANY) in our list */ for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next ) { const mbedtls_x509_buf *cur_oid = &cur->buf; if( cur_oid->len == usage_len && memcmp( cur_oid->p, usage_oid, usage_len ) == 0 ) { return( 0 ); } if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 ) return( 0 ); } return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); } #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ #if defined(MBEDTLS_X509_CRL_PARSE_C) /* * Return 1 if the certificate is revoked, or 0 otherwise. */ int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl ) { const mbedtls_x509_crl_entry *cur = &crl->entry; while( cur != NULL && cur->serial.len != 0 ) { if( crt->serial.len == cur->serial.len && memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 ) { if( mbedtls_x509_time_is_past( &cur->revocation_date ) ) return( 1 ); } cur = cur->next; } return( 0 ); } /* * Check that the given certificate is not revoked according to the CRL. * Skip validation if no CRL for the given CA is present. */ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca, mbedtls_x509_crl *crl_list, const mbedtls_x509_crt_profile *profile ) { int flags = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; const mbedtls_md_info_t *md_info; if( ca == NULL ) return( flags ); while( crl_list != NULL ) { if( crl_list->version == 0 || x509_name_cmp( &crl_list->issuer, &ca->subject ) != 0 ) { crl_list = crl_list->next; continue; } /* * Check if the CA is configured to sign CRLs */ #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 ) { flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; } #endif /* * Check if CRL is correctly signed by the trusted CA */ if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 ) flags |= MBEDTLS_X509_BADCRL_BAD_MD; if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 ) flags |= MBEDTLS_X509_BADCRL_BAD_PK; md_info = mbedtls_md_info_from_type( crl_list->sig_md ); if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 ) { /* Note: this can't happen except after an internal error */ flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; } if( x509_profile_check_key( profile, &ca->pk ) != 0 ) flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk, crl_list->sig_md, hash, mbedtls_md_get_size( md_info ), crl_list->sig.p, crl_list->sig.len ) != 0 ) { flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED; break; } /* * Check for validity of CRL (Do not drop out) */ if( mbedtls_x509_time_is_past( &crl_list->next_update ) ) flags |= MBEDTLS_X509_BADCRL_EXPIRED; if( mbedtls_x509_time_is_future( &crl_list->this_update ) ) flags |= MBEDTLS_X509_BADCRL_FUTURE; /* * Check if certificate is revoked */ if( mbedtls_x509_crt_is_revoked( crt, crl_list ) ) { flags |= MBEDTLS_X509_BADCERT_REVOKED; break; } crl_list = crl_list->next; } return( flags ); } #endif /* MBEDTLS_X509_CRL_PARSE_C */ /* * Check the signature of a certificate by its parent */ static int x509_crt_check_signature( const mbedtls_x509_crt *child, mbedtls_x509_crt *parent, mbedtls_x509_crt_restart_ctx *rs_ctx ) { unsigned char hash[MBEDTLS_MD_MAX_SIZE]; size_t hash_len; #if !defined(MBEDTLS_USE_PSA_CRYPTO) const mbedtls_md_info_t *md_info; md_info = mbedtls_md_info_from_type( child->sig_md ); hash_len = mbedtls_md_get_size( md_info ); /* Note: hash errors can happen only after an internal error */ if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 ) return( -1 ); #else psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT; psa_algorithm_t hash_alg = mbedtls_psa_translate_md( child->sig_md ); if( psa_hash_setup( &hash_operation, hash_alg ) != PSA_SUCCESS ) return( -1 ); if( psa_hash_update( &hash_operation, child->tbs.p, child->tbs.len ) != PSA_SUCCESS ) { return( -1 ); } if( psa_hash_finish( &hash_operation, hash, sizeof( hash ), &hash_len ) != PSA_SUCCESS ) { return( -1 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* Skip expensive computation on obvious mismatch */ if( ! mbedtls_pk_can_do( &parent->pk, child->sig_pk ) ) return( -1 ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && child->sig_pk == MBEDTLS_PK_ECDSA ) { return( mbedtls_pk_verify_restartable( &parent->pk, child->sig_md, hash, hash_len, child->sig.p, child->sig.len, &rs_ctx->pk ) ); } #else (void) rs_ctx; #endif return( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, child->sig_md, hash, hash_len, child->sig.p, child->sig.len ) ); } /* * Check if 'parent' is a suitable parent (signing CA) for 'child'. * Return 0 if yes, -1 if not. * * top means parent is a locally-trusted certificate */ static int x509_crt_check_parent( const mbedtls_x509_crt *child, const mbedtls_x509_crt *parent, int top ) { int need_ca_bit; /* Parent must be the issuer */ if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 ) return( -1 ); /* Parent must have the basicConstraints CA bit set as a general rule */ need_ca_bit = 1; /* Exception: v1/v2 certificates that are locally trusted. */ if( top && parent->version < 3 ) need_ca_bit = 0; if( need_ca_bit && ! parent->ca_istrue ) return( -1 ); #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) if( need_ca_bit && mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 ) { return( -1 ); } #endif return( 0 ); } /* * Find a suitable parent for child in candidates, or return NULL. * * Here suitable is defined as: * 1. subject name matches child's issuer * 2. if necessary, the CA bit is set and key usage allows signing certs * 3. for trusted roots, the signature is correct * (for intermediates, the signature is checked and the result reported) * 4. pathlen constraints are satisfied * * If there's a suitable candidate which is also time-valid, return the first * such. Otherwise, return the first suitable candidate (or NULL if there is * none). * * The rationale for this rule is that someone could have a list of trusted * roots with two versions on the same root with different validity periods. * (At least one user reported having such a list and wanted it to just work.) * The reason we don't just require time-validity is that generally there is * only one version, and if it's expired we want the flags to state that * rather than NOT_TRUSTED, as would be the case if we required it here. * * The rationale for rule 3 (signature for trusted roots) is that users might * have two versions of the same CA with different keys in their list, and the * way we select the correct one is by checking the signature (as we don't * rely on key identifier extensions). (This is one way users might choose to * handle key rollover, another relies on self-issued certs, see [SIRO].) * * Arguments: * - [in] child: certificate for which we're looking for a parent * - [in] candidates: chained list of potential parents * - [out] r_parent: parent found (or NULL) * - [out] r_signature_is_good: 1 if child signature by parent is valid, or 0 * - [in] top: 1 if candidates consists of trusted roots, ie we're at the top * of the chain, 0 otherwise * - [in] path_cnt: number of intermediates seen so far * - [in] self_cnt: number of self-signed intermediates seen so far * (will never be greater than path_cnt) * - [in-out] rs_ctx: context for restarting operations * * Return value: * - 0 on success * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise */ static int x509_crt_find_parent_in( mbedtls_x509_crt *child, mbedtls_x509_crt *candidates, mbedtls_x509_crt **r_parent, int *r_signature_is_good, int top, unsigned path_cnt, unsigned self_cnt, mbedtls_x509_crt_restart_ctx *rs_ctx ) { int ret; mbedtls_x509_crt *parent, *fallback_parent; int signature_is_good, fallback_signature_is_good; #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* did we have something in progress? */ if( rs_ctx != NULL && rs_ctx->parent != NULL ) { /* restore saved state */ parent = rs_ctx->parent; fallback_parent = rs_ctx->fallback_parent; fallback_signature_is_good = rs_ctx->fallback_signature_is_good; /* clear saved state */ rs_ctx->parent = NULL; rs_ctx->fallback_parent = NULL; rs_ctx->fallback_signature_is_good = 0; /* resume where we left */ goto check_signature; } #endif fallback_parent = NULL; fallback_signature_is_good = 0; for( parent = candidates; parent != NULL; parent = parent->next ) { /* basic parenting skills (name, CA bit, key usage) */ if( x509_crt_check_parent( child, parent, top ) != 0 ) continue; /* +1 because stored max_pathlen is 1 higher that the actual value */ if( parent->max_pathlen > 0 && (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt ) { continue; } /* Signature */ #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) check_signature: #endif ret = x509_crt_check_signature( child, parent, rs_ctx ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { /* save state */ rs_ctx->parent = parent; rs_ctx->fallback_parent = fallback_parent; rs_ctx->fallback_signature_is_good = fallback_signature_is_good; return( ret ); } #else (void) ret; #endif signature_is_good = ret == 0; if( top && ! signature_is_good ) continue; /* optional time check */ if( mbedtls_x509_time_is_past( &parent->valid_to ) || mbedtls_x509_time_is_future( &parent->valid_from ) ) { if( fallback_parent == NULL ) { fallback_parent = parent; fallback_signature_is_good = signature_is_good; } continue; } break; } if( parent != NULL ) { *r_parent = parent; *r_signature_is_good = signature_is_good; } else { *r_parent = fallback_parent; *r_signature_is_good = fallback_signature_is_good; } return( 0 ); } /* * Find a parent in trusted CAs or the provided chain, or return NULL. * * Searches in trusted CAs first, and return the first suitable parent found * (see find_parent_in() for definition of suitable). * * Arguments: * - [in] child: certificate for which we're looking for a parent, followed * by a chain of possible intermediates * - [in] trust_ca: list of locally trusted certificates * - [out] parent: parent found (or NULL) * - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0 * - [out] signature_is_good: 1 if child signature by parent is valid, or 0 * - [in] path_cnt: number of links in the chain so far (EE -> ... -> child) * - [in] self_cnt: number of self-signed certs in the chain so far * (will always be no greater than path_cnt) * - [in-out] rs_ctx: context for restarting operations * * Return value: * - 0 on success * - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise */ static int x509_crt_find_parent( mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca, mbedtls_x509_crt **parent, int *parent_is_trusted, int *signature_is_good, unsigned path_cnt, unsigned self_cnt, mbedtls_x509_crt_restart_ctx *rs_ctx ) { int ret; mbedtls_x509_crt *search_list; *parent_is_trusted = 1; #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* restore then clear saved state if we have some stored */ if( rs_ctx != NULL && rs_ctx->parent_is_trusted != -1 ) { *parent_is_trusted = rs_ctx->parent_is_trusted; rs_ctx->parent_is_trusted = -1; } #endif while( 1 ) { search_list = *parent_is_trusted ? trust_ca : child->next; ret = x509_crt_find_parent_in( child, search_list, parent, signature_is_good, *parent_is_trusted, path_cnt, self_cnt, rs_ctx ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { /* save state */ rs_ctx->parent_is_trusted = *parent_is_trusted; return( ret ); } #else (void) ret; #endif /* stop here if found or already in second iteration */ if( *parent != NULL || *parent_is_trusted == 0 ) break; /* prepare second iteration */ *parent_is_trusted = 0; } /* extra precaution against mistakes in the caller */ if( *parent == NULL ) { *parent_is_trusted = 0; *signature_is_good = 0; } return( 0 ); } /* * Check if an end-entity certificate is locally trusted * * Currently we require such certificates to be self-signed (actually only * check for self-issued as self-signatures are not checked) */ static int x509_crt_check_ee_locally_trusted( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca ) { mbedtls_x509_crt *cur; /* must be self-issued */ if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 ) return( -1 ); /* look for an exact match with trusted cert */ for( cur = trust_ca; cur != NULL; cur = cur->next ) { if( crt->raw.len == cur->raw.len && memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 ) { return( 0 ); } } /* too bad */ return( -1 ); } /* * Build and verify a certificate chain * * Given a peer-provided list of certificates EE, C1, ..., Cn and * a list of trusted certs R1, ... Rp, try to build and verify a chain * EE, Ci1, ... Ciq [, Rj] * such that every cert in the chain is a child of the next one, * jumping to a trusted root as early as possible. * * Verify that chain and return it with flags for all issues found. * * Special cases: * - EE == Rj -> return a one-element list containing it * - EE, Ci1, ..., Ciq cannot be continued with a trusted root * -> return that chain with NOT_TRUSTED set on Ciq * * Tests for (aspects of) this function should include at least: * - trusted EE * - EE -> trusted root * - EE -> intermediate CA -> trusted root * - if relevant: EE untrusted * - if relevant: EE -> intermediate, untrusted * with the aspect under test checked at each relevant level (EE, int, root). * For some aspects longer chains are required, but usually length 2 is * enough (but length 1 is not in general). * * Arguments: * - [in] crt: the cert list EE, C1, ..., Cn * - [in] trust_ca: the trusted list R1, ..., Rp * - [in] ca_crl, profile: as in verify_with_profile() * - [out] ver_chain: the built and verified chain * Only valid when return value is 0, may contain garbage otherwise! * Restart note: need not be the same when calling again to resume. * - [in-out] rs_ctx: context for restarting operations * * Return value: * - non-zero if the chain could not be fully built and examined * - 0 is the chain was successfully built and examined, * even if it was found to be invalid */ static int x509_crt_verify_chain( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb, const mbedtls_x509_crt_profile *profile, mbedtls_x509_crt_verify_chain *ver_chain, mbedtls_x509_crt_restart_ctx *rs_ctx ) { /* Don't initialize any of those variables here, so that the compiler can * catch potential issues with jumping ahead when restarting */ int ret; uint32_t *flags; mbedtls_x509_crt_verify_chain_item *cur; mbedtls_x509_crt *child; mbedtls_x509_crt *parent; int parent_is_trusted; int child_is_trusted; int signature_is_good; unsigned self_cnt; mbedtls_x509_crt *cur_trust_ca = NULL; #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* resume if we had an operation in progress */ if( rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent ) { /* restore saved state */ *ver_chain = rs_ctx->ver_chain; /* struct copy */ self_cnt = rs_ctx->self_cnt; /* restore derived state */ cur = &ver_chain->items[ver_chain->len - 1]; child = cur->crt; flags = &cur->flags; goto find_parent; } #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ child = crt; self_cnt = 0; parent_is_trusted = 0; child_is_trusted = 0; while( 1 ) { /* Add certificate to the verification chain */ cur = &ver_chain->items[ver_chain->len]; cur->crt = child; cur->flags = 0; ver_chain->len++; flags = &cur->flags; /* Check time-validity (all certificates) */ if( mbedtls_x509_time_is_past( &child->valid_to ) ) *flags |= MBEDTLS_X509_BADCERT_EXPIRED; if( mbedtls_x509_time_is_future( &child->valid_from ) ) *flags |= MBEDTLS_X509_BADCERT_FUTURE; /* Stop here for trusted roots (but not for trusted EE certs) */ if( child_is_trusted ) return( 0 ); /* Check signature algorithm: MD & PK algs */ if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_MD; if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; /* Special case: EE certs that are locally trusted */ if( ver_chain->len == 1 && x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 ) { return( 0 ); } #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) find_parent: #endif /* Obtain list of potential trusted signers from CA callback, * or use statically provided list. */ #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) if( f_ca_cb != NULL ) { mbedtls_x509_crt_free( ver_chain->trust_ca_cb_result ); mbedtls_free( ver_chain->trust_ca_cb_result ); ver_chain->trust_ca_cb_result = NULL; ret = f_ca_cb( p_ca_cb, child, &ver_chain->trust_ca_cb_result ); if( ret != 0 ) return( MBEDTLS_ERR_X509_FATAL_ERROR ); cur_trust_ca = ver_chain->trust_ca_cb_result; } else #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ { ((void) f_ca_cb); ((void) p_ca_cb); cur_trust_ca = trust_ca; } /* Look for a parent in trusted CAs or up the chain */ ret = x509_crt_find_parent( child, cur_trust_ca, &parent, &parent_is_trusted, &signature_is_good, ver_chain->len - 1, self_cnt, rs_ctx ); #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS ) { /* save state */ rs_ctx->in_progress = x509_crt_rs_find_parent; rs_ctx->self_cnt = self_cnt; rs_ctx->ver_chain = *ver_chain; /* struct copy */ return( ret ); } #else (void) ret; #endif /* No parent? We're done here */ if( parent == NULL ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; return( 0 ); } /* Count intermediate self-issued (not necessarily self-signed) certs. * These can occur with some strategies for key rollover, see [SIRO], * and should be excluded from max_pathlen checks. */ if( ver_chain->len != 1 && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) { self_cnt++; } /* path_cnt is 0 for the first intermediate CA, * and if parent is trusted it's not an intermediate CA */ if( ! parent_is_trusted && ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { /* return immediately to avoid overflow the chain array */ return( MBEDTLS_ERR_X509_FATAL_ERROR ); } /* signature was checked while searching parent */ if( ! signature_is_good ) *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; /* check size of signing key */ if( x509_profile_check_key( profile, &parent->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; #if defined(MBEDTLS_X509_CRL_PARSE_C) /* Check trusted CA's CRL for the given crt */ *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile ); #else (void) ca_crl; #endif /* prepare for next iteration */ child = parent; parent = NULL; child_is_trusted = parent_is_trusted; signature_is_good = 0; } } /* * Check for CN match */ static int x509_crt_check_cn( const mbedtls_x509_buf *name, const char *cn, size_t cn_len ) { /* try exact match */ if( name->len == cn_len && x509_memcasecmp( cn, name->p, cn_len ) == 0 ) { return( 0 ); } /* try wildcard match */ if( x509_check_wildcard( cn, name ) == 0 ) { return( 0 ); } return( -1 ); } /* * Verify the requested CN - only call this if cn is not NULL! */ static void x509_crt_verify_name( const mbedtls_x509_crt *crt, const char *cn, uint32_t *flags ) { const mbedtls_x509_name *name; const mbedtls_x509_sequence *cur; size_t cn_len = strlen( cn ); if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next ) { if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 ) break; } if( cur == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } else { for( name = &crt->subject; name != NULL; name = name->next ) { if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 && x509_crt_check_cn( &name->val, cn, cn_len ) == 0 ) { break; } } if( name == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } } /* * Merge the flags for all certs in the chain, after calling callback */ static int x509_crt_merge_flags_with_cb( uint32_t *flags, const mbedtls_x509_crt_verify_chain *ver_chain, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret; unsigned i; uint32_t cur_flags; const mbedtls_x509_crt_verify_chain_item *cur; for( i = ver_chain->len; i != 0; --i ) { cur = &ver_chain->items[i-1]; cur_flags = cur->flags; if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, cur->crt, (int) i-1, &cur_flags ) ) != 0 ) return( ret ); *flags |= cur_flags; } return( 0 ); } /* * Verify the certificate validity, with profile, restartable version * * This function: * - checks the requested CN (if any) * - checks the type and size of the EE cert's key, * as that isn't done as part of chain building/verification currently * - builds and verifies the chain * - then calls the callback and merges the flags * * The parameters pairs `trust_ca`, `ca_crl` and `f_ca_cb`, `p_ca_cb` * are mutually exclusive: If `f_ca_cb != NULL`, it will be used by the * verification routine to search for trusted signers, and CRLs will * be disabled. Otherwise, `trust_ca` will be used as the static list * of trusted signers, and `ca_crl` will be use as the static list * of CRLs. */ static int x509_crt_verify_restartable_ca_cb( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy, mbedtls_x509_crt_restart_ctx *rs_ctx ) { int ret; mbedtls_pk_type_t pk_type; mbedtls_x509_crt_verify_chain ver_chain; uint32_t ee_flags; *flags = 0; ee_flags = 0; x509_crt_verify_chain_reset( &ver_chain ); if( profile == NULL ) { ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA; goto exit; } /* check name if requested */ if( cn != NULL ) x509_crt_verify_name( crt, cn, &ee_flags ); /* Check the type and size of the key */ pk_type = mbedtls_pk_get_type( &crt->pk ); if( x509_profile_check_pk_alg( profile, pk_type ) != 0 ) ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK; if( x509_profile_check_key( profile, &crt->pk ) != 0 ) ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY; /* Check the chain */ ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, f_ca_cb, p_ca_cb, profile, &ver_chain, rs_ctx ); if( ret != 0 ) goto exit; /* Merge end-entity flags */ ver_chain.items[0].flags |= ee_flags; /* Build final flags, calling callback on the way if any */ ret = x509_crt_merge_flags_with_cb( flags, &ver_chain, f_vrfy, p_vrfy ); exit: #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) mbedtls_x509_crt_free( ver_chain.trust_ca_cb_result ); mbedtls_free( ver_chain.trust_ca_cb_result ); ver_chain.trust_ca_cb_result = NULL; #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) mbedtls_x509_crt_restart_free( rs_ctx ); #endif /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by * the SSL module for authmode optional, but non-zero return from the * callback means a fatal error so it shouldn't be ignored */ if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ) ret = MBEDTLS_ERR_X509_FATAL_ERROR; if( ret != 0 ) { *flags = (uint32_t) -1; return( ret ); } if( *flags != 0 ) return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); return( 0 ); } /* * Verify the certificate validity (default profile, not restartable) */ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl, NULL, NULL, &mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy, NULL ) ); } /* * Verify the certificate validity (user-chosen profile, not restartable) */ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl, NULL, NULL, profile, cn, flags, f_vrfy, p_vrfy, NULL ) ); } #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) /* * Verify the certificate validity (user-chosen profile, CA callback, * not restartable). */ int mbedtls_x509_crt_verify_with_ca_cb( mbedtls_x509_crt *crt, mbedtls_x509_crt_ca_cb_t f_ca_cb, void *p_ca_cb, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { return( x509_crt_verify_restartable_ca_cb( crt, NULL, NULL, f_ca_cb, p_ca_cb, profile, cn, flags, f_vrfy, p_vrfy, NULL ) ); } #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */ int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy, mbedtls_x509_crt_restart_ctx *rs_ctx ) { return( x509_crt_verify_restartable_ca_cb( crt, trust_ca, ca_crl, NULL, NULL, profile, cn, flags, f_vrfy, p_vrfy, rs_ctx ) ); } /* * Initialize a certificate chain */ void mbedtls_x509_crt_init( mbedtls_x509_crt *crt ) { memset( crt, 0, sizeof(mbedtls_x509_crt) ); } /* * Unallocate all certificate data */ void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ) { mbedtls_x509_crt *cert_cur = crt; mbedtls_x509_crt *cert_prv; mbedtls_x509_name *name_cur; mbedtls_x509_name *name_prv; mbedtls_x509_sequence *seq_cur; mbedtls_x509_sequence *seq_prv; if( crt == NULL ) return; do { mbedtls_pk_free( &cert_cur->pk ); #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) mbedtls_free( cert_cur->sig_opts ); #endif name_cur = cert_cur->issuer.next; while( name_cur != NULL ) { name_prv = name_cur; name_cur = name_cur->next; mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } name_cur = cert_cur->subject.next; while( name_cur != NULL ) { name_prv = name_cur; name_cur = name_cur->next; mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) ); mbedtls_free( name_prv ); } seq_cur = cert_cur->ext_key_usage.next; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } seq_cur = cert_cur->subject_alt_names.next; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } seq_cur = cert_cur->certificate_policies.next; while( seq_cur != NULL ) { seq_prv = seq_cur; seq_cur = seq_cur->next; mbedtls_platform_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) ); mbedtls_free( seq_prv ); } if( cert_cur->raw.p != NULL && cert_cur->own_buffer ) { mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len ); mbedtls_free( cert_cur->raw.p ); } cert_cur = cert_cur->next; } while( cert_cur != NULL ); cert_cur = crt; do { cert_prv = cert_cur; cert_cur = cert_cur->next; mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) ); if( cert_prv != crt ) mbedtls_free( cert_prv ); } while( cert_cur != NULL ); } #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) /* * Initialize a restart context */ void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx ) { mbedtls_pk_restart_init( &ctx->pk ); ctx->parent = NULL; ctx->fallback_parent = NULL; ctx->fallback_signature_is_good = 0; ctx->parent_is_trusted = -1; ctx->in_progress = x509_crt_rs_none; ctx->self_cnt = 0; x509_crt_verify_chain_reset( &ctx->ver_chain ); } /* * Free the components of a restart context */ void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_pk_restart_free( &ctx->pk ); mbedtls_x509_crt_restart_init( ctx ); } #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_X509_CRT_PARSE_C */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/include/ff_string.h
<reponame>MicroEJ/FreeRTOS /* * FreeRTOS+FAT build 191128 - Note: FreeRTOS+FAT is still in the lab! * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Authors include <NAME>, <NAME> and <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * */ /** * @file ff_string.c * @ingroup STRING * * @defgroup STRING FreeRTOS+FAT String Library * @brief Portable String Library for FreeRTOS+FAT * * **/ #ifndef _FF_STRING_H_ #define _FF_STRING_H_ #include "FreeRTOSFATConfig.h" #include <string.h> #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) #include <wchar.h> typedef wchar_t FF_T_WCHAR; /*/< Unicode UTF-16 Character type, for FreeRTOS+FAT when UNICODE is enabled. */ #endif #if defined( _MSC_VER ) && ( _MSC_VER <= 1600 ) #define FF_stricmp _stricmp #else #define FF_stricmp strcasecmp #endif #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) void FF_tolower ( FF_T_WCHAR *string, uint32_t strLen ); void FF_toupper ( FF_T_WCHAR *string, uint32_t strLen ); BaseType_t FF_strmatch ( const FF_T_WCHAR *str1, const FF_T_WCHAR *str2, BaseType_t len ); FF_T_WCHAR *FF_strtok ( const FF_T_WCHAR *string, FF_T_WCHAR *token, uint16_t *tokenNumber, BaseType_t *last, BaseType_t xLength ); BaseType_t FF_wildcompare ( const FF_T_WCHAR *pcWildCard, const FF_T_WCHAR *pszString ); /* ASCII to UTF16 and UTF16 to ASCII routines. -- These are lossy routines, and are only for converting ASCII to UTF-16 */ /* and the equivalent back to ASCII. Do not use them for international text. */ void FF_cstrtowcs(FF_T_WCHAR *wcsDest, const char *szpSource); void FF_wcstocstr(char *szpDest, const FF_T_WCHAR *wcsSource); void FF_cstrntowcs(FF_T_WCHAR *wcsDest, const char *szpSource, uint32_t len); void FF_wcsntocstr(char *szpDest, const FF_T_WCHAR *wcsSource, uint32_t len); #else void FF_tolower ( char *string, uint32_t strLen ); void FF_toupper ( char *string, uint32_t strLen ); BaseType_t FF_strmatch ( const char *str1, const char *str2, BaseType_t len ); char *FF_strtok ( const char *string, char *token, uint16_t *tokenNumber, BaseType_t *last, BaseType_t xLength ); BaseType_t FF_wildcompare ( const char *pcWildCard, const char *pszString ); #endif /* ffconfigUNICODE_UTF16_SUPPORT */ /* UTF8 / UTF16 Transformation Functions. */ #if ( ( ffconfigUNICODE_UTF16_SUPPORT != 0 ) && ( WCHAR_MAX > 0xFFFF ) ) || ( ffconfigUNICODE_UTF8_SUPPORT != 0 ) UBaseType_t FF_GetUtf16SequenceLen (uint16_t usLeadChar); #endif #if( ffconfigUNICODE_UTF8_SUPPORT != 0 ) int32_t FF_Utf8ctoUtf16c (uint16_t *utf16Dest, const uint8_t *utf8Source, uint32_t ulSize); int32_t FF_Utf16ctoUtf8c (uint8_t *utf8Dest, const uint16_t *utf16Source, uint32_t ulSize); #endif /* ffconfigUNICODE_UTF8_SUPPORT */ /* UTF16 / UTF32 Transformation Functions. */ #if( ffconfigNOT_USED_FOR_NOW != 0 ) int32_t FF_Utf16ctoUtf32c(uint32_t *utf32Dest, const uint16_t *utf16Source); #endif #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) && ( WCHAR_MAX > 0xFFFF ) int32_t FF_Utf32ctoUtf16c(uint16_t *utf16Dest, uint32_t utf32char, uint32_t ulSize); #endif /* String transformations. */ int32_t FF_Utf32stoUtf8s(uint8_t *Utf8String, uint32_t *Utf32String); #if( ffconfigUNICODE_UTF16_SUPPORT != 0 ) #define STRNCPY( target, src, maxlen ) wcsncpy( ( target ), ( src ), ( maxlen ) ) #define STRLEN( string ) wcslen( ( string ) ) #else #define STRNCPY( target, src, maxlen ) strncpy( ( target ), ( src ), ( maxlen ) ); #define STRLEN( string ) strlen( ( string ) ) #endif #endif
MicroEJ/FreeRTOS
FreeRTOS-Labs/Demo/FreeRTOS_IoT_Libraries/include/https_demo_profile.h
/* * FreeRTOS Kernel V10.3.0 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* * Each profile corresponds to a different service. The demos that use the same * profile share the same service. It is important to understand the * correspondence between the preconfigured profiles and demos, since each * service have different connection configuration and credential validation. * * - mqtt_demo_profile.h is preconfigured to test.mosquitto.org MQTT broker. * The file is used with mqtt_plain_text demo and mqtt_basic_tls_server_auth * demo. Feel free to try out other broker with the demos. * * - https_demo_profile.h (current) is preconfigured to httpbin.org server. * The file is used with http_plain_text demo and https_basic_tls_server_auth * demo. * * - aws_iot_demo_profile.h contains information to connect to AWS * IoT. The file is used with mqtt_tls_mutual_auth demo, https_tls_mutual_auth * demo, and other AWS IoT related demo. */ #ifndef HTTPS_DEMO_PROFILE_H #define HTTPS_DEMO_PROFILE_H #include "demo_config.h" /** * @brief Details of the HTTPS server to connect to. * * Please note that many web servers will close the connection immediately after * sending the response in order to save resources. This demo is compatible only * with a server that persists the connection after sending a response. * * Port 443 is the standard port designated for encrypted HTTPS traffic. */ #define httpsdemoprofileSERVER_ADDRESS "httpbin.org" #if ( democonfigENABLE_TLS ) #define httpsdemoprofileSERVER_PORT 443 #else #define httpsdemoprofileSERVER_PORT 80 #endif /** * @brief The server certificate for httpbin.org:443. * * This certificate is obtained from https://httpbin.org/ and is used to * authenticate the HTTPS server. This demo only authenticates the server and * does not authenticate the client. * * If you want to connect to any other HTTPS server other than httpbin.org, * replace it with the certificate of the HTTPS server. */ #define httpsdemoprofileSERVER_CERTIFICATE_PEM \ "-----BEGIN CERTIFICATE-----\n" \ "MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ "ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ "b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ "b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ "ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ "9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ "<KEY>" \ "<KEY>" \ "<KEY>" \ "jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ "AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ "A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ "U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ "N+gDS63pYaAC<KEY>" \ "o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ "5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ "rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ "-----END CERTIFICATE-----\n" #endif /* ifndef HTTPS_DEMO_PROFILE_H */
MicroEJ/FreeRTOS
FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/portable/ATSAM4E/ff_sddisk.c
<filename>FreeRTOS-Labs/Source/FreeRTOS-Plus-FAT/portable/ATSAM4E/ff_sddisk.c /* * FreeRTOS+FAT build 191128 - Note: FreeRTOS+FAT is still in the lab! * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Authors include <NAME>, <NAME> and <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * */ /* Standard includes. */ #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdio.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "semphr.h" #include "portmacro.h" /* FreeRTOS+FAT includes. */ #include "ff_sddisk.h" #include "ff_sys.h" /* Atmel includes. */ #include <board.h> #include <sd_mmc.h> #include "hr_gettime.h" /* Misc definitions. */ #define sdSIGNATURE 0x41404342UL #define sdHUNDRED_64_BIT ( 100ull ) #define sdBYTES_PER_MB ( 1024ull * 1024ull ) #define sdSECTORS_PER_MB ( sdBYTES_PER_MB / 512ull ) #define sdIOMAN_MEM_SIZE 4096 #define xSDCardInfo ( sd_mmc_cards[ 0 ] ) #define sdAligned( pvAddress ) ( ( ( ( size_t ) ( pvAddress ) ) & ( sizeof( size_t ) - 1 ) ) == 0 ) #if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 ) /* Define a time-out for all DMA transactions in msec. */ #ifndef sdMAX_TRANSFER_TIME #define sdMAX_TRANSFER_TIME 4000 #endif /* Define all possible interrupts of interest. */ #define sdHSMCI_INTERRUPT_FLAGS \ HSMCI_IER_NOTBUSY | \ HSMCI_IER_UNRE | \ HSMCI_IER_OVRE | \ HSMCI_IER_DTOE | \ HSMCI_IER_DCRCE | \ HSMCI_IER_TXBUFE | \ HSMCI_IER_RXBUFF | \ HSMCI_IER_XFRDONE #define sdMSMCI_USE_SEMAPHORE 1 #endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */ /*-----------------------------------------------------------*/ #if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 ) static TickType_t xDMARemainingTime; static TimeOut_t xDMATimeOut; static volatile uint32_t ulSDInterruptStatus; static volatile int iWaitForWriting; #if( sdMSMCI_USE_SEMAPHORE != 0 ) static SemaphoreHandle_t xSDSemaphore = NULL; #else static TaskHandle_t xSDTaskHandle = NULL; #endif #endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */ /* * Return pdFALSE if the SD card is not inserted. */ static BaseType_t prvSDDetect( void ); /* * Check if the card is present, and if so, print out some info on the card. */ static BaseType_t prvSDMMCInit( BaseType_t xDriveNumber ); /*-----------------------------------------------------------*/ /* * Mutex for partition. */ static SemaphoreHandle_t xPlusFATMutex = NULL; /* * Remembers if the card is currently considered to be present. */ static BaseType_t xSDCardStatus = pdFALSE; /*-----------------------------------------------------------*/ typedef struct { uint32_t ulStart; uint32_t ulSize; } MemoryGroup_t; #define ARRAY_SIZE(x) (int)(sizeof(x)/sizeof(x)[0]) static const MemoryGroup_t xMemories[] = { { IRAM_ADDR, IRAM_SIZE }, { EBI_CS1_ADDR, 512ul * 1024ul }, { EBI_CS3_ADDR, 512ul * 1024ul }, }; static BaseType_t prvIsInternalRAM( uint8_t *pucBuffer ) { BaseType_t xResult = pdFALSE, xIndex; uint32_t ulAddress = ( uint32_t ) pucBuffer; for( xIndex = 0; xIndex < ARRAY_SIZE( xMemories ); xIndex++ ) { if( ( ulAddress >= xMemories[ xIndex].ulStart ) && ( ulAddress < xMemories[ xIndex].ulStart + xMemories[ xIndex].ulSize ) ) { xResult = pdTRUE; break; } } return xResult; } /*-----------------------------------------------------------*/ static int32_t prvFFRead( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk ) { int32_t lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_READ | FF_ERRFLAG, lResult = pdFALSE; if( ( pxDisk != NULL ) && ( xSDCardStatus == pdPASS ) && ( pxDisk->ulSignature == sdSIGNATURE ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) && ( ulSectorNumber < pxDisk->ulNumberOfSectors ) && ( ( pxDisk->ulNumberOfSectors - ulSectorNumber ) >= ulSectorCount ) ) { /* As the MCI driver is configured to use DMA, it must be tested that the buffer is located in internal SRAM ("IRAM") and if it is 4-byte aligned. */ if( sdAligned( pucBuffer ) && prvIsInternalRAM( pucBuffer ) ) { lResult = sd_physical_read( ulSectorNumber, pucBuffer, ulSectorCount ); } else { uint32_t ulSector; uint8_t *pucDMABuffer = ffconfigMALLOC( 512ul ); /* The buffer is NOT word-aligned, read to an aligned buffer and then copy the data to the user provided buffer. */ if( pucDMABuffer != NULL ) { for( ulSector = 0; ulSector < ulSectorCount; ulSector++ ) { lResult = sd_physical_read( ulSectorNumber + ulSector, pucDMABuffer, 1 ); if( lResult == pdFALSE ) { break; } /* Copy to the user-provided buffer. */ memcpy( pucBuffer + 512ul * ulSector, pucDMABuffer, 512ul ); } ffconfigFREE( pucDMABuffer ); } else { FF_PRINTF( "prvFFRead: malloc failed\n" ); lResult = pdFALSE; } } if( lResult != pdFALSE ) { lReturnCode = 0L; } else { /* Some error occurred. */ FF_PRINTF( "prvFFRead: %lu: %ld\n", ulSectorNumber, lResult ); } } else { /* Make sure no random data is in the returned buffer. */ memset( ( void * ) pucBuffer, '\0', ulSectorCount * 512UL ); if( pxDisk->xStatus.bIsInitialised != pdFALSE ) { FF_PRINTF( "prvFFRead: warning: %lu + %lu > %lu\n", ulSectorNumber, ulSectorCount, pxDisk->ulNumberOfSectors ); } } return lReturnCode; } /*-----------------------------------------------------------*/ static int32_t prvFFWrite( uint8_t *pucBuffer, uint32_t ulSectorNumber, uint32_t ulSectorCount, FF_Disk_t *pxDisk ) { int32_t lReturnCode = FF_ERR_IOMAN_OUT_OF_BOUNDS_READ | FF_ERRFLAG, lResult = pdFALSE; if( ( pxDisk != NULL ) && ( xSDCardStatus == pdPASS ) && ( pxDisk->ulSignature == sdSIGNATURE ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) && ( ulSectorNumber < pxDisk->ulNumberOfSectors ) && ( ( pxDisk->ulNumberOfSectors - ulSectorNumber ) >= ulSectorCount ) ) { /* As the MCI driver is configured to use DMA, it must be tested that the buffer is located in internal SRAM ("IRAM") and if it is 4-byte aligned. */ if( sdAligned( pucBuffer ) && prvIsInternalRAM( pucBuffer ) ) { lResult = sd_physical_write( ulSectorNumber, pucBuffer, ulSectorCount ); } else { uint32_t ulSector; uint8_t *pucDMABuffer = ffconfigMALLOC( 512ul ); /* The buffer is NOT word-aligned, read to an aligned buffer and then copy the data to the user provided buffer. */ if( pucDMABuffer != NULL ) { for( ulSector = 0; ulSector < ulSectorCount; ulSector++ ) { /* Copy from the user provided buffer to the temporary buffer. */ memcpy( pucDMABuffer, pucBuffer + 512ul * ulSector, 512ul ); lResult = sd_physical_write( ulSectorNumber + ulSector, pucDMABuffer, 1 ); if( lResult == pdFALSE ) { break; } } ffconfigFREE( pucDMABuffer ); } else { FF_PRINTF( "prvFFWrite: malloc failed\n" ); lResult = pdFALSE; } } if( lResult != pdFALSE ) { /* No errors. */ lReturnCode = 0L; } else { FF_PRINTF( "prvFFWrite: %lu: %ld\n", ulSectorNumber, lResult ); } } else { if( pxDisk->xStatus.bIsInitialised != pdFALSE ) { FF_PRINTF( "prvFFWrite: warning: %lu + %lu > %lu\n", ulSectorNumber, ulSectorCount, pxDisk->ulNumberOfSectors ); } } return lReturnCode; } /*-----------------------------------------------------------*/ void FF_SDDiskFlush( FF_Disk_t *pxDisk ) { if( ( pxDisk != NULL ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) && ( pxDisk->pxIOManager != NULL ) ) { FF_FlushCache( pxDisk->pxIOManager ); } } /*-----------------------------------------------------------*/ /* Initialise the SDIO driver and mount an SD card */ FF_Disk_t *FF_SDDiskInit( const char *pcName ) { FF_Error_t xFFError; BaseType_t xPartitionNumber = 0; FF_CreationParameters_t xParameters; FF_Disk_t *pxDisk; #if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 ) { NVIC_SetPriority( HSMCI_IRQn, configHSMCI_INTERRUPT_PRIORITY ); NVIC_EnableIRQ( HSMCI_IRQn ); #if( sdMSMCI_USE_SEMAPHORE != 0 ) { if( xSDSemaphore == NULL ) { xSDSemaphore = xSemaphoreCreateBinary(); } } #endif /* sdMSMCI_USE_SEMAPHORE */ } #endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */ xSDCardStatus = prvSDMMCInit( 0 ); if( xSDCardStatus == pdPASS ) { pxDisk = (FF_Disk_t *)ffconfigMALLOC( sizeof( *pxDisk ) ); if( pxDisk != NULL ) { /* Initialise the created disk structure. */ memset( pxDisk, '\0', sizeof( *pxDisk ) ); /* The Atmel MMC driver sets capacity as a number of KB. Divide by two to get the number of 512-byte sectors. */ pxDisk->ulNumberOfSectors = xSDCardInfo.capacity << 1; if( xPlusFATMutex == NULL ) { xPlusFATMutex = xSemaphoreCreateRecursiveMutex(); } pxDisk->ulSignature = sdSIGNATURE; if( xPlusFATMutex != NULL) { memset( &xParameters, '\0', sizeof( xParameters ) ); xParameters.ulMemorySize = sdIOMAN_MEM_SIZE; xParameters.ulSectorSize = 512; xParameters.fnWriteBlocks = prvFFWrite; xParameters.fnReadBlocks = prvFFRead; xParameters.pxDisk = pxDisk; /* prvFFRead()/prvFFWrite() are not re-entrant and must be protected with the use of a semaphore. */ xParameters.xBlockDeviceIsReentrant = pdFALSE; /* The semaphore will be used to protect critical sections in the +FAT driver, and also to avoid concurrent calls to prvFFRead()/prvFFWrite() from different tasks. */ xParameters.pvSemaphore = ( void * ) xPlusFATMutex; pxDisk->pxIOManager = FF_CreateIOManger( &xParameters, &xFFError ); if( pxDisk->pxIOManager == NULL ) { FF_PRINTF( "FF_SDDiskInit: FF_CreateIOManger: %s\n", (const char*)FF_GetErrMessage( xFFError ) ); FF_SDDiskDelete( pxDisk ); pxDisk = NULL; } else { pxDisk->xStatus.bIsInitialised = pdTRUE; pxDisk->xStatus.bPartitionNumber = xPartitionNumber; if( FF_SDDiskMount( pxDisk ) == 0 ) { FF_SDDiskDelete( pxDisk ); pxDisk = NULL; } else { if( pcName == NULL ) { pcName = "/"; } FF_FS_Add( pcName, pxDisk ); FF_PRINTF( "FF_SDDiskInit: Mounted SD-card as root \"%s\"\n", pcName ); } } /* if( pxDisk->pxIOManager != NULL ) */ } /* if( xPlusFATMutex != NULL) */ } /* if( pxDisk != NULL ) */ else { FF_PRINTF( "FF_SDDiskInit: Malloc failed\n" ); } } /* if( xSDCardStatus == pdPASS ) */ else { FF_PRINTF( "FF_SDDiskInit: prvSDMMC_Init failed\n" ); pxDisk = NULL; } return pxDisk; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskFormat( FF_Disk_t *pxDisk, BaseType_t xPartitionNumber ) { FF_Error_t xError; BaseType_t xReturn = pdFAIL; xError = FF_Unmount( pxDisk ); if( FF_isERR( xError ) != pdFALSE ) { FF_PRINTF( "FF_SDDiskFormat: unmount fails: %08x\n", ( unsigned ) xError ); } else { /* Format the drive - try FAT32 with large clusters. */ xError = FF_Format( pxDisk, xPartitionNumber, pdFALSE, pdFALSE); if( FF_isERR( xError ) ) { FF_PRINTF( "FF_SDDiskFormat: %s\n", (const char*)FF_GetErrMessage( xError ) ); } else { FF_PRINTF( "FF_SDDiskFormat: OK, now remounting\n" ); pxDisk->xStatus.bPartitionNumber = xPartitionNumber; xError = FF_SDDiskMount( pxDisk ); FF_PRINTF( "FF_SDDiskFormat: rc %08x\n", ( unsigned )xError ); if( FF_isERR( xError ) == pdFALSE ) { xReturn = pdPASS; } } } return xReturn; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskUnmount( FF_Disk_t *pxDisk ) { FF_Error_t xFFError; BaseType_t xReturn = pdPASS; if( ( pxDisk != NULL ) && ( pxDisk->xStatus.bIsMounted != pdFALSE ) ) { pxDisk->xStatus.bIsMounted = pdFALSE; xFFError = FF_Unmount( pxDisk ); if( FF_isERR( xFFError ) ) { FF_PRINTF( "FF_SDDiskUnmount: rc %08x\n", ( unsigned )xFFError ); xReturn = pdFAIL; } else { FF_PRINTF( "Drive unmounted\n" ); } } return xReturn; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskReinit( FF_Disk_t *pxDisk ) { BaseType_t xStatus = prvSDMMCInit( 0 ); /* Hard coded index. */ /*_RB_ parameter not used. */ ( void ) pxDisk; FF_PRINTF( "FF_SDDiskReinit: rc %08x\n", ( unsigned ) xStatus ); return xStatus; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskMount( FF_Disk_t *pxDisk ) { FF_Error_t xFFError; BaseType_t xReturn; /* Mount the partition */ xFFError = FF_Mount( pxDisk, pxDisk->xStatus.bPartitionNumber ); if( FF_isERR( xFFError ) ) { FF_PRINTF( "FF_SDDiskMount: %08lX\n", xFFError ); xReturn = pdFAIL; } else { pxDisk->xStatus.bIsMounted = pdTRUE; FF_PRINTF( "****** FreeRTOS+FAT initialized %lu sectors\n", pxDisk->pxIOManager->xPartition.ulTotalSectors ); FF_SDDiskShowPartition( pxDisk ); xReturn = pdPASS; } return xReturn; } /*-----------------------------------------------------------*/ FF_IOManager_t *sddisk_ioman( FF_Disk_t *pxDisk ) { FF_IOManager_t *pxReturn; if( ( pxDisk != NULL ) && ( pxDisk->xStatus.bIsInitialised != pdFALSE ) ) { pxReturn = pxDisk->pxIOManager; } else { pxReturn = NULL; } return pxReturn; } /*-----------------------------------------------------------*/ /* Release all resources */ BaseType_t FF_SDDiskDelete( FF_Disk_t *pxDisk ) { if( pxDisk != NULL ) { pxDisk->ulSignature = 0; pxDisk->xStatus.bIsInitialised = 0; if( pxDisk->pxIOManager != NULL ) { if( FF_Mounted( pxDisk->pxIOManager ) != pdFALSE ) { FF_Unmount( pxDisk ); } FF_DeleteIOManager( pxDisk->pxIOManager ); } vPortFree( pxDisk ); } return 1; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskShowPartition( FF_Disk_t *pxDisk ) { FF_Error_t xError; uint64_t ullFreeSectors; uint32_t ulTotalSizeMB, ulFreeSizeMB; int iPercentageFree; FF_IOManager_t *pxIOManager; const char *pcTypeName = "unknown type"; BaseType_t xReturn = pdPASS; if( pxDisk == NULL ) { xReturn = pdFAIL; } else { pxIOManager = pxDisk->pxIOManager; FF_PRINTF( "Reading FAT and calculating Free Space\n" ); switch( pxIOManager->xPartition.ucType ) { case FF_T_FAT12: pcTypeName = "FAT12"; break; case FF_T_FAT16: pcTypeName = "FAT16"; break; case FF_T_FAT32: pcTypeName = "FAT32"; break; default: pcTypeName = "UNKOWN"; break; } FF_GetFreeSize( pxIOManager, &xError ); ullFreeSectors = pxIOManager->xPartition.ulFreeClusterCount * pxIOManager->xPartition.ulSectorsPerCluster; iPercentageFree = ( int ) ( ( sdHUNDRED_64_BIT * ullFreeSectors + pxIOManager->xPartition.ulDataSectors / 2 ) / ( ( uint64_t )pxIOManager->xPartition.ulDataSectors ) ); ulTotalSizeMB = pxIOManager->xPartition.ulDataSectors / sdSECTORS_PER_MB; ulFreeSizeMB = ( uint32_t ) ( ullFreeSectors / sdSECTORS_PER_MB ); /* It is better not to use the 64-bit format such as %Lu because it might not be implemented. */ FF_PRINTF( "Partition Nr %8u\n", pxDisk->xStatus.bPartitionNumber ); FF_PRINTF( "Type %8u (%s)\n", pxIOManager->xPartition.ucType, pcTypeName ); FF_PRINTF( "VolLabel '%8s' \n", pxIOManager->xPartition.pcVolumeLabel ); FF_PRINTF( "TotalSectors %8lu\n", pxIOManager->xPartition.ulTotalSectors ); FF_PRINTF( "SecsPerCluster %8lu\n", pxIOManager->xPartition.ulSectorsPerCluster ); FF_PRINTF( "Size %8lu MB\n", ulTotalSizeMB ); FF_PRINTF( "FreeSize %8lu MB ( %d perc free )\n", ulFreeSizeMB, iPercentageFree ); } return xReturn; } /*-----------------------------------------------------------*/ BaseType_t FF_SDDiskDetect( FF_Disk_t *pxDisk ) { BaseType_t xIsPresent; void *pvSemaphore; if( ( pxDisk != NULL ) && ( pxDisk->pxIOManager ) ) { pvSemaphore = pxDisk->pxIOManager->pvSemaphore; } else { pvSemaphore = NULL; } /*_RB_ Can these NULL checks be moved inside the FF_nnnSemaphore() functions? */ /*_HT_ I'm afraid not, both functions start with configASSERT( pxSemaphore ); */ if( pvSemaphore != NULL ) { FF_PendSemaphore( pvSemaphore ); } xIsPresent = prvSDDetect(); if( pvSemaphore != NULL ) { FF_ReleaseSemaphore( pvSemaphore ); } return xIsPresent; } /*-----------------------------------------------------------*/ static BaseType_t prvSDDetect( void ) { static BaseType_t xWasPresent; BaseType_t xIsPresent; sd_mmc_err_t xSDPresence; if( xWasPresent == pdFALSE ) { /* Try to initialize SD MMC stack */ sd_mmc_init(); xSDPresence = sd_mmc_check( 0 ); if( ( xSDPresence == SD_MMC_OK ) || ( xSDPresence == SD_MMC_INIT_ONGOING ) ) { xIsPresent = pdTRUE; } else { xIsPresent = pdFALSE; } } else { /* See if the card is still present. */ xSDPresence = sd_mmc_check_status(0); if( xSDPresence == SD_MMC_OK ) { xIsPresent = pdTRUE; } else { xIsPresent = pdFALSE; } } xWasPresent = xIsPresent; return xIsPresent; } /*-----------------------------------------------------------*/ static BaseType_t prvSDMMCInit( BaseType_t xDriveNumber ) { BaseType_t xReturn; /* 'xDriveNumber' not yet in use. */ ( void ) xDriveNumber; /* Check if the SD card is plugged in the slot */ if( prvSDDetect() == pdFALSE ) { FF_PRINTF( "No SD card detected\n" ); xReturn = pdFAIL; } else { FF_PRINTF( "HAL_SD_Init: type: %s Capacity: %lu MB\n", xSDCardInfo.type & CARD_TYPE_HC ? "SDHC" : "SD", ( xSDCardInfo.capacity << 1 ) / 2048 ); xReturn = pdPASS; } return xReturn; } /*-----------------------------------------------------------*/ #if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 ) void HSMCI_Handler( void ) { uint32_t ulSR; BaseType_t xSwitchRequired = pdFALSE; ulSR = HSMCI->HSMCI_SR & HSMCI->HSMCI_IMR; HSMCI->HSMCI_IDR = ulSR; ulSDInterruptStatus |= ulSR; #if( sdMSMCI_USE_SEMAPHORE != 0 ) { if( xSDSemaphore != NULL ) { xSemaphoreGiveFromISR( xSDSemaphore, &xSwitchRequired ); } } #else { if( xSDTaskHandle != NULL ) { vTaskNotifyGiveFromISR( xSDTaskHandle, ( BaseType_t * ) &xSwitchRequired ); } } #endif if( xSwitchRequired != pdFALSE ) { portEND_SWITCHING_ISR( xSwitchRequired ); } } #endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */ /*-----------------------------------------------------------*/ #if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 ) void vMCIEventSetupFunction( int iForWriting ) { iWaitForWriting = iForWriting != 0; #if( sdMSMCI_USE_SEMAPHORE == 0 ) { xSDTaskHandle = xTaskGetCurrentTaskHandle(); } #endif ulSDInterruptStatus = 0; HSMCI->HSMCI_IER = sdHSMCI_INTERRUPT_FLAGS; /* A DMA transfer to or from the SD-card is about to start. Reset the timers that will be used in prvEventWaitFunction() */ xDMARemainingTime = pdMS_TO_TICKS( sdMAX_TRANSFER_TIME ); vTaskSetTimeOutState( &xDMATimeOut ); } #endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */ /*-----------------------------------------------------------*/ #if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 ) void vMCIEventReadyFunction() { #if( sdMSMCI_USE_SEMAPHORE == 0 ) { xSDTaskHandle = NULL; } #endif ulSDInterruptStatus = 0; HSMCI->HSMCI_IDR = sdHSMCI_INTERRUPT_FLAGS; } #endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */ /*-----------------------------------------------------------*/ #if( ffconfigSDIO_DRIVER_USES_INTERRUPT != 0 ) uint32_t ulMCIEventWaitFunction( uint32_t ulMask ) { /* * It was measured how quickly a DMA interrupt was received. It varied * between 0 and 4 ms. * <= 1 ms : 8047 * <= 2 ms : 1850 * <= 3 ms : 99 * <= 4 ms : 79 * >= 5 ms : 0 times */ if( xTaskCheckForTimeOut( &xDMATimeOut, &xDMARemainingTime ) != pdFALSE ) { /* The timeout has been reached, no need to block. */ FF_PRINTF( "ulMCIEventWaitFunction: %s timed out. SR = %08x\n", iWaitForWriting ? "Write" : "Read", ulSDInterruptStatus ); } else { /* The timeout has not been reached yet, block on the semaphore. */ #if( sdMSMCI_USE_SEMAPHORE != 0 ) { if( ( ulSDInterruptStatus & ulMask ) == 0ul ) { xSemaphoreTake( xSDSemaphore, xDMARemainingTime ); } } #else { if( ( ulSDInterruptStatus & ulMask ) == 0ul ) { ulTaskNotifyTake( pdFALSE, xDMARemainingTime ); } } #endif if( xTaskCheckForTimeOut( &xDMATimeOut, &xDMARemainingTime ) != pdFALSE ) { FF_PRINTF( "ulMCIEventWaitFunction: %s timed out. SR = %08x\n", iWaitForWriting ? "Write" : "Read", ulSDInterruptStatus ); } } return ulSDInterruptStatus; } #endif /* ffconfigSDIO_DRIVER_USES_INTERRUPT */ /*-----------------------------------------------------------*/
avrora-robotics/ur_hardware_driver
src/uniorhwinterface.h
<reponame>avrora-robotics/ur_hardware_driver<gh_stars>1-10 /********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2016, AVRORA ROBOTICS LLC * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of AVRORA ROBOTICS LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: <NAME> Desc: */ #ifndef UNIORHWINTERFACE_H #define UNIORWINTERFACE_H #include <ros/console.h> #include <hardware_interface/robot_hw.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/joint_command_interface.h> #include <joint_limits_interface/joint_limits_interface.h> #include "ur_hardware_driver_config.h" #include "umotoudpinterface.h" using namespace hardware_interface; using namespace joint_limits_interface; using namespace umoto_interface; class UniorHW : public hardware_interface::RobotHW { public: UniorHW(); void read(const ros::Time& time, const ros::Duration& period); void write(const ros::Time& time, const ros::Duration& period); private: void registerSteeringJoint(); void registerVelocityJoint(); UMotoUDPInterface umoto_interface_; JointStateInterface joint_state_interface_; VelocityJointInterface joint_vel_command_interface_; PositionJointInterface joint_pos_command_interface_; VelocityJointSoftLimitsInterface limits_vel_interface_; PositionJointSoftLimitsInterface limits_pos_interface_; double steering_wheel_pose_ = 0; double steering_wheel_vel_ = 0; double steering_wheel_effort_ = 0; double steering_wheel_cmd_ = 0; double rear_wheel_pose_ = 0; double rear_wheel_vel_ = 0; double rear_wheel_effort_ = 0; double rear_wheel_cmd_ = 0; const int MAX_COMM_ERRORS = 5; int communication_error_cnt_ = 0; }; #endif // UNIORHWINTERFACE_H
avrora-robotics/ur_hardware_driver
src/umotoudpinterface.h
<filename>src/umotoudpinterface.h<gh_stars>1-10 /********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2016, AVRORA ROBOTICS LLC * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of AVRORA ROBOTICS LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: <NAME> Desc: */ #ifndef UMOTOUDPINTERFACE_H #define UMOTOUDPINTERFACE_H #include <boost/array.hpp> #include <boost/asio.hpp> #include <boost/asio/buffer.hpp> #include <boost/system/error_code.hpp> #include <boost/asio/deadline_timer.hpp> #include <boost/bind.hpp> #include <boost/lambda/lambda.hpp> #include <ros/console.h> #include <mutex> #include "umotopackets.h" using boost::asio::ip::udp; namespace umoto_interface { class UDPSocketConnection { public: UDPSocketConnection(); virtual ~UDPSocketConnection(); void connectToIP(const std::string& ip, uint16_t port); void disconnect(); size_t sendRequest(const std::vector<uint8_t> &request, std::vector<uint8_t> &response); private: void startReading(); void handleReceive(const boost::system::error_code& error, size_t bytes_transferred); void handleWrite(const boost::system::error_code& error, std::size_t bytes_transferred); void handleTimeout(const boost::system::error_code &error); const int UDP_TIMEOUT_MSEC = 30; boost::asio::io_service io_service_; udp::socket socket_; udp::endpoint endpoint_receiver_; udp::endpoint endpoint_sender_; boost::asio::deadline_timer timer_; boost::system::error_code error_code_; size_t bytes_rcv_ = 0; std::mutex connection_mutex_; }; class UMotoUDPInterface { public: UMotoUDPInterface(); void connectToIP(const std::string& ip, uint16_t port); UMotoData sendControl(const UMotoControl& control); UMotoVersion requestUMotoVersion(); private: template<typename Request, typename Response> void sendRequest(const Request& request, Response& response); UDPSocketConnection connection; }; } #endif // UMOTOUDPINTERFACE_H
avrora-robotics/ur_hardware_driver
src/umototypes.h
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2016, AVRORA ROBOTICS LLC * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of AVRORA ROBOTICS LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: <NAME> Desc: */ #ifndef UMOTOTYPES_H #define UMOTOTYPES_H #include <inttypes.h> class UMotoControl { public: int16_t steering = 0; int16_t velocity = 0; }; class UMotoData { public: uint32_t timestamp = 0; int32_t velocity = 0; int32_t rear_enc = 0; int32_t steering_enc = 0; uint32_t state = 0; }; class UMotoVersion { public: uint8_t version[4] = {0,0,0,0}; }; #endif // UMOTOTYPES_H
avrora-robotics/ur_hardware_driver
src/umotopackets.h
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2016, AVRORA ROBOTICS LLC * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of AVRORA ROBOTICS LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: <NAME> Desc: */ #ifndef UMOTOPACKETS_H #define UMOTOPACKETS_H #include <vector> #include <inttypes.h> #include <cstring> #include <stdexcept> #include "umototypes.h" namespace umoto_interface { const uint16_t REQ_PREAMBLE = 0x6E | (0x70<<8); const uint16_t RESP_PREAMBLE = 0xA1 | (0xA2<<8); const uint8_t UMotoControlPacketID = 1; const uint8_t UMotoDataPacketID = 1; const uint8_t UMotoVersionRequestPacketID = 16; class PacketHandler { public: template<typename UMotoPacket> static std::vector<uint8_t> serialize(const UMotoPacket& packet) { std::vector<uint8_t> bytes; bytes.assign(reinterpret_cast<const uint8_t*>(&packet), reinterpret_cast<const uint8_t*>(&packet) + sizeof(packet)); return bytes; } template<typename UMotoPacket> static UMotoPacket deserialize(const std::vector<uint8_t>& raw_data) { UMotoPacket packet; if (raw_data.size()==sizeof(packet)) { std::memcpy(&packet, raw_data.data(), sizeof(packet)); } else { throw std::range_error("Message deserialization error: raw_data length mismatch"); } return packet; } template<typename UMotoPacket> static uint16_t calcCRC(const UMotoPacket* packet) { const uint8_t CRC16_Hi[] = { 0x00, 0xc0, 0xc1, 0x01, 0xc3, 0x03, 0x02, 0xc2, 0xc6, 0x06, 0x07, 0xc7, 0x05, 0xc5, 0xc4, 0x04, 0xcc, 0x0c, 0x0d, 0xcd, 0x0f, 0xcf, 0xce, 0x0e, 0x0a, 0xca, 0xcb, 0x0b, 0xc9, 0x09, 0x08, 0xc8, 0xd8, 0x18, 0x19, 0xd9, 0x1b, 0xdb, 0xda, 0x1a, 0x1e, 0xde, 0xdf, 0x1f, 0xdd, 0x1d, 0x1c, 0xdc, 0x14, 0xd4, 0xd5, 0x15, 0xd7, 0x17, 0x16, 0xd6, 0xd2, 0x12, 0x13, 0xd3, 0x11, 0xd1, 0xd0, 0x10, 0xf0, 0x30, 0x31, 0xf1, 0x33, 0xf3, 0xf2, 0x32, 0x36, 0xf6, 0xf7, 0x37, 0xf5, 0x35, 0x34, 0xf4, 0x3c, 0xfc, 0xfd, 0x3d, 0xff, 0x3f, 0x3e, 0xfe, 0xfa, 0x3a, 0x3b, 0xfb, 0x39, 0xf9, 0xf8, 0x38, 0x28, 0xe8, 0xe9, 0x29, 0xeb, 0x2b, 0x2a, 0xea, 0xee, 0x2e, 0x2f, 0xef, 0x2d, 0xed, 0xec, 0x2c, 0xe4, 0x24, 0x25, 0xe5, 0x27, 0xe7, 0xe6, 0x26, 0x22, 0xe2, 0xe3, 0x23, 0xe1, 0x21, 0x20, 0xe0, 0xa0, 0x60, 0x61, 0xa1, 0x63, 0xa3, 0xa2, 0x62, 0x66, 0xa6, 0xa7, 0x67, 0xa5, 0x65, 0x64, 0xa4, 0x6c, 0xac, 0xad, 0x6d, 0xaf, 0x6f, 0x6e, 0xae, 0xaa, 0x6a, 0x6b, 0xab, 0x69, 0xa9, 0xa8, 0x68, 0x78, 0xb8, 0xb9, 0x79, 0xbb, 0x7b, 0x7a, 0xba, 0xbe, 0x7e, 0x7f, 0xbf, 0x7d, 0xbd, 0xbc, 0x7c, 0xb4, 0x74, 0x75, 0xb5, 0x77, 0xb7, 0xb6, 0x76, 0x72, 0xb2, 0xb3, 0x73, 0xb1, 0x71, 0x70, 0xb0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9c, 0x5c, 0x5d, 0x9d, 0x5f, 0x9f, 0x9e, 0x5e, 0x5a, 0x9a, 0x9b, 0x5b, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4b, 0x8b, 0x8a, 0x4a, 0x4e, 0x8e, 0x8f, 0x4f, 0x8d, 0x4d, 0x4c, 0x8c, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40 }; const uint8_t CRC16_Lo[] = { 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40 }; uint8_t Temp, CRCHi = 0xFF, CRCLo = 0xFF; const uint8_t *ptr = (const uint8_t*)packet; for (unsigned int Index = sizeof(packet->header.preamble); Index<sizeof(*packet)-sizeof(packet->CRC); Index++) { Temp = CRC16_Lo[ptr[Index]^CRCLo]^CRCHi; CRCHi = CRC16_Hi[ptr[Index]^CRCLo]; CRCLo = Temp; } return (((CRCHi << 8) + CRCLo)); } }; #pragma pack(push) #pragma pack(1) template<typename T, uint16_t Preamble, uint8_t TypeID> struct UMotoPacket { struct Header { uint16_t preamble = Preamble; uint8_t unimoto_num = 0; uint8_t type_id = TypeID; uint8_t data_length = sizeof(data_field); } header; T data_field; uint16_t CRC = 0; UMotoPacket(const T& data) : data_field(data), CRC(PacketHandler::calcCRC(this)) { } UMotoPacket() { } }; #pragma pack(pop) typedef UMotoPacket<UMotoControl, REQ_PREAMBLE, UMotoControlPacketID> UMotoControlPacket; typedef UMotoPacket<UMotoData, RESP_PREAMBLE, UMotoDataPacketID> UMotoDataPacket; typedef UMotoPacket<UMotoVersion, REQ_PREAMBLE, UMotoVersionRequestPacketID> UMotoVersionRequestPacket; } #endif // UMOTOPACKETS_H
avrora-robotics/ur_hardware_driver
src/ur_hardware_driver_config.h
<gh_stars>1-10 #ifndef UR_HARDWARE_DRIVER_CONFIG_H #define UR_HARDWARE_DRIVER_CONFIG_H /** ATTENTION This file was generated from the config file ur_hardware_driver_config.yaml and contains set of _default_ parameters. DO NOT DARE TO EDIT ANY OF THIS */ #include "ros/ros.h" class UrHardwareDriverConfig { public: void init() { ros::NodeHandle parameter_node_handle("~"); parameter_node_handle.param<double>("steering_enc_coeff", steering_enc_coeff, 0.00390625); parameter_node_handle.param<double>("steering_zero_offset", steering_zero_offset, 0.0); parameter_node_handle.param<std::string>("umoto_ip", umoto_ip, "192.168.1.190"); parameter_node_handle.param<int>("umoto_port", umoto_port, 20000); parameter_node_handle.param<double>("velocity_enc_coeff", velocity_enc_coeff, 0.0009765625); } double steering_enc_coeff = 0.00390625; double steering_zero_offset = 0.0; std::string umoto_ip = "192.168.1.190"; int umoto_port = 20000; double velocity_enc_coeff = 0.0009765625; }; extern UrHardwareDriverConfig ur_hardware_driver_config; #endif
rafaello7/nanopi-load
main.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <libusb.h> #include <errno.h> #include <unistd.h> #include "s5p_usb.h" #include "s5p_boot.h" #define BUF_MAX (50 * 1024 * 1024) #define MIN(A, B) (((A) < (B)) ? (A) : (B)) typedef unsigned char uint8; typedef unsigned int uint32; static unsigned char mem[BUF_MAX]; static void write32LE(uint8 *addr, uint32 data) { addr[0] = (uint8)(data & 0xff); addr[1] = (uint8)((data >> 8) & 0xff); addr[2] = (uint8)((data >> 16) & 0xff); addr[3] = (uint8)((data >> 24) & 0xff); } static unsigned read32LE(const uint8 *addr) { return addr[0] + (addr[1] << 8) + (addr[2] << 16) + (addr[3] << 24); } static void initBootloaderHeader(uint8 *buf, int is64bitBoot, unsigned size, unsigned loadAddr, unsigned launchAddr, int bootMethod) { static const unsigned arm64bootcode[15] = { 0xE59F0030, // ldr r0, =0xc0011000 0xE590113C, // ldr r1, [r0, #0x13c] 0xE3811A0F, // orr r1, r1, #0xf000 0xE580113C, // str r1, [r0, #0x13c] 0xE59F1024, // ldr r1, =#0x3fffc080 @ launchAddr >> 2 0xE5801140, // str r1, [r0, #0x140] 0xE5101D54, // ldr r1, [r0, #-0xd54] @ 0cx00102ac 0xE3811001, // orr r1, r1, #1 0xE5001D54, // str r1, [r0, #-0xd54] @ 0cx00102ac 0xE5901138, // ldr r1, [r0, #0x138] 0xE381160F, // orr r1, r1, #0xf00000 0xE5801138, // str r1, [r0, #0x138] 0xE320F003, // wfi 0xEAFFFFFE, // b . 0xC0011000 }; unsigned i; if( is64bitBoot ) { for(i = 0; i < sizeof(arm64bootcode) / sizeof(arm64bootcode[0]); ++i) write32LE(buf + 4 * i, arm64bootcode[i]); write32LE(buf + 4 * i, launchAddr >> 2); launchAddr = loadAddr; // launch the CPU reset } write32LE(buf + 0x44, size); // load size write32LE(buf + 0x48, loadAddr); // load address write32LE(buf + 0x4c, launchAddr); // launch address if( bootMethod >= 0 ) buf[0x57] = bootMethod; memcpy(buf + 0x1fc, "NSIH", 4); // signature } static int checkBootloaderHeader(uint8 *buf, unsigned readSize, int isVerbose, int fixSize, int bootMethod) { static const char bootMethods[][6] = { "USB", "SPI", "NAND", "SDMMC", "SDFS" }; unsigned size; int res = !fixSize; unsigned headerSize, sizeOffset, loadAddrOffset, launchAddrOffset; headerSize = 512; sizeOffset = 0x44; loadAddrOffset = 0x48; launchAddrOffset = 0x4c; if( readSize >= headerSize ) { if( !memcmp(buf + 0x1fc, "NSIH", 4) ) { size = read32LE(buf + sizeOffset); if( fixSize ) write32LE(buf + sizeOffset, readSize - headerSize); if( bootMethod >= 0 ) buf[0x57] = bootMethod; if( isVerbose ) { printf("Boot Header:\n"); printf(" size: %u ", size); if( size == readSize - headerSize ) printf("(OK)\n"); else{ printf("(real: %u%s)\n", readSize - headerSize, fixSize ? ", fixed" : ""); } printf(" load address: 0x%x\n", read32LE(buf + loadAddrOffset)); printf(" launch address: 0x%x\n", read32LE(buf + launchAddrOffset)); bootMethod = ((unsigned char*)buf)[0x57]; printf(" boot method: %d (%s)\n", bootMethod, bootMethod < 5 ? bootMethods[bootMethod] : "unknown"); printf(" signature: OK\n"); }else{ if( !fixSize && size != readSize - headerSize ) { printf("warning: wrong load size in header: %u, real: %u\n", size, readSize - headerSize); } } res = 1; }else{ printf("%s: bad signature in header\n", fixSize ? "error" : "warning"); } }else{ printf("%s: read data size (%u) is less than boot header size\n", fixSize ? "error" : "warning", readSize); } return res; } static int readBin(uint8 *buf, unsigned bufsize, const char *filepath, int isEnv) { enum { BUF_PADDING = 16 }; FILE *fin; int size; if( !strcmp(filepath, "-") ) fin = stdin; else{ fin = fopen(filepath, "rb"); if (fin == NULL) { printf("unable to open %s: %s\n", filepath, strerror(errno)); return -1; } } size = fread(buf, 1, bufsize, fin); if( fin != stdin ) fclose(fin); if(size < 0) { fprintf(stderr, "fread: %s\n", strerror(errno)); return size; } if( isEnv && (unsigned)size < bufsize ) buf[size++] = '\0'; // Pad size to be a multiple of BUF_PADDING bytes if( BUF_PADDING > 1 ) size = ((size - 1) | (BUF_PADDING - 1)) + 1; return size; } static int hotplug_callback_attach(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data) { (void)ctx; // unused (void)event; // unused libusb_device_handle **dev_handle_ptr = user_data; int ret; ret = libusb_open(dev, dev_handle_ptr); if( LIBUSB_SUCCESS != ret ) { fprintf(stderr, "libusb_open: %s\n", libusb_strerror(ret)); return 0; } return 1; } static int device_open(libusb_context *ctx, libusb_device_handle **dev_handle_ptr, int isVerbose) { libusb_hotplug_callback_handle hp; int ret; if( isVerbose ) printf("Waiting for device to be available...\n"); ret = libusb_hotplug_register_callback(ctx, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED, LIBUSB_HOTPLUG_ENUMERATE, S5P6818_VID, S5P6818_PID, LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback_attach, (void *)dev_handle_ptr, &hp); if( LIBUSB_SUCCESS != ret ) { fprintf(stderr, "libusb_hotplug_register_callback: %s\n", libusb_strerror(ret)); return ret; } while( NULL == *dev_handle_ptr ) { ret = libusb_handle_events(ctx); if( LIBUSB_SUCCESS != ret ) { fprintf(stderr, "libusb_handle_events: %s\n", libusb_strerror(ret)); } } if( isVerbose ) printf("Device opened.\n"); libusb_hotplug_deregister_callback(ctx, hp); return LIBUSB_SUCCESS; } static int usbBoot(uint8 *buf, int size, int isVerbose) { enum { TRANSFER_CHUNK = 1024 * 1024, TRANSFER_TIMEOUT_MS = 10000 }; libusb_context *ctx; libusb_device_handle *dev_handle = NULL; int ret, boot_ret = 1; int transferred, remain; ret = libusb_init(&ctx); if( LIBUSB_SUCCESS != ret ) { fprintf(stderr, "libusb_init: %s\n", libusb_strerror(ret)); return 1; } ret = device_open(ctx, &dev_handle, isVerbose); if( LIBUSB_SUCCESS == ret ) { ret = libusb_claim_interface(dev_handle, S5P6818_INTERFACE); if( LIBUSB_SUCCESS == ret ) { if( isVerbose ) printf("Start transfer, size=%d\n", size); remain = size; while( remain > 0 ) { ret = libusb_bulk_transfer(dev_handle, S5P6818_EP_OUT, buf, MIN(remain, TRANSFER_CHUNK), &transferred, TRANSFER_TIMEOUT_MS); if( LIBUSB_SUCCESS != ret ) break; buf += transferred; remain -= transferred; } if( LIBUSB_SUCCESS == ret ) { if( isVerbose ) printf("Finish transfer, transferred=%d\n", size); boot_ret = 0; }else{ fprintf(stderr, "libusb_bulk_transfer: %s\n", libusb_strerror(ret)); } libusb_release_interface(dev_handle, 0); }else{ fprintf(stderr, "libusb_claim_interface: %s\n", libusb_strerror(ret)); } }else{ fprintf(stderr, "device_open failed: %s\n", libusb_strerror(ret)); } libusb_close(dev_handle); libusb_exit(ctx); return boot_ret; } static int outTofile(const char *fname, const unsigned char *data, unsigned size) { FILE *fp; int wr; if( !strcmp(fname, "-") ) fp = stdout; else{ fp = fopen(fname, "w"); if( fp == NULL ) { perror(fname); return 1; } } while( size ) { if( (wr = fwrite(data, 1, size, fp)) < 0 ) { perror("fwrite"); break; } data += wr; size -= wr; } if( fp != stdout ) fclose(fp); return size != 0; } static void usage(void) { printf("\n" "usage: nanopi-load [options...] <bootloader.bin> [<loadaddr> [<startaddr>]]\n" "\n" "options:\n" " -b <num> - write the value at \"boot method\" offset (0x57) in NSIH header\n" " -c - dry run (implies -v)\n" " -e - pad data with at least one '\\0' byte (for env to import)\n" " -f - fix load size in Boot Header\n" " -h - print this help\n" " -o <file> - output result to file instead of upload\n" " -v - be verbose\n" " -x - add code for iROMBOOT to Boot Header that switches to 64-bit\n" "\n" "If <loadaddr> is specified, image is prepended with 512-byte Boot Header\n" "If <startaddr> is not specified, assume <loadaddr> + 0x200\n" "If <bootloader.bin> is \"-\", stdin is read\n" "\n"); } int main(int argc, char *argv[]) { int offset, size, opt; int is64bitBoot = 0, dryRun = 0, isVerbose = 0, fixSize = 0; int bootMethod = -1, isEnv = 0; unsigned int load_addr; unsigned int launch_addr; const char *infile = NULL, *outfile = NULL; if( argc == 1 ) { usage(); return 0; } while( (opt = getopt(argc, argv, "b:cefho:vx")) > 0 ) { switch( opt ) { case 'b': bootMethod = strtoul(optarg, NULL, 0); break; case 'c': dryRun = 1; isVerbose = 1; break; case 'e': isEnv = 1; break; case 'f': fixSize = 1; break; case 'h': usage(); return 0; case 'o': outfile = optarg; break; case 'v': isVerbose = 1; break; case 'x': is64bitBoot = 1; break; case '?': return 1; } } if( argc == optind ) { printf("error: input file not provided\n"); return 1; } infile = argv[optind++]; offset = argc == optind ? 0 : 0x200; memset(mem, 0, offset); size = readBin(mem + offset, sizeof(mem) - offset, infile, isEnv); if( size < 0 ) return 1; if( argc > optind ) { load_addr = strtoul(argv[optind++], NULL, 16); launch_addr = load_addr + offset; if( argc > optind ) launch_addr = strtoul(argv[optind], NULL, 16); initBootloaderHeader(mem, is64bitBoot, size, load_addr, launch_addr, bootMethod); if( isVerbose ) { printf("Added Boot Header: load=0x%x, launch=0x%x size=%u%s\n", load_addr, launch_addr, size, is64bitBoot ? " 64-bit" : ""); } size += offset; offset = 0; }else{ if( ! checkBootloaderHeader(mem, size, isVerbose, fixSize, bootMethod) ) return 1; } if( dryRun ) return 0; if( outfile ) { return outTofile(outfile, mem, size); } return usbBoot(mem, size, isVerbose); }
cnlohr/ws2812esp8266
user/user_main.c
<gh_stars>100-1000 #include "mem.h" #include "c_types.h" #include "user_interface.h" #include "ets_sys.h" #include "driver/uart.h" #include "osapi.h" #include "espconn.h" #include "mystuff.h" #define PORT 7777 #define SERVER_TIMEOUT 1500 #define MAX_CONNS 5 #define MAX_FRAME 2000 #define procTaskPrio 0 #define procTaskQueueLen 1 static volatile os_timer_t some_timer; static struct espconn *pUdpServer; void user_rf_pre_init(void) { //nothing. } char * strcat( char * dest, char * src ) { return strcat(dest, src ); } //Tasks that happen all the time. os_event_t procTaskQueue[procTaskQueueLen]; static uint8_t printed_ip = 0; static void ICACHE_FLASH_ATTR procTask(os_event_t *events) { system_os_post(procTaskPrio, 0, 0 ); if( events->sig == 0 && events->par == 0 ) { //Idle Event. struct station_config wcfg; char stret[256]; char *stt = &stret[0]; struct ip_info ipi; int stat = wifi_station_get_connect_status(); // printf( "STAT: %d\n", stat ); if( stat == STATION_WRONG_PASSWORD || stat == STATION_NO_AP_FOUND || stat == STATION_CONNECT_FAIL ) { wifi_set_opmode_current( 2 ); stt += ets_sprintf( stt, "Connection failed: %d\n", stat ); uart0_sendStr(stret); } if( stat == STATION_GOT_IP && !printed_ip ) { wifi_station_get_config( &wcfg ); wifi_get_ip_info(0, &ipi); stt += ets_sprintf( stt, "STAT: %d\n", stat ); stt += ets_sprintf( stt, "IP: %d.%d.%d.%d\n", (ipi.ip.addr>>0)&0xff,(ipi.ip.addr>>8)&0xff,(ipi.ip.addr>>16)&0xff,(ipi.ip.addr>>24)&0xff ); stt += ets_sprintf( stt, "NM: %d.%d.%d.%d\n", (ipi.netmask.addr>>0)&0xff,(ipi.netmask.addr>>8)&0xff,(ipi.netmask.addr>>16)&0xff,(ipi.netmask.addr>>24)&0xff ); stt += ets_sprintf( stt, "GW: %d.%d.%d.%d\n", (ipi.gw.addr>>0)&0xff,(ipi.gw.addr>>8)&0xff,(ipi.gw.addr>>16)&0xff,(ipi.gw.addr>>24)&0xff ); stt += ets_sprintf( stt, "WCFG: /%s/%s/\n", wcfg.ssid, wcfg.password ); uart0_sendStr(stret); printed_ip = 1; } } } //Timer event. static void ICACHE_FLASH_ATTR myTimer(void *arg) { uart0_sendStr("."); } //Called when new packet comes in. static void ICACHE_FLASH_ATTR udpserver_recv(void *arg, char *pusrdata, unsigned short len) { struct espconn *pespconn = (struct espconn *)arg; uint8_t buffer[MAX_FRAME]; //Seems to be optional, still can cause crashes. ets_wdt_disable(); WS2812OutBuffer( pusrdata, len ); ets_sprintf( buffer, "%03x", len ); uart0_sendStr(buffer); } void ICACHE_FLASH_ATTR charrx( uint8_t c ) { //Called from UART. } void user_init(void) { uart_init(BIT_RATE_115200, BIT_RATE_115200); int wifiMode = wifi_get_opmode(); uart0_sendStr("\r\nCustom Server\r\n"); wifi_set_opmode( 2 ); //We broadcast our ESSID, wait for peopel to join. /* struct station_config stationConf; wifi_set_opmode( 1 ); //We broadcast our ESSID, wait for peopel to join. os_memcpy(&stationConf.ssid, "xxx", ets_strlen( "xxx" ) + 1); os_memcpy(&stationConf.password, "<PASSWORD>", ets_strlen( "yyy" ) + 1); wifi_set_opmode( 1 ); wifi_station_set_config(&stationConf); wifi_station_connect();**/ pUdpServer = (struct espconn *)os_zalloc(sizeof(struct espconn)); ets_memset( pUdpServer, 0, sizeof( struct espconn ) ); espconn_create( pUdpServer ); pUdpServer->type = ESPCONN_UDP; pUdpServer->proto.udp = (esp_udp *)os_zalloc(sizeof(esp_udp)); pUdpServer->proto.udp->local_port = 7777; espconn_regist_recvcb(pUdpServer, udpserver_recv); /* wifi_station_dhcpc_start(); */ if( espconn_create( pUdpServer ) ) { while(1) { uart0_sendStr( "\r\nFAULT\r\n" ); } } char outbuffer[] = { 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,0xff,0xff, 0x00,0xff,0x00 }; WS2812OutBuffer( outbuffer, 1 ); //Initialize the output. //Add a process system_os_task(procTask, procTaskPrio, procTaskQueue, procTaskQueueLen); uart0_sendStr("\r\nBooting\r\n"); WS2812OutBuffer( outbuffer, sizeof(outbuffer) ); //Timer example os_timer_disarm(&some_timer); os_timer_setfn(&some_timer, (os_timer_func_t *)myTimer, NULL); os_timer_arm(&some_timer, 100, 1); system_os_post(procTaskPrio, 0, 0 ); }
cnlohr/ws2812esp8266
top/top.c
<filename>top/top.c<gh_stars>100-1000 #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <math.h> int sockfd; struct sockaddr_in servaddr; unsigned long HSVtoHEX( float hue, float sat, float value ) { float pr = 0; float pg = 0; float pb = 0; short ora = 0; short og = 0; short ob = 0; float ro = fmod( hue * 6, 6. ); float avg = 0; ro = fmod( ro + 6 + 1, 6 ); //Hue was 60* off... if( ro < 1 ) //yellow->red { pr = 1; pg = 1. - ro; } else if( ro < 2 ) { pr = 1; pb = ro - 1.; } else if( ro < 3 ) { pr = 3. - ro; pb = 1; } else if( ro < 4 ) { pb = 1; pg = ro - 3; } else if( ro < 5 ) { pb = 5 - ro; pg = 1; } else { pg = 1; pr = ro - 5; } //Actually, above math is backwards, oops! pr *= value; pg *= value; pb *= value; avg += pr; avg += pg; avg += pb; pr = pr * sat + avg * (1.-sat); pg = pg * sat + avg * (1.-sat); pb = pb * sat + avg * (1.-sat); ora = pr * 255; og = pb * 255; ob = pg * 255; if( ora < 0 ) ora = 0; if( ora > 255 ) ora = 255; if( og < 0 ) og = 0; if( og > 255 ) og = 255; if( ob < 0 ) ob = 0; if( ob > 255 ) ob = 255; return (ob<<16) | (og<<8) | ora; } int main( int argc, char ** argv ) { int firstoverride = -1; if( argc < 2 ) { fprintf( stderr, "Error: usage: [tool] [ip address] [optional: no of lights] [optional (if present, first override (i.e. white on some systems))]\n" ); return -1; } uint32_t frame = 0; sockfd=socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr=inet_addr(argv[1]); servaddr.sin_port=htons(7777); int lights = 186; if( argc >= 3 ) { lights = atoi( argv[2] ); } if( argc >= 4 ) { firstoverride = atoi( argv[3] ); } printf( "Lights: %d\n", lights ); while(1) { //#define lights 186 uint8_t buffer[lights*3]; int i; for( i = 0; i < lights; i++ ) { //#define BEAT uint32_t hex; //For button // hex = (i == (frame % lights))?0xFFFFFF:0x000000; // hex=0xffffff; // hex = HSVtoHEX( i*(1/12.) + frame*(1./48.), 1, 1.0 ); // hex = (((frame+i)%lights)>(lights-2))?0xffffff:0; //The worm. hex = HSVtoHEX( i*.03 - frame*.04, 1, (((((-i<<3)%256) - ((frame<<3)%256)+256)%256) ) /256.0*0.9-0.1); //Long, smooth, transitioning. 1.0 //For wall art. // hex = 0x404040; hex = HSVtoHEX( i*.05 + frame*.01, 1, 1.0 ); //0.50 = overload. 0.45 = overheat? =0.40 = HOT // hex = (((frame+i)%186)>160)?0xff8f8f:0; //The worm. // hex = (((frame+i)%186)>130)?0x0000ff:0; //The red worm. // hex = HSVtoHEX( i*.005 - frame*.001, 1, ((((-i%256) - ((frame>>1)%256)+256)%256) ) /256.0*1.2-0.1); // hex = HSVtoHEX( i*.00500 + ((int)(frame*0.42))*.17, 1, 0.40 ); //Fiesta //and my favorite: // hex = HSVtoHEX( i*.001 - frame*.001, 1, ((((i%256) - ((frame>>1)%256)+256)%256) ) /256.0*1.5-0.1); //Long, smooth, transitioning. 1.0 overloads. Trying 0.9. If 0.9 works, should back off. // hex = HSVtoHEX( i*0.005376344 - frame*.001, 1.3, 1.0); //Long, smooth, transitioning. full-brigth //Chaser // hex = HSVtoHEX( i*.002 + frame*.002, 4, 1.0 ); //0.50 = overload. 0.45 = overheat? =0.40 = HOT // hex = HSVtoHEX( frame*.001, 1.0, 1.0); //Long, smooth, transitioning. full-brigth // hex = 0x0000ff; // hex = HSVtoHEX( i * 0.0002+.3333, 1, 1.0 ); buffer[0+i*3] = (hex>>8); buffer[1+i*3] = (hex); buffer[2+i*3] = (hex>>16); } if( firstoverride >= 0 ) buffer[0] = firstoverride; #ifdef BEAT for( i = 0; i < 4;i ++ ) { uint32_t hex = ((-frame % 48)+48)*256/48;//((frame %48) == 0)?0xffffff:0x000000; hex |= hex<<8 | hex<<16; buffer[0+i*3] = (hex>>8); buffer[1+i*3] = (hex); buffer[2+i*3] = (hex>>16); } #endif sendto(sockfd,buffer,sizeof(buffer),0, (struct sockaddr *)&servaddr,sizeof(servaddr)); frame++; printf( "." ); fflush( stdout ); usleep(14000); } }
cnlohr/ws2812esp8266
user/ws2812.c
#include "ws2812.h" #include "ets_sys.h" #include "mystuff.h" #include "osapi.h" #define GPIO_OUTPUT_SET(gpio_no, bit_value) \ gpio_output_set(bit_value<<gpio_no, ((~bit_value)&0x01)<<gpio_no, 1<<gpio_no,0) //I just used a scope to figure out the right time periods. void SEND_WS_0() { uint8_t time; time = 3; while(time--) WRITE_PERI_REG( PERIPHS_GPIO_BASEADDR + GPIO_ID_PIN(WSGPIO), 1 ); time = 8; while(time--) WRITE_PERI_REG( PERIPHS_GPIO_BASEADDR + GPIO_ID_PIN(WSGPIO), 0 ); } void SEND_WS_1() { uint8_t time; time = 7; while(time--) WRITE_PERI_REG( PERIPHS_GPIO_BASEADDR + GPIO_ID_PIN(WSGPIO), 1 ); time = 5; while(time--) WRITE_PERI_REG( PERIPHS_GPIO_BASEADDR + GPIO_ID_PIN(WSGPIO), 0 ); } void WS2812OutBuffer( uint8_t * buffer, uint16_t length ) { uint16_t i; GPIO_OUTPUT_SET(GPIO_ID_PIN(WSGPIO), 0); ets_intr_lock(); for( i = 0; i < length; i++ ) { uint8_t mask = 0x80; uint8_t byte = buffer[i]; while (mask) { if( byte & mask ) SEND_WS_1(); else SEND_WS_0(); mask >>= 1; } } ets_intr_unlock(); }
cnlohr/ws2812esp8266
user/ws2812.h
#ifndef _WS2812_H #define _WS2812_H #define WSGPIO 0 #include "c_types.h" #include "user_interface.h" #include "ets_sys.h" #include "gpio.h" //You will have to os_intr_lock(); os_intr_unlock(); void WS2812OutBuffer( uint8_t * buffer, uint16_t length ); #endif
ngagesdk/nrpg
src/ngine.h
<gh_stars>1-10 /** @file ngine.h * * N-GINE, a portable game engine which is being developed specifically * for the Nokia N-Gage. * * API definition. * * Copyright (c) 2022, <NAME>. All rights reserved. * SPDX-License-Identifier: MIT * **/ #ifndef NGINE_H #define NGINE_H #include "ngtypes.h" #ifndef FUNCTION_NAME #define FUNCTION_NAME "" #endif status_t ng_init_core(const char* resource_file, const char* title, ngine_t** core); status_t ng_update_core(ngine_t* core); void ng_free_core(ngine_t *core); status_t ng_load_map(const char* map_name, ngine_t* core); void ng_unload_map(ngine_t* core); #endif /* NGINE_H */
ngagesdk/nrpg
src/pfs.c
/** @file pfs.c * * Packed file system implementation. * Adapted version, originally from The Mistral Report: * https://montyontherun.itch.io/the-mistral-report * * Copyright (c) 2019, <NAME>. All rights reserved. * SPDX-License-Identifier: BSD-2-Clause * **/ #include <SDL.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #define kDataPath_MaxLength 256 char mDataPath[kDataPath_MaxLength]; void init_file_reader(const char * dataFilePath) { sprintf (mDataPath, "%s", dataFilePath); } size_t size_of_file(const char * path) { FILE *mDataPack = fopen(mDataPath, "rb"); char buffer[85]; int c; Uint32 size = 0; Uint32 offset = 0; Uint16 entries = 0; fread(&entries, 2, 1, mDataPack); for (c = 0; c < entries; ++c) { uint8_t stringSize = 0; fread(&offset, 4, 1, mDataPack); fread(&stringSize, 1, 1, mDataPack); fread(&buffer, stringSize + 1, 1, mDataPack); if (!strcmp(buffer, path)) { goto found; } } found: if (offset == 0) { printf("failed to load %s\n", path); exit(-1); } fseek(mDataPack, offset, SEEK_SET); fread(&size, 4, 1, mDataPack); fclose(mDataPack); return size; } Uint8 *load_binary_file_from_path(const char * path) { FILE *mDataPack = fopen(mDataPath, "rb"); Uint32 offset = 0; Uint16 entries = 0; char buffer[85]; int c; Uint32 size = 0; Uint8 *toReturn; fread(&entries, 2, 1, mDataPack); for (c = 0; c < entries; ++c) { Uint8 stringSize = 0; fread(&offset, 4, 1, mDataPack); fread(&stringSize, 1, 1, mDataPack); fread(&buffer, stringSize + 1, 1, mDataPack); if (!strcmp(buffer, path)) { goto found; } } found: if (offset == 0) { printf("failed to load %s\n", path); exit(-1); } fseek(mDataPack, offset, SEEK_SET); fread(&size, 4, 1, mDataPack); toReturn = (Uint8 *) malloc(size); fread(toReturn, sizeof(uint8_t), size, mDataPack); fclose(mDataPack); return toReturn; } FILE *open_binary_file_from_path(const char * path) { FILE *mDataPack = fopen(mDataPath, "rb"); Uint32 offset = 0; Uint16 entries = 0; char buffer[85]; int c; Uint32 size = 0; fread(&entries, 2, 1, mDataPack); for (c = 0; c < entries; ++c) { Uint8 stringSize = 0; fread(&offset, 4, 1, mDataPack); fread(&stringSize, 1, 1, mDataPack); fread(&buffer, stringSize + 1, 1, mDataPack); if (!strcmp(buffer, path)) { goto found; } } return NULL; found: if (offset == 0) { printf("failed to load %s\n", path); exit(-1); } fseek(mDataPack, offset, SEEK_SET); fread(&size, 4, 1, mDataPack); return mDataPack; }
ngagesdk/nrpg
src/utils.c
/** @file utils.c * * N-GINE, a portable game engine which is being developed specifically * for the Nokia N-Gage. * * Utility functions. * * Copyright (c) 2022, <NAME>. All rights reserved. * SPDX-License-Identifier: MIT * **/ #include <SDL.h> #include <stb_sprintf.h> #include "ngine.h" static void get_character_position(const unsigned char character, int* pos_x, int* pos_y) { Sint32 index = 0; // If the character is not valid, select space. if ((character < 0x20) || (character > 0x7e)) { index = 0; } else { index = character - 0x20; } *pos_x = (index % 18) * 7; *pos_y = (index / 18) * 9; } SDL_bool bb_do_intersect(const aabb_t bb_a, const aabb_t bb_b) { Sint32 bb_a_x = bb_b.left - bb_a.right; Sint32 bb_a_y = bb_b.top - bb_a.bottom; Sint32 bb_b_x = bb_a.left - bb_b.right; Sint32 bb_b_y = bb_a.top - bb_b.bottom; if (0 < bb_a_x || 0 < bb_a_y) { return SDL_FALSE; } if (0 < bb_b_x || 0 < bb_b_y) { return SDL_FALSE; } return SDL_TRUE; } status_t load_texture_from_file(const char* file_name, SDL_Texture** texture, ngine_t* core) { Uint8* resource_buf; SDL_RWops* resource; SDL_Surface* surface; if (! file_name) { return NG_WARNING; } resource_buf = (Uint8*)load_binary_file_from_path(file_name); if (! resource_buf) { // SDL_Log("Failed to load resource: %s", file_name); return NG_ERROR; } resource = SDL_RWFromConstMem((Uint8*)resource_buf, size_of_file(file_name)); if (! resource) { free(resource_buf); // SDL_Log("Failed to convert resource %s: %s", file_name, SDL_GetError()); return NG_ERROR; } surface = SDL_LoadBMP_RW(resource, SDL_TRUE); if (! surface) { free(resource_buf); // SDL_Log("Failed to load image: %s", SDL_GetError()); return NG_ERROR; } free(resource_buf); if (0 != SDL_SetColorKey(surface, SDL_TRUE, SDL_MapRGB(surface->format, 0xff, 0x00, 0xff))) { // SDL_Log("Failed to set color key for %s: %s", file_name, SDL_GetError()); } if (0 != SDL_SetSurfaceRLE(surface, 1)) { // SDL_Log("Could not enable RLE for surface %s: %s", file_name, SDL_GetError()); } *texture = SDL_CreateTextureFromSurface(core->renderer, surface); if (! *texture) { // SDL_Log("Could not create texture from surface: %s", SDL_GetError()); SDL_FreeSurface(surface); return NG_ERROR; } SDL_FreeSurface(surface); // SDL_Log("Loading image from file: %s.", file_name); return NG_OK; } status_t set_display_text(const char* text, ngine_t* core) { size_t text_length = strlen(text); if (text_length > 144) { text_length = 144; } core->display_text = (unsigned char*)calloc(text_length + 1, sizeof(unsigned char)); if (! core->display_text) { // SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_ERROR; } stbsp_snprintf(core->display_text, text_length + 1, "%s", text); return NG_OK; } void clear_display_text(ngine_t* core) { core->display_text = NULL; } // Error handling: yes or no? void render_text(ngine_t* core) { SDL_Rect textbox = { 0, 144, 176, 64 }; SDL_Rect border_a = { 0, 144, 176, 64 }; SDL_Rect border_b = { 2, 146, 172, 60 }; SDL_Rect src = { 0, 0, 7, 9 }; SDL_Rect dst = { 4, 149, 7, 9 }; int string_index = 0; int col, row; SDL_SetRenderDrawColor(core->renderer, 0xff, 0xff, 0xff, 0x00); SDL_RenderFillRect(core->renderer, &textbox); SDL_RenderDrawRect(core->renderer, &textbox); SDL_SetRenderDrawColor(core->renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderDrawRect(core->renderer, &border_a); SDL_RenderDrawRect(core->renderer, &border_b); for (row = 0; row < 6; row += 1) { dst.x = 4; for (col = 0; col < 24; col += 1) { if ('\0' == core->display_text[string_index]) { goto no_text_left; } get_character_position(core->display_text[string_index], &src.x, &src.y); if (' ' == core->display_text[string_index] && (4 == dst.x)) { dst.x -= 7; col -= 1; } string_index += 1; SDL_RenderCopy(core->renderer, core->font_texture, &src, &dst); dst.x += 7; } dst.y += 9; } no_text_left: }
ngagesdk/nrpg
src/core.c
<reponame>ngagesdk/nrpg /** @file core.c * * N-GINE, a portable game engine which is being developed specifically * for the Nokia N-Gage. * * Engine core implementation. * * Copyright (c) 2022, <NAME>. All rights reserved. * SPDX-License-Identifier: MIT * **/ #include <SDL.h> #include "ngine.h" #include "ngtypes.h" #define STB_SPRINTF_IMPLEMENTATION #include <stb_sprintf.h> #if defined __SYMBIAN32__ #define CUTE_TILED_SNPRINTF(ARGS...) (void)(ARGS) #define CUTE_TILED_STRTOLL strtol #define CUTE_TILED_STRTOULL strtoul #define STRPOOL_EMBEDDED_STRNICMP strncasecmp #endif #define CUTE_TILED_IMPLEMENTATION #include <cute_tiled.h> #define ANIM_TILE_FPS 15 #define H_anim_fps 0x001ae6d81102fff2 #define H_anim_idle_down_index 0x66ea76e9fc6fd195 #define H_anim_idle_down_len 0x280eca46bcffe9bc #define H_anim_idle_left_index 0x66ebbb28ad663a28 #define H_anim_idle_left_len 0x280eca92f60d118f #define H_anim_idle_right_index 0x44846fb424c8da3b #define H_anim_idle_right_len 0x29e824c6561290e2 #define H_anim_idle_up_index 0x280ecaef820b1782 #define H_anim_idle_up_len 0x534121551546d069 #define H_anim_walk_down_index 0xf4edbbfc5e4b5586 #define H_anim_walk_down_len 0x6a0291af9997bd6d #define H_anim_walk_left_index 0xf4ef003b0f41be19 #define H_anim_walk_left_len 0x6a0291fbd2a4e540 #define H_anim_walk_right_index 0x92f05712c214dc4c #define H_anim_walk_right_len 0xaa54d94ac5a4dab3 #define H_anim_walk_up_index 0x6a0292585ea2eb33 #define H_anim_walk_up_len 0x538cd069ddc403da #define H_display_text 0xd064eba5e9b9b1df #define H_height 0x0000065301d688de #define H_is_player 0x0377cc4478b16e8d #define H_is_solid 0x001ae728dd16b21b #define H_map_down 0x001ae74b4abd8f1a #define H_map_left 0x001ae74b4ac1c56d #define H_map_right 0x0377d0b4a3693ac0 #define H_map_up 0x000006530d3ba847 #define H_objectgroup 0xc0b9d518970be349 #define H_sprite_cols 0xc0d1f24f33052c2c #define H_sprite_id 0x0377d8f6e7994748 #define H_tilelayer 0x0377d9f70e844fb0 #define H_width 0x0000003110a3b0a5 // Could be fun if the engine supports platformer games. #define H_meter_in_pixel 0xfbbc8a6d4a407cf9 #define H_gravity 0x0000d0b30d77f26b Sint32 get_first_gid(cute_tiled_map_t* tiled_map) { return tiled_map->tilesets->firstgid; } cute_tiled_layer_t* get_head_layer(cute_tiled_map_t* tiled_map) { return tiled_map->layers; } SDL_bool is_tiled_layer_of_type(const tiled_layer_type tiled_type, cute_tiled_layer_t* tiled_layer, ngine_t* core) { switch (tiled_type) { case TILE_LAYER: if (core->map->hash_id_tilelayer == tiled_layer->type.hash_id) { return SDL_TRUE; } break; case OBJECT_GROUP: if (core->map->hash_id_objectgroup == tiled_layer->type.hash_id) { return SDL_TRUE; } break; } return SDL_FALSE; } cute_tiled_object_t* get_head_object(cute_tiled_layer_t* tiled_layer, ngine_t* core) { if (is_tiled_layer_of_type(OBJECT_GROUP, tiled_layer, core)) { return tiled_layer->objects; } return NULL; } cute_tiled_tileset_t* get_head_tileset(cute_tiled_map_t* tiled_map) { return tiled_map->tilesets; } Sint32* get_layer_content(cute_tiled_layer_t* tiled_layer) { return (Sint32*)tiled_layer->data; } const char* get_layer_name(cute_tiled_layer_t* tiled_layer) { return tiled_layer->name.ptr; } Sint32 get_layer_property_count(cute_tiled_layer_t* tiled_layer) { return tiled_layer->property_count; } Sint32 get_local_id(Sint32 gid, cute_tiled_map_t* tiled_map) { Sint32 local_id = gid - get_first_gid(tiled_map); return local_id >= 0 ? local_id : 0; } Sint32 get_map_property_count(cute_tiled_map_t* tiled_map) { return tiled_map->property_count; } Sint32 get_next_animated_tile_id(Sint32 gid, Sint32 current_frame, cute_tiled_map_t* tiled_map) { cute_tiled_tileset_t* tileset = get_head_tileset(tiled_map); cute_tiled_tile_descriptor_t* tile = tileset->tiles; while (tile) { if (tile->tile_index == gid) { return tile->animation[current_frame].tileid; } tile = tile->next; } return 0; } const int get_object_uid(cute_tiled_object_t* tiled_object) { return tiled_object->id; } const char* get_object_name(cute_tiled_object_t* tiled_object) { return tiled_object->name.ptr; } Sint32 get_object_property_count(cute_tiled_object_t* tiled_object) { return tiled_object->property_count; } const char* get_object_type_name(cute_tiled_object_t* tiled_object) { return tiled_object->type.ptr; } void get_tile_position(Sint32 gid, Sint32* pos_x, Sint32* pos_y, cute_tiled_map_t* tiled_map) { cute_tiled_tileset_t* tileset = tiled_map->tilesets; Sint32 local_id = get_local_id(gid, tiled_map); *pos_x = (local_id % tileset->columns) * get_tile_width(tiled_map); *pos_y = (local_id / tileset->columns) * get_tile_height(tiled_map); } void get_frame_position(Sint32 frame_index, Sint32 width, Sint32 height, int* pos_x, int* pos_y, Sint32 column_count) { *pos_x = (frame_index % column_count) * width; *pos_y = (frame_index / column_count) * height; } Sint32 get_tile_property_count(cute_tiled_tile_descriptor_t* tiled_tile) { return tiled_tile->property_count; } SDL_bool is_gid_valid(Sint32 gid, cute_tiled_map_t* tiled_map) { if (gid) { return SDL_TRUE; } return SDL_FALSE; } SDL_bool is_tile_animated(Sint32 gid, Sint32* animation_length, Sint32* id, cute_tiled_map_t* tiled_map) { Sint32 local_id = get_local_id(gid, tiled_map); cute_tiled_tileset_t* tileset = tiled_map->tilesets; cute_tiled_tile_descriptor_t* tile = tileset->tiles; while (tile) { if (tile->tile_index == local_id) { if (tile->animation) { if (animation_length) { *animation_length = tile->frame_count; } if (id) { *id = tile->animation->tileid; } return SDL_TRUE; } } tile = tile->next; } return SDL_FALSE; } Sint32 remove_gid_flip_bits(Sint32 gid) { return cute_tiled_unset_flags(gid); } SDL_bool tile_has_properties(Sint32 gid, cute_tiled_tile_descriptor_t** tile, cute_tiled_map_t* tiled_map) { Sint32 local_id; local_id = gid - get_first_gid(tiled_map); while ((*tile)) { if ((*tile)->tile_index == local_id) { if (0 < (*tile)->property_count) { return SDL_TRUE; } } (*tile) = (*tile)->next; } return SDL_FALSE; } /* djb2 by <NAME> * http://www.cse.yorku.ca/~oz/hash.html */ Uint64 generate_hash(const unsigned char* name) { Uint64 hash = 5381; Uint32 c; while ((c = *name++)) { hash = ((hash << 5) + hash) + c; } return hash; } void load_property(const Uint64 name_hash, cute_tiled_property_t* properties, Sint32 property_count, ngine_t* core) { int index = 0; SDL_bool prop_found = SDL_FALSE; for (index = 0; index < property_count; index += 1) { if (name_hash == generate_hash((const unsigned char*)properties[index].name.ptr)) { prop_found = SDL_TRUE; break; } } if (! prop_found) { return; } // Entities are allowed to have no properties. if (0 == property_count) { return; } if (properties[index].name.ptr) { switch (properties[index].type) { case CUTE_TILED_PROPERTY_COLOR: case CUTE_TILED_PROPERTY_FILE: case CUTE_TILED_PROPERTY_NONE: break; case CUTE_TILED_PROPERTY_INT: core->map->integer_property = properties[index].data.integer; break; case CUTE_TILED_PROPERTY_BOOL: core->map->boolean_property = (SDL_bool)properties[index].data.boolean; break; case CUTE_TILED_PROPERTY_FLOAT: core->map->decimal_property = (float)properties[index].data.floating; break; case CUTE_TILED_PROPERTY_STRING: core->map->string_property = properties[index].data.string.ptr; break; } } } status_t create_and_set_render_target(SDL_Texture** target, ngine_t* core) { if (! (*target)) { (*target) = SDL_CreateTexture( core->renderer, SDL_PIXELFORMAT_RGB444, SDL_TEXTUREACCESS_TARGET, 176, 208); } if (! (*target)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } if (0 > SDL_SetRenderTarget(core->renderer, (*target))) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); SDL_DestroyTexture((*target)); return NG_ERROR; } SDL_RenderClear(core->renderer); return NG_OK; } Sint32 get_tile_index(Sint32 pos_x, Sint32 pos_y, ngine_t* core) { Sint32 tile_index; tile_index = pos_x / get_tile_width(core->map->handle); tile_index += (pos_y / get_tile_height(core->map->handle)) * core->map->handle->width; if (tile_index > (core->map->tile_desc_count - 1)) { tile_index = core->map->tile_desc_count - 1; } return tile_index; } void unload_tiled_map(ngine_t* core) { core->map->hash_id_objectgroup = 0; core->map->hash_id_tilelayer = 0; if (core->map->handle) { cute_tiled_free_map(core->map->handle); } } SDL_bool is_map_loaded(ngine_t* core) { return core->is_map_loaded; } int get_tile_width(cute_tiled_map_t* tiled_map) { return tiled_map->tilesets->tilewidth; } int get_tile_height(cute_tiled_map_t* tiled_map) { return tiled_map->tilesets->tileheight; } SDL_bool get_boolean_map_property(const Uint64 name_hash, ngine_t* core) { Sint32 prop_cnt; if (! is_map_loaded(core)) { return SDL_FALSE; } prop_cnt = get_map_property_count(core->map->handle); core->map->boolean_property = SDL_FALSE; load_property(name_hash, core->map->handle->properties, prop_cnt, core); return core->map->boolean_property; } float get_decimal_map_property(const Uint64 name_hash, ngine_t* core) { Sint32 prop_cnt; if (! is_map_loaded(core)) { return 0.0; } prop_cnt = get_map_property_count(core->map->handle); core->map->decimal_property = 0.0; load_property(name_hash, core->map->handle->properties, prop_cnt, core); return core->map->decimal_property; } Sint32 get_integer_map_property(const Uint64 name_hash, ngine_t* core) { Sint32 prop_cnt; if (! is_map_loaded(core)) { return 0; } prop_cnt = get_map_property_count(core->map->handle); core->map->integer_property = 0; load_property(name_hash, core->map->handle->properties, prop_cnt, core); return core->map->integer_property; } const char* get_string_map_property(const Uint64 name_hash, ngine_t* core) { Sint32 prop_cnt; if (! is_map_loaded(core)) { return NULL; } prop_cnt = get_map_property_count(core->map->handle); core->map->string_property = NULL; load_property(name_hash, core->map->handle->properties, prop_cnt, core); return core->map->string_property; } SDL_bool get_boolean_property(const Uint64 name_hash, cute_tiled_property_t* properties, Sint32 property_count, ngine_t* core) { core->map->boolean_property = SDL_FALSE; load_property(name_hash, properties, property_count, core); return core->map->boolean_property; } float get_decimal_property(const Uint64 name_hash, cute_tiled_property_t* properties, Sint32 property_count, ngine_t* core) { core->map->decimal_property = 0.0; load_property(name_hash, properties, property_count, core); return core->map->decimal_property; } int32_t get_integer_property(const Uint64 name_hash, cute_tiled_property_t* properties, Sint32 property_count, ngine_t* core) { core->map->integer_property = 0; load_property(name_hash, properties, property_count, core); return core->map->integer_property; } const char* get_string_property(const Uint64 name_hash, cute_tiled_property_t* properties, Sint32 property_count, ngine_t* core) { core->map->string_property = NULL; load_property(name_hash, properties, property_count, core); return core->map->string_property; } void trigger_action(ngine_t* core) { cute_tiled_layer_t* layer; cute_tiled_object_t* tiled_object = NULL; if (! is_map_loaded(core)) { //SDL_Log("No map has been loaded."); return; } layer = get_head_layer(core->map->handle); while (layer && core->map->entity_count) { if (is_tiled_layer_of_type(OBJECT_GROUP, layer, core)) { Sint32 index = 0; tiled_object = get_head_object(layer, core); while (tiled_object) { cute_tiled_property_t* properties = tiled_object->properties; Sint32 prop_cnt = get_object_property_count(tiled_object); entity_t* entity_a = &core->map->entity[index]; entity_t* entity_b = &core->map->entity[core->map->active_entity - 1]; Sint32 tile_index_a = get_tile_index(entity_a->pos_x, entity_a->pos_y, core); Sint32 tile_index_b = get_tile_index(entity_b->pos_x, entity_b->pos_y, core); if (tile_index_a == tile_index_b) { if (get_string_property(H_display_text, properties, prop_cnt, core)) { set_display_text(core->map->string_property, core); break; } } index += 1; tiled_object = tiled_object->next; } } layer = layer->next; } } status_t load_tiles(ngine_t* core) { cute_tiled_layer_t* layer = get_head_layer(core->map->handle); core->map->tile_desc_count = (Sint32)(core->map->handle->height * core->map->handle->width); if (core->map->tile_desc_count < 0) { return NG_OK; } core->map->tile_desc = (tile_desc_t*)calloc((size_t)core->map->tile_desc_count, sizeof(struct tile_desc)); if (! core->map->tile_desc) { //SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_ERROR; } while (layer) { if (is_tiled_layer_of_type(TILE_LAYER, layer, core)) { Sint32 index_height; Sint32 index_width; for (index_height = 0; index_height < (Sint32)core->map->handle->height; index_height += 1) { for (index_width = 0; index_width < (Sint32)core->map->handle->width; index_width += 1) { cute_tiled_tileset_t* tileset = get_head_tileset(core->map->handle); cute_tiled_tile_descriptor_t* tile = tileset->tiles; Sint32* layer_content = get_layer_content(layer); Sint32 tile_index = (index_height * (Sint32)core->map->handle->width) + index_width; Sint32 gid = remove_gid_flip_bits((Sint32)layer_content[tile_index]); if (tile_has_properties(gid, &tile, core->map->handle)) { Sint32 prop_cnt = get_tile_property_count(tile); if (get_boolean_property(H_is_solid, tile->properties, prop_cnt, core)) { core->map->tile_desc[tile_index].is_solid = SDL_TRUE; } } } } } layer = layer->next; } return NG_OK; } status_t load_tileset(ngine_t* core) { status_t status = NG_OK; char tileset_file_name[16] = { 0 }; stbsp_snprintf(tileset_file_name, 16, "%s", core->map->handle->tilesets->image.ptr); if (NG_OK != load_texture_from_file((const char*)tileset_file_name, &core->map->tileset_texture, core)) { //SDL_Log("%s: Error loading image '%s'.", FUNCTION_NAME, tileset_file_name); status = NG_ERROR; } return status; } status_t load_tiled_map(const char* map_file_name, ngine_t* core) { cute_tiled_layer_t* layer; Uint8* resource_buf; resource_buf = (Uint8*)load_binary_file_from_path(map_file_name); if (! resource_buf) { //SDL_Log("Failed to load resource: %s", map_file_name); return NG_ERROR; } core->map->handle = cute_tiled_load_map_from_memory((const void*)resource_buf, size_of_file(map_file_name), NULL); if (! core->map->handle) { free(resource_buf); //SDL_Log("%s: %s.", FUNCTION_NAME, cute_tiled_error_reason); return NG_WARNING; } free(resource_buf); layer = get_head_layer(core->map->handle); while (layer) { if (H_tilelayer == generate_hash((const unsigned char*)layer->type.ptr) && !core->map->hash_id_tilelayer) { core->map->hash_id_tilelayer = layer->type.hash_id; //SDL_Log("Set hash ID for tile layer: %llu", core->map->hash_id_tilelayer); } else if (H_objectgroup == generate_hash((const unsigned char*)layer->type.ptr) && !core->map->hash_id_objectgroup) { core->map->hash_id_objectgroup = layer->type.hash_id; //SDL_Log("Set hash ID for object group: %llu", core->map->hash_id_objectgroup); } layer = layer->next; } return NG_OK; } status_t load_animated_tiles(ngine_t* core) { cute_tiled_layer_t* layer = get_head_layer(core->map->handle); Sint32 animated_tile_count = 0; Sint32 index_height; Sint32 index_width; while (layer) { if (is_tiled_layer_of_type(TILE_LAYER, layer, core) && layer->visible) { for (index_height = 0; index_height < (Sint32)core->map->handle->height; index_height += 1) { for (index_width = 0; index_width < (Sint32)core->map->handle->width; index_width += 1) { Sint32* layer_content = get_layer_content(layer); Sint32 gid = remove_gid_flip_bits((Sint32)layer_content[(index_height * (Sint32)core->map->handle->width) + index_width]); if (is_tile_animated(gid, NULL, NULL, core->map->handle)) { animated_tile_count += 1; } } } } layer = layer->next; } if (0 >= animated_tile_count) { return NG_OK; } else { core->map->animated_tile = (animated_tile_t*)calloc((size_t)animated_tile_count, sizeof(struct animated_tile)); if (! core->map->animated_tile) { //SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_ERROR; } } //SDL_Log("Load %u animated tile(s).", animated_tile_count); return NG_OK; } status_t load_sprites(ngine_t* core) { status_t status = NG_OK; char property_name[17] = { 0 }; SDL_bool search_is_running = SDL_TRUE; Sint32 prop_cnt = get_map_property_count(core->map->handle); Sint32 index; core->map->sprite_count = 0; while (search_is_running) { stbsp_snprintf(property_name, 17, "sprite_sheet_%u", core->map->sprite_count + 1); if (get_string_property(generate_hash((const unsigned char*)property_name), core->map->handle->properties, prop_cnt, core)) { core->map->sprite_count += 1; } else { search_is_running = SDL_FALSE; } } if (0 == core->map->sprite_count) { return NG_OK; } core->map->sprite = (sprite_t*)calloc((size_t)core->map->sprite_count, sizeof(struct sprite)); if (! core->map->sprite) { //SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_ERROR; } for (index = 0; index < core->map->sprite_count; index += 1) { const char* file_name; stbsp_snprintf(property_name, 17, "sprite_sheet_%u", index + 1); file_name = get_string_property(generate_hash((const unsigned char*)property_name), core->map->handle->properties, prop_cnt, core); if (file_name) { Sint32 source_length = (Sint32)(strlen(file_name) + 1); char* sprite_image_source = (char*)calloc(1, source_length); if (! sprite_image_source) { //SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_ERROR; } stbsp_snprintf(sprite_image_source, source_length, "%s", file_name); core->map->sprite[index].id = index + 1; status = load_texture_from_file(sprite_image_source, &core->map->sprite[index].texture, core); if (NG_OK != status) { free(sprite_image_source); return status; } } } return status; } status_t load_entities(ngine_t* core) { cute_tiled_layer_t* layer = get_head_layer(core->map->handle); cute_tiled_object_t* tiled_object = NULL; if (core->map->entity_count) { /* Nothing else to do here. */ return NG_OK; } while (layer) { if (is_tiled_layer_of_type(OBJECT_GROUP, layer, core)) { tiled_object = get_head_object(layer, core); while (tiled_object) { core->map->entity_count += 1; tiled_object = tiled_object->next; } } layer = layer->next; } if (core->map->entity_count) { core->map->entity = (entity_t*)calloc((size_t)core->map->entity_count, sizeof(struct entity)); if (! core->map->entity) { //SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_ERROR; } } //SDL_Log("Load %u entities:", core->map->entity_count); layer = get_head_layer(core->map->handle); while (layer) { if (is_tiled_layer_of_type(OBJECT_GROUP, layer, core)) { Sint32 index = 0; tiled_object = get_head_object(layer, core); while (tiled_object) { entity_t* entity = &core->map->entity[index]; cute_tiled_property_t* properties = tiled_object->properties; Sint32 prop_cnt = get_object_property_count(tiled_object); entity->handle = tiled_object; entity->state = S_DOWN | S_IDLE; entity->pos_x = (Sint32)tiled_object->x; entity->pos_y = (Sint32)tiled_object->y; entity->uid = (Sint32)get_object_uid(tiled_object); entity->id = (Sint32)index + 1; entity->width = (Sint32)get_integer_property(H_width, properties, prop_cnt, core); entity->height = (Sint32)get_integer_property(H_height, properties, prop_cnt, core); entity->sprite_id = (Sint32)get_integer_property(H_sprite_id, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)1; entity->animation.fps = (Sint32)0; entity->animation.length = (Sint32)0; entity->animation.offset_y = (Sint32)1; if (entity->width <= 0) { entity->width = get_tile_width(core->map->handle); } if (entity->height <= 0) { entity->width = get_tile_height(core->map->handle); } if (get_boolean_property(H_is_player, properties, prop_cnt, core)) { core->map->active_entity = entity->id; core->camera.is_locked = SDL_TRUE; } index += 1; tiled_object = tiled_object->next; } } layer = layer->next; } return NG_OK; } status_t load_font(ngine_t* core) { status_t status = NG_OK; if (NG_OK != load_texture_from_file((const char*)"font.bmp", &core->font_texture, core)) { //SDL_Log("%s: Error loading image '%s'.", FUNCTION_NAME, tileset_file_name); status = NG_ERROR; } clear_display_text(core); return status; } status_t render_scene(ngine_t* core) { cute_tiled_layer_t* layer; Sint32 index; if (! core->is_map_loaded) { return NG_OK; } // Update and render animated tiles. core->map->time_since_last_anim_frame += core->time_since_last_frame; if (0 < core->map->animated_tile_index && core->map->time_since_last_anim_frame >= (Uint32)(1000 / ANIM_TILE_FPS)) { core->map->time_since_last_anim_frame = 0; if (0 > SDL_SetRenderTarget(core->renderer, core->map->layer_texture)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } for (index = 0; core->map->animated_tile_index > index; index += 1) { cute_tiled_tileset_t* tileset; Sint32 gid = core->map->animated_tile[index].gid; Sint32 next_tile_id = 0; Sint32 local_id; SDL_Rect dst = { 0 }; SDL_Rect src = { 0 }; local_id = core->map->animated_tile[index].id + 1; tileset = get_head_tileset(core->map->handle); src.w = dst.w = get_tile_width(core->map->handle); src.h = dst.h = get_tile_height(core->map->handle); dst.x = core->map->animated_tile[index].dst_x; dst.y = core->map->animated_tile[index].dst_y; get_tile_position(local_id, (Uint32*)&src.x, (Uint32*)&src.y, core->map->handle); if (0 > SDL_RenderCopy(core->renderer, core->map->tileset_texture, &src, &dst)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } core->map->animated_tile[index].current_frame += 1; if (core->map->animated_tile[index].current_frame >= core->map->animated_tile[index].animation_length) { core->map->animated_tile[index].current_frame = 0; } next_tile_id = get_next_animated_tile_id(gid, core->map->animated_tile[index].current_frame, core->map->handle); core->map->animated_tile[index].id = next_tile_id; } } if (NG_OK != create_and_set_render_target(&core->render_target, core)) { return NG_ERROR; } layer = get_head_layer(core->map->handle); // Texture has already been rendered. if (core->map->layer_texture) { Sint32 render_pos_x = 0 - core->camera.pos_x; Sint32 render_pos_y = 0 - core->camera.pos_y; SDL_Rect dst = { (Sint32)render_pos_x, (Sint32)render_pos_y, (Sint32)core->map->width, (Sint32)core->map->height }; if (0 > SDL_RenderCopyEx(core->renderer, core->map->layer_texture, NULL, &dst, 0, NULL, SDL_FLIP_NONE)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } // Update and render entity entities. index = 0; while (layer && core->map->entity_count) { if (is_tiled_layer_of_type(OBJECT_GROUP, layer, core)) { cute_tiled_object_t* tiled_object = get_head_object(layer, core); while (tiled_object) { entity_t* entity = &core->map->entity[index]; cute_tiled_property_t* properties = tiled_object->properties; Sint32 prop_cnt = get_object_property_count(tiled_object); Sint32 pos_x = entity->pos_x - core->camera.pos_x; Sint32 pos_y = entity->pos_y - core->camera.pos_y; SDL_Rect src = { 0 }; SDL_bool is_walking = SDL_FALSE; Sint32 sprite_cols = (Sint32)get_integer_property(H_sprite_cols, properties, prop_cnt, core); if (IS_STATE_SET(entity->state, S_WALK)) { is_walking = SDL_TRUE; } if (IS_STATE_SET(entity->state, S_RIGHT)) { if (is_walking) { entity->animation.length = (Sint32)get_integer_property(H_anim_walk_right_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_walk_right_index, properties, prop_cnt, core); } else { entity->animation.length = (Sint32)get_integer_property(H_anim_idle_right_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_idle_right_index, properties, prop_cnt, core); } } else if (IS_STATE_SET(entity->state, S_LEFT)) { if (is_walking) { entity->animation.length = (Sint32)get_integer_property(H_anim_walk_left_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_walk_left_index, properties, prop_cnt, core); } else { entity->animation.length = (Sint32)get_integer_property(H_anim_idle_left_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_idle_left_index, properties, prop_cnt, core); } } else if (IS_STATE_SET(entity->state, S_UP)) { if (is_walking) { entity->animation.length = (Sint32)get_integer_property(H_anim_walk_up_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_walk_up_index, properties, prop_cnt, core); } else { entity->animation.length = (Sint32)get_integer_property(H_anim_idle_up_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_idle_up_index, properties, prop_cnt, core); } } else if (IS_STATE_SET(entity->state, S_DOWN)) { if (is_walking) { entity->animation.length = (Sint32)get_integer_property(H_anim_walk_down_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_walk_down_index, properties, prop_cnt, core); } else { entity->animation.length = (Sint32)get_integer_property(H_anim_idle_down_len, properties, prop_cnt, core); entity->animation.first_frame = (Sint32)get_integer_property(H_anim_idle_down_index, properties, prop_cnt, core); } } entity->animation.first_frame -= 1; if (entity->animation.length > 1) { entity->animation.time_since_last_anim_frame += core->time_since_last_frame; } if (entity->animation.length > 1 && !core->display_text) { entity->animation.time_since_last_anim_frame += core->time_since_last_frame; entity->animation.fps = (Sint32)get_integer_property(H_anim_fps, properties, prop_cnt, core); if (entity->animation.time_since_last_anim_frame >= (Uint32)(1000 / entity->animation.fps)) { entity->animation.time_since_last_anim_frame = 0; entity->animation.current_frame += 1; if (entity->animation.current_frame >= entity->animation.length) { entity->animation.current_frame = 0; } } } else { entity->animation.current_frame = 0; //get_frame_position(entity->animation.first_frame, entity->width, entity->height, &src.x, &src.y, sprite_cols); } get_frame_position(entity->animation.first_frame + entity->animation.current_frame, entity->width, entity->height, &src.x, &src.y, sprite_cols); src.w = entity->width; src.h = entity->height; dst.x = (Sint32)pos_x - (entity->width / 2); dst.y = (Sint32)pos_y - (entity->height / 2); dst.w = entity->width; dst.h = entity->height; // We do not need to draw entities that are not // inside the viewport. if ((dst.x > (0 - entity->width)) && (dst.x < 176)) { if ((dst.y > (0 - entity->height)) && (dst.y < 208)) { // We do not draw entities that have no // sprite either and if the sprite requested // does not exist, there is also nothing to // do here. if ((entity->sprite_id > 0) && &core->map->sprite[entity->sprite_id - 1]) { if (core->map->sprite[entity->sprite_id - 1].texture) { if (0 > SDL_RenderCopyEx(core->renderer, core->map->sprite[entity->sprite_id - 1].texture, &src, &dst, 0, NULL, SDL_FLIP_NONE)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } } } if (core->debug_mode) { SDL_Rect tile_frame = { 0 }; Sint32 tile_index; tile_index = get_tile_index(entity->pos_x, entity->pos_y, core); tile_frame.w = get_tile_width(core->map->handle); tile_frame.h = get_tile_height(core->map->handle); tile_frame.x = (tile_index % core->map->handle->width) * tile_frame.w; tile_frame.y = (tile_index / core->map->handle->width) * tile_frame.h; tile_frame.x = tile_frame.x - core->camera.pos_x; tile_frame.y = tile_frame.y - core->camera.pos_y; if (core->map->tile_desc[tile_index].is_solid) { SDL_SetRenderDrawColor(core->renderer, 0xff, 0x00, 0x00, 0x00); } else { SDL_SetRenderDrawColor(core->renderer, 0x00, 0xff, 0x00, 0x00); } SDL_RenderDrawRect(core->renderer, &tile_frame); } } } index += 1; tiled_object = tiled_object->next; } } layer = layer->next; } if (core->display_text) { render_text(core); } return NG_OK; } // Texture does not yet exist. Render it! core->map->layer_texture = SDL_CreateTexture( core->renderer, SDL_PIXELFORMAT_RGB444, SDL_TEXTUREACCESS_TARGET, (Sint32)core->map->width, (Sint32)core->map->height); if (! core->map->layer_texture) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } if (0 > SDL_SetRenderTarget(core->renderer, core->map->layer_texture)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } SDL_RenderClear(core->renderer); while (layer) { SDL_Rect dst = { 0 }; SDL_Rect src = { 0 }; if (is_tiled_layer_of_type(TILE_LAYER, layer, core)) { Sint32 prop_cnt = get_layer_property_count(layer); if (layer->visible) { Sint32 index_height; Sint32 index_width; for (index_height = 0; index_height < (Sint32)core->map->handle->height; index_height += 1) { for (index_width = 0; index_width < (Sint32)core->map->handle->width; index_width += 1) { Sint32* layer_content = get_layer_content(layer); Sint32 gid = remove_gid_flip_bits((Sint32)layer_content[(index_height * (Sint32)core->map->handle->width) + index_width]); Sint32 local_id = gid - get_first_gid(core->map->handle); if (is_gid_valid(gid, core->map->handle)) { cute_tiled_tileset_t* tileset = get_head_tileset(core->map->handle); Sint32 animation_length = 0; Sint32 id = 0; src.w = dst.w = get_tile_width(core->map->handle); src.h = dst.h = get_tile_height(core->map->handle); dst.x = (Sint32)(index_width * get_tile_width(core->map->handle)); dst.y = (Sint32)(index_height * get_tile_height(core->map->handle)); get_tile_position(gid, (Uint32*)&src.x, (Uint32*)&src.y, core->map->handle); SDL_RenderCopy(core->renderer, core->map->tileset_texture, &src, &dst); if (is_tile_animated(gid, &animation_length, &id, core->map->handle)) { core->map->animated_tile[core->map->animated_tile_index].gid = get_local_id(gid, core->map->handle); core->map->animated_tile[core->map->animated_tile_index].id = id; core->map->animated_tile[core->map->animated_tile_index].dst_x = dst.x; core->map->animated_tile[core->map->animated_tile_index].dst_y = dst.y; core->map->animated_tile[core->map->animated_tile_index].current_frame = 0; core->map->animated_tile[core->map->animated_tile_index].animation_length = animation_length; core->map->animated_tile_index += 1; } } } } { const char* layer_name = get_layer_name(layer); //SDL_Log("Render map layer: %s", layer_name); } } } layer = layer->next; } if (0 > SDL_SetRenderTarget(core->renderer, core->render_target)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } return NG_OK; } // https://github.com/ngagesdk/nrpg/issues/2 status_t render_scene_ex(ngine_t* core) { status_t status = NG_OK; if (! core->is_map_loaded) { return NG_OK; } if (! core->map->layer_texture) { core->map->layer_texture = SDL_CreateTexture( core->renderer, SDL_PIXELFORMAT_RGB444, SDL_TEXTUREACCESS_TARGET, 256, 256); if (! core->map->layer_texture) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); status = NG_ERROR; goto exit; } } // tbd. exit: return status; } status_t draw_scene(ngine_t* core) { SDL_Rect dst = { 0, 0, 176, 208 }; if (0 > SDL_SetRenderTarget(core->renderer, NULL)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); } if (! core->is_map_loaded) { SDL_SetRenderDrawColor(core->renderer, 0x22, 0x33, 0x44, 0x00); SDL_RenderClear(core->renderer); //set_display_text("Loading", core); //render_text(core); SDL_RenderPresent(core->renderer); return NG_OK; } if (0 > SDL_RenderCopy(core->renderer, core->render_target, NULL, &dst)) { //SDL_Log("%s: %s.", FUNCTION_NAME, SDL_GetError()); return NG_ERROR; } SDL_SetRenderDrawColor(core->renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderPresent(core->renderer); SDL_RenderClear(core->renderer); return NG_OK; } void restrict_camera(ngine_t* core) { if (! is_map_loaded(core)) { return; } core->camera.pos_x = SDL_clamp(core->camera.pos_x, 0, core->map->width - 176); core->camera.pos_y = SDL_clamp(core->camera.pos_y, 0, core->map->height - 208); if (core->map->active_entity) { if (core->map->active_entity < 1) { core->map->active_entity = core->map->entity_count; } else if (core->map->active_entity > core->map->entity_count) { core->map->active_entity = 1; } } } void update_camera(ngine_t* core) { if (! is_map_loaded(core)) { return; } if (core->camera.is_locked) { if (core->map->active_entity) { entity_t* target = &core->map->entity[core->map->active_entity - 1]; core->camera.pos_x = target->pos_x; core->camera.pos_x -= 88; // 176 / 2 core->camera.pos_y = target->pos_y; core->camera.pos_y -= 104; // 208 / 2 } if (core->camera.pos_x < 0) { core->camera.pos_x = 0; } restrict_camera(core); } } status_t load_map_right(const char* map_name, Sint32 pos_y, ngine_t* core) { status_t status = NG_OK; Sint32 player_index; status = ng_load_map(map_name, core); if (NG_OK != status) { return status; } player_index = core->map->active_entity - 1; core->map->entity[player_index].pos_x = (core->map->entity[player_index].width / 2); core->map->entity[player_index].pos_y = pos_y; return status; } status_t load_map_left(const char* map_name, Sint32 pos_y, ngine_t* core) { status_t status = NG_OK; Sint32 player_index; status = ng_load_map(map_name, core); if (NG_OK != status) { return status; } player_index = core->map->active_entity - 1; core->map->entity[player_index].pos_x = core->map->width - (core->map->entity[player_index].width / 2); core->map->entity[player_index].pos_y = pos_y; return status; } status_t load_map_down(const char* map_name, Sint32 pos_x, ngine_t* core) { status_t status = NG_OK; Sint32 player_index; status = ng_load_map(map_name, core); if (NG_OK != status) { return status; } player_index = core->map->active_entity - 1; core->map->entity[player_index].pos_x = pos_x; core->map->entity[player_index].pos_y = 0; return status; } status_t load_map_up(const char* map_name, Sint32 pos_x, ngine_t* core) { status_t status = NG_OK; Sint32 player_index; status = ng_load_map(map_name, core); if (NG_OK != status) { return status; } player_index = core->map->active_entity - 1; core->map->entity[player_index].pos_x = pos_x; core->map->entity[player_index].pos_y = core->map->height - (core->map->entity[player_index].height / 2); return status; } void move_entity(entity_t* entity, Sint32 offset_x, Sint32 offset_y, ngine_t* core) { Sint32 tile_index; Sint32 adjacent_tile; if (! is_map_loaded(core)) { return; } if (core->display_text) { return; } tile_index = get_tile_index(entity->pos_x, entity->pos_y, core); // Moves right. if (offset_x > 0) { adjacent_tile = tile_index + 1; if (! core->map->tile_desc[adjacent_tile].is_solid) { entity->pos_x += offset_x; } else if((entity->pos_x / get_tile_width(core->map->handle)) >= (core->map->handle->width - 1)) { entity->pos_x += offset_x; } if (entity->pos_x >= (core->map->width + (entity->width / 2))) { if (get_string_map_property(H_map_right, core)) { char map_name[16] = { 0 }; stbsp_snprintf(map_name, 16, "%s", core->map->string_property); ng_unload_map(core); load_map_right(map_name, entity->pos_y, core); return; } } } // Moves left. else if (offset_x < 0) { adjacent_tile = tile_index - 1; if (! core->map->tile_desc[adjacent_tile].is_solid) { entity->pos_x += offset_x; } else if((entity->pos_x / get_tile_width(core->map->handle)) <= 0) { entity->pos_x += offset_x; } if (entity->pos_x <= (0 - (entity->width / 2))) { if (get_string_map_property(H_map_left, core)) { char map_name[16] = { 0 }; stbsp_snprintf(map_name, 16, "%s", core->map->string_property); ng_unload_map(core); load_map_left(map_name, entity->pos_y, core); return; } } } // Moves down. if (offset_y > 0) { adjacent_tile = tile_index + core->map->handle->width; if (adjacent_tile >= core->map->tile_desc_count) { adjacent_tile = core->map->tile_desc_count - 1; } if (! core->map->tile_desc[adjacent_tile].is_solid) { entity->pos_y += offset_y; } else if((entity->pos_y / get_tile_height(core->map->handle)) >= (core->map->handle->height - 1)) { entity->pos_y += offset_y; } if (entity->pos_y >= (core->map->height + (entity->height / 2))) { if (get_string_map_property(H_map_down, core)) { char map_name[16] = { 0 }; stbsp_snprintf(map_name, 16, "%s", core->map->string_property); ng_unload_map(core); load_map_down(map_name, entity->pos_x, core); return; } } } // Moves up. else if (offset_y < 0) { adjacent_tile = tile_index - core->map->handle->width; if (adjacent_tile >= 0) { if (! core->map->tile_desc[adjacent_tile].is_solid) { entity->pos_y += offset_y; } } else { entity->pos_y += offset_y; } if (entity->pos_y <= (0 - (entity->height / 2))) { if (get_string_map_property(H_map_up, core)) { char map_name[16] = { 0 }; stbsp_snprintf(map_name, 16, "%s", core->map->string_property); ng_unload_map(core); load_map_up(map_name, entity->pos_x, core); return; } } } }
ngagesdk/nrpg
src/ngtypes.h
<filename>src/ngtypes.h /** @file ngtypes.h * * N-GINE, a portable game engine which is being developed specifically * for the Nokia N-Gage. * * Internal type definitions. * * Copyright (c) 2022, <NAME>. All rights reserved. * SPDX-License-Identifier: MIT * **/ #ifndef NGTYPES_H #define NGTYPES_H #include <SDL.h> #include <cute_tiled.h> #define CLR_STATE(var, pos) var &= ~(1UL << pos) #define SET_STATE(var, pos) var |= 1UL << pos #define IS_STATE_SET(var, pos) ((0U == (var & (1 << pos))) ? 0U : 1U) typedef enum status { NG_OK = 0, NG_WARNING, NG_ERROR, NG_EXIT } status_t; typedef enum { TILE_LAYER = 0, OBJECT_GROUP } tiled_layer_type; typedef enum { S_IDLE, S_WALK, S_RIGHT, S_LEFT, S_UP, S_DOWN } state_t; typedef struct aabb { Uint8 bottom; Uint8 left; Uint8 right; Uint8 top; } aabb_t; typedef struct camera { Sint32 pos_x; Sint32 pos_y; Sint32 max_pos_x; Sint32 max_pos_y; SDL_bool is_locked; } camera_t; typedef struct animation { Uint32 time_since_last_anim_frame; Sint32 current_frame; Sint32 first_frame; Sint32 fps; Sint32 length; Sint32 offset_y; } animation_t; typedef struct entity { cute_tiled_object_t* handle; state_t state; Sint32 pos_x; Sint32 pos_y; Sint32 uid; Sint32 id; Sint32 index; Sint32 width; Sint32 height; Sint32 sprite_id; animation_t animation; } entity_t; typedef struct sprite { SDL_Texture* texture; Sint32 id; } sprite_t; typedef struct animated_tile { Sint32 dst_x; Sint32 dst_y; Sint32 animation_length; Sint32 current_frame; Sint32 gid; Sint32 id; } animated_tile_t; typedef struct tile_desc { SDL_bool is_solid; } tile_desc_t; typedef struct map { cute_tiled_map_t* handle; long long unsigned hash_id_objectgroup; long long unsigned hash_id_tilelayer; Sint32 width; Sint32 height; animated_tile_t* animated_tile; Sint32 animated_tile_index; Uint32 time_since_last_anim_frame; SDL_Texture* animated_tile_texture; SDL_Texture* layer_texture; SDL_Texture* tileset_texture; SDL_bool boolean_property; float decimal_property; Sint32 integer_property; const char* string_property; entity_t* entity; Sint32 entity_count; Sint32 active_entity; sprite_t* sprite; Sint32 sprite_count; tile_desc_t* tile_desc; Sint32 tile_desc_count; } map_t; typedef struct ngine { SDL_Renderer* renderer; SDL_Texture* render_target; SDL_Texture* font_texture; unsigned char* display_text; SDL_Window* window; map_t* map; struct camera camera; SDL_bool is_map_loaded; SDL_bool debug_mode; Uint32 time_since_last_frame; Uint32 time_a; Uint32 time_b; } ngine_t; #endif /* NGTYPES_H */
ngagesdk/nrpg
src/ngine.c
<gh_stars>1-10 /** @file ngine.c * * N-GINE, a portable game engine which is being developed specifically * for the Nokia N-Gage. * * API implementation. * * Copyright (c) 2022, <NAME>. All rights reserved. * SPDX-License-Identifier: MIT * **/ #include <SDL.h> #include "ngine.h" status_t ng_init(const char* resource_file, const char* title, ngine_t** core) { status_t status = NG_OK; *core = (ngine_t*)calloc(1, sizeof(struct ngine)); if (! *core) { //SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_ERROR; } SDL_SetMainReady(); if (0 != SDL_Init(SDL_INIT_VIDEO)) { //SDL_Log("Unable to initialise SDL: %s", SDL_GetError()); return NG_ERROR; } (*core)->window = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 176, 208, SDL_WINDOW_FULLSCREEN); if (! (*core)->window) { //SDL_Log("Could not create window: %s", SDL_GetError()); return NG_ERROR; } (*core)->renderer = SDL_CreateRenderer((*core)->window, 0, SDL_RENDERER_SOFTWARE); if (! (*core)->renderer) { //SDL_Log("Could not create renderer: %s", SDL_GetError()); SDL_DestroyWindow((*core)->window); return NG_ERROR; } if (0 != SDL_RenderSetIntegerScale((*core)->renderer, SDL_TRUE)) { //SDL_Log("Could not enable integer scale: %s", SDL_GetError()); status = NG_WARNING; } init_file_reader(resource_file); if (NG_OK != load_font((*core))) { return NG_ERROR; } return status; } status_t ng_update(ngine_t* core) { status_t status = NG_OK; Uint32 delta_time = 0; const Uint8* keystate = SDL_GetKeyboardState(NULL); SDL_Event event; Sint32 player_index; core->time_b = core->time_a; core->time_a = SDL_GetTicks(); // Calculate delta time. if (core->time_a > core->time_b) { delta_time = core->time_a - core->time_b; } else { delta_time = core->time_b - core->time_a; } core->time_since_last_frame = delta_time; // Set-up basic controls/events. if (is_map_loaded(core)) { player_index = core->map->active_entity - 1; CLR_STATE(core->map->entity[player_index].state, S_WALK); if (keystate[SDL_SCANCODE_UP]) { SET_STATE(core->map->entity[player_index].state, S_WALK); SET_STATE(core->map->entity[player_index].state, S_UP); CLR_STATE(core->map->entity[player_index].state, S_DOWN); CLR_STATE(core->map->entity[player_index].state, S_LEFT); CLR_STATE(core->map->entity[player_index].state, S_RIGHT); move_entity(&core->map->entity[player_index], 0, -2, core); } if (keystate[SDL_SCANCODE_DOWN]) { SET_STATE(core->map->entity[player_index].state, S_WALK); SET_STATE(core->map->entity[player_index].state, S_DOWN); CLR_STATE(core->map->entity[player_index].state, S_UP); CLR_STATE(core->map->entity[player_index].state, S_LEFT); CLR_STATE(core->map->entity[player_index].state, S_RIGHT); move_entity(&core->map->entity[player_index], 0, 2, core); } if (keystate[SDL_SCANCODE_LEFT]) { SET_STATE(core->map->entity[player_index].state, S_WALK); SET_STATE(core->map->entity[player_index].state, S_LEFT); CLR_STATE(core->map->entity[player_index].state, S_RIGHT); CLR_STATE(core->map->entity[player_index].state, S_UP); CLR_STATE(core->map->entity[player_index].state, S_DOWN); move_entity(&core->map->entity[player_index], -2, 0, core); } if (keystate[SDL_SCANCODE_RIGHT]) { SET_STATE(core->map->entity[player_index].state, S_WALK); SET_STATE(core->map->entity[player_index].state, S_RIGHT); CLR_STATE(core->map->entity[player_index].state, S_LEFT); CLR_STATE(core->map->entity[player_index].state, S_UP); CLR_STATE(core->map->entity[player_index].state, S_DOWN); move_entity(&core->map->entity[player_index], 2, 0, core); } } if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: { switch (event.key.keysym.sym) { case SDLK_BACKSPACE: status = NG_EXIT; goto exit; case SDLK_5: trigger_action(core); break; case SDLK_9: core->debug_mode = !core->debug_mode; break; default: clear_display_text(core); break; } } case SDL_KEYUP: { switch (event.key.keysym.sym) { default: break; } } } } update_camera(core); status = render_scene(core); if (NG_OK != status) { goto exit; } status = draw_scene(core); exit: return status; } void ng_free(ngine_t *core) { if (core->display_text) { free(core->display_text); core->display_text = NULL; } if (core->font_texture) { SDL_DestroyTexture(core->font_texture); core->font_texture = NULL; } if (core->render_target) { SDL_DestroyTexture(core->render_target); core->render_target = NULL; } if (core->window) { SDL_DestroyWindow(core->window); } if (core->renderer) { SDL_DestroyRenderer(core->renderer); } if (core) { free(core); } SDL_Quit(); } status_t ng_load_map(const char* map_name, ngine_t* core) { status_t status = NG_OK; if (is_map_loaded(core)) { //SDL_Log("A map has already been loaded: unload map first."); return NG_WARNING; } // Load map file and allocate required memory. // [1] Map. core->map = (map_t*)calloc(1, sizeof(struct map)); if (! core->map) { //SDL_Log("%s: error allocating memory.", FUNCTION_NAME); return NG_WARNING; } // [2] Tiled map. status = load_tiled_map(map_name, core); if (NG_OK != status) { free(core->map); goto exit; } // [3] Tiles. status = load_tiles(core); if (NG_OK != status) { goto exit; } // [4] Entities. status = load_entities(core); if (NG_OK != status) { goto exit; } // [5] Tileset. status = load_tileset(core); if (NG_OK != status) { goto exit; } // [6] Sprites. status = load_sprites(core); if (NG_OK != status) { goto exit; } // [7] Animated tiles. status = load_animated_tiles(core); if (NG_OK != status) { goto exit; } core->map->height = (Sint32)((Sint32)core->map->handle->height * get_tile_height(core->map->handle)); core->map->width = (Sint32)((Sint32)core->map->handle->width * get_tile_width(core->map->handle)); exit: if (NG_OK != status) { ng_unload_map(core); } clear_display_text(core); core->is_map_loaded = SDL_TRUE; return status; } void ng_unload_map(ngine_t* core) { Sint32 index; if (! is_map_loaded(core)) { //SDL_Log("No map has been loaded."); return; } core->is_map_loaded = SDL_FALSE; if (core->map->layer_texture) { SDL_DestroyTexture(core->map->layer_texture); core->map->layer_texture = NULL; } if (core->map->animated_tile_texture) { SDL_DestroyTexture(core->map->animated_tile_texture); core->map->animated_tile_texture = NULL; } // Free up allocated memory in reverse order. // [7] Animated tiles. free(core->map->animated_tile); // [6] Sprites. if (core->map->sprite_count > 0) { for (index = 0; index < core->map->sprite_count; index += 1) { core->map->sprite[index].id = 0; if (core->map->sprite[index].texture) { SDL_DestroyTexture(core->map->sprite[index].texture); core->map->sprite[index].texture = NULL; } } } free(core->map->sprite); core->map->sprite = NULL; // [5] Tileset. if (core->map->tileset_texture) { SDL_DestroyTexture(core->map->tileset_texture); core->map->tileset_texture = NULL; } // [4] Entities. free(core->map->entity); // [3] Tiles. free(core->map->tile_desc); core->map->tile_desc = NULL; // [2] Tiled map. unload_tiled_map(core); // [1] Map. free(core->map); core->map = NULL; }
ngagesdk/nrpg
src/main.c
/** @file main.c * * N-GINE, a portable game engine which is being developed specifically * for the Nokia N-Gage. * * Minimal launcher implementation. * * Copyright (c) 2022, <NAME>. All rights reserved. * SPDX-License-Identifier: MIT * **/ #include "ngine.h" #if defined __SYMBIAN32__ #define RES_FILE "E:\\data.pfs" #else #define RES_FILE "data.pfs" #endif int main(int argc, char *argv[]) { int status = 0; ngine_t *core = NULL; status = ng_init(RES_FILE, "ngine", &core); if (NG_OK != status) { goto quit; } status = ng_load_map("entry.tmj", core); if (NG_OK != status) { goto quit; } while (NG_OK == status) { status = ng_update(core); if (NG_EXIT == status) { status = NG_OK; goto quit; } } quit: ng_unload_map(core); ng_free(core); return status; }
skeeto/makefile-game-of-life
lifegen.c
<gh_stars>1-10 #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <getopt.h> #define FATAL(s) \ do { \ fprintf(stderr, "%s: " s " -- %s\n", argv[0], optarg); \ exit(EXIT_FAILURE); \ } while (0); struct config { unsigned width; unsigned height; double delay; const char *makefile; const char *rules; char alive; char dead; }; static unsigned cell_width(unsigned x) { unsigned result = 1; unsigned value = 10; while (value <= x) { value *= 10; result++; } return result; } static void cell_name(char *dst, const struct config *c, unsigned x, unsigned y) { unsigned wx = cell_width(c->width); unsigned wy = cell_width(c->width); sprintf(dst, "%0*u%0*u", wx, x, wy, y); } static bool rule_eval(const char *rules, unsigned count, bool state) { size_t length = strlen(rules); for (const char *p = rules + length - 1; p >= rules && *p != '/'; p--) if ((unsigned)*p == count + '0') return true; for (const char *p = rules; p < rules + length && *p != '/'; p++) if ((unsigned)*p == count + '0') return state; return false; } static void print_target(const struct config *c) { printf("output :\n"); printf("\t@printf \"$(output)\"\n"); if (c->delay != 0.0) printf("\t@sleep %f\n", c->delay); printf("\t@$(MAKE) -f %s $(args)\n", c->makefile); } static void print_rules(const struct config *c) { for (unsigned n = 0; n < 512; n++) { char lvalue[10]; unsigned count = 0; for (unsigned i = 0; i < 9; i++) { unsigned set = (n >> i) & 1; if (i != 4) // !self count += set; lvalue[i] = set ? c->alive : c->dead; } lvalue[9] = 0; bool state = ((n >> 4) & 1) == 1; bool result = rule_eval(c->rules, count, state); printf("%s = %c\n", lvalue, result ? c->alive : c->dead); } } static void print_init(const struct config *c) { for (unsigned y = 0; y < c->height; y++) for (unsigned x = 0; x < c->width; x++) { char cell[64]; cell_name(cell, c, x, y); double v = rand() / (double)RAND_MAX; printf("%s = %c\n", cell, v < 0.5 ? c->alive : c->dead); } } static void print_compute(const struct config *c) { for (unsigned y = 0; y < c->height; y++) for (unsigned x = 0; x < c->width; x++) { char cell[64]; cell_name(cell, c, x, y); printf("n%s = $(", cell); for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++) { char source[64]; unsigned xx = (x + dx + c->width) % c->width; unsigned yy = (y + dy + c->height) % c->height; cell_name(source, c, xx, yy); printf("$(%s)", source); } puts(")"); } } static void print_output(const struct config *c) { printf("output = \\033[2J\\033[H"); for (unsigned y = 0; y < c->height; y++) { for (unsigned x = 0; x < c->width; x++) { char cell[64]; cell_name(cell, c, x, y); printf("$(%s)", cell); } printf("\\n"); } puts(""); } static void print_args(const struct config *c) { printf("args ="); for (unsigned y = 0; y < c->height; y++) for (unsigned x = 0; x < c->width; x++) { char cell[64]; cell_name(cell, c, x, y); printf(" %s=$(n%s)", cell, cell); } puts(""); } static void print_help(FILE *o, const char *progname) { fprintf(o, "usage: %s [options]\n", progname); fprintf(o, " -c <cellspec> pair of alive/dead characters (@.)\n"); fprintf(o, " -d <delay> fractional delay between frames (0.1)\n"); fprintf(o, " -f <filename> internal makefile name (life.mak)\n"); fprintf(o, " -h print this help information\n"); fprintf(o, " -r <rules> games of life rules (23/3)\n"); fprintf(o, " -s <seed> initialization seed\n"); fprintf(o, " -z <width:height> grid size in characters (50:40)\n"); } int main(int argc, char **argv) { struct config config = { .width = 50, .height = 40, .delay = 0.1, .makefile = "life.mak", .rules = "23/3", .alive = '@', .dead = '.', }; int option; while ((option = getopt(argc, argv, "c:d:f:hr:s:z:")) != -1) { switch (option) { case 'c': { char a = config.alive = optarg[0]; char d = config.dead = optarg[1]; const char *verboten = " \t\n\v\f\r=:&%()"; if (strchr(verboten, a) || strchr(verboten, d)) FATAL("invalid cell spec"); } break; case 'd': { config.delay = strtod(optarg, NULL); if (config.delay < 0) FATAL("invalid delay"); } break; case 'f': { for (char *p = optarg; *p; p++) if (isspace(*p)) FATAL("invalid filename"); config.makefile = optarg; } break; case 'h': { print_help(stdout, argv[0]); exit(EXIT_SUCCESS); } break; case 'r': { unsigned d; config.rules = optarg; if (sscanf(config.rules, "%u/%u", &d, &d) != 2) FATAL("invalid rules"); } break; case 's': { srand(atoi(optarg)); } break; case 'z': { int r = sscanf(optarg, "%u:%u", &config.width, &config.height); if (r != 2) FATAL("invalid size"); } break; default: { char message[2] = {option}; optarg = message; print_help(stderr, argv[0]); exit(EXIT_FAILURE); } break; } } print_target(&config); puts(""); print_rules(&config); puts(""); print_init(&config); puts(""); print_compute(&config); puts(""); print_output(&config); puts(""); print_args(&config); return 0; }
edparsons/com.speedshare.cordova.htmlviewer
src/ios/htmlViewerPlugin.h
// // SpeedsharePlugin.h // // Copyright (c) 2015 Osix Corp. All rights reserved. // Please see the LICENSE included with this distribution for details. // #import <Cordova/CDVPlugin.h> #import <WebKit/WebKit.h> @interface HtmlViewerPlugin : CDVPlugin <WKNavigationDelegate, WKScriptMessageHandler> - (void)startSession:(CDVInvokedUrlCommand*)command; - (void)stopSession:(CDVInvokedUrlCommand*)command; - (void)updateView:(CDVInvokedUrlCommand*)command; - (void)updateDOM:(CDVInvokedUrlCommand*)command; - (void)updateHTML:(CDVInvokedUrlCommand*)command; - (void)updateInternalView:(CDVInvokedUrlCommand*)command; - (void)bringToFront:(CDVInvokedUrlCommand*)command; - (void)sendToBack:(CDVInvokedUrlCommand*)command; - (void)sendScroll:(CDVInvokedUrlCommand*)command; - (void)checkElement:(CDVInvokedUrlCommand*)command; - (void)startLoading:(CDVInvokedUrlCommand*)command; - (void)hideView:(CDVInvokedUrlCommand*)command; - (void)showView:(CDVInvokedUrlCommand*)command; - (void)ravenSetup:(CDVInvokedUrlCommand*)command; - (void)fakeCrash:(CDVInvokedUrlCommand*)command; - (void)setCrashlytics:(CDVInvokedUrlCommand*)command; - (void)init:(CDVInvokedUrlCommand*)command; @end
Sensirion/raspberry-pi-i2c-sgp41
sensirion_common.h
<filename>sensirion_common.h /* * Copyright (c) 2018, Sensirion AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Sensirion AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef SENSIRION_COMMON_H #define SENSIRION_COMMON_H #include "sensirion_config.h" #ifdef __cplusplus extern "C" { #endif #define NO_ERROR 0 #define NOT_IMPLEMENTED_ERROR 31 #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x))) #endif #define SENSIRION_COMMAND_SIZE 2 #define SENSIRION_WORD_SIZE 2 #define SENSIRION_NUM_WORDS(x) (sizeof(x) / SENSIRION_WORD_SIZE) #define SENSIRION_MAX_BUFFER_WORDS 32 /** * sensirion_common_bytes_to_int16_t() - Convert an array of bytes to an int16_t * * Convert an array of bytes received from the sensor in big-endian/MSB-first * format to an int16_t value in the correct system-endianness. * * @param bytes An array of at least two bytes (MSB first) * @return The byte array represented as int16_t */ int16_t sensirion_common_bytes_to_int16_t(const uint8_t* bytes); /** * sensirion_common_bytes_to_int32_t() - Convert an array of bytes to an int32_t * * Convert an array of bytes received from the sensor in big-endian/MSB-first * format to an int32_t value in the correct system-endianness. * * @param bytes An array of at least four bytes (MSB first) * @return The byte array represented as int32_t */ int32_t sensirion_common_bytes_to_int32_t(const uint8_t* bytes); /** * sensirion_common_bytes_to_uint16_t() - Convert an array of bytes to an * uint16_t * * Convert an array of bytes received from the sensor in big-endian/MSB-first * format to an uint16_t value in the correct system-endianness. * * @param bytes An array of at least two bytes (MSB first) * @return The byte array represented as uint16_t */ uint16_t sensirion_common_bytes_to_uint16_t(const uint8_t* bytes); /** * sensirion_common_bytes_to_uint32_t() - Convert an array of bytes to an * uint32_t * * Convert an array of bytes received from the sensor in big-endian/MSB-first * format to an uint32_t value in the correct system-endianness. * * @param bytes An array of at least four bytes (MSB first) * @return The byte array represented as uint32_t */ uint32_t sensirion_common_bytes_to_uint32_t(const uint8_t* bytes); /** * sensirion_common_bytes_to_float() - Convert an array of bytes to a float * * Convert an array of bytes received from the sensor in big-endian/MSB-first * format to an float value in the correct system-endianness. * * @param bytes An array of at least four bytes (MSB first) * @return The byte array represented as float */ float sensirion_common_bytes_to_float(const uint8_t* bytes); /** * sensirion_common_uint32_t_to_bytes() - Convert an uint32_t to an array of * bytes * * Convert an uint32_t value in system-endianness to big-endian/MBS-first * format to send to the sensor. * * @param value Value to convert * @param bytes An array of at least four bytes */ void sensirion_common_uint32_t_to_bytes(const uint32_t value, uint8_t* bytes); /** * sensirion_common_uint16_t_to_bytes() - Convert an uint16_t to an array of * bytes * * Convert an uint16_t value in system-endianness to big-endian/MBS-first * format to send to the sensor. * * @param value Value to convert * @param bytes An array of at least two bytes */ void sensirion_common_uint16_t_to_bytes(const uint16_t value, uint8_t* bytes); /** * sensirion_common_int32_t_to_bytes() - Convert an int32_t to an array of bytes * * Convert an int32_t value in system-endianness to big-endian/MBS-first * format to send to the sensor. * * @param value Value to convert * @param bytes An array of at least four bytes */ void sensirion_common_int32_t_to_bytes(const int32_t value, uint8_t* bytes); /** * sensirion_common_int16_t_to_bytes() - Convert an int16_t to an array of bytes * * Convert an int16_t value in system-endianness to big-endian/MBS-first * format to send to the sensor. * * @param value Value to convert * @param bytes An array of at least two bytes */ void sensirion_common_int16_t_to_bytes(const int16_t value, uint8_t* bytes); /** * sensirion_common_float_to_bytes() - Convert an float to an array of bytes * * Convert an float value in system-endianness to big-endian/MBS-first * format to send to the sensor. * * @param value Value to convert * @param bytes An array of at least four bytes */ void sensirion_common_float_to_bytes(const float value, uint8_t* bytes); /** * sensirion_common_copy_bytes() - Copy bytes from one array to the other. * * @param source Array of bytes to be copied. * @param destination Array of bytes to be copied to. * @param data_length Number of bytes to copy. */ void sensirion_common_copy_bytes(const uint8_t* source, uint8_t* destination, uint16_t data_length); #ifdef __cplusplus } #endif #endif /* SENSIRION_COMMON_H */
Sensirion/raspberry-pi-i2c-sgp41
sensirion_common.c
/* * Copyright (c) 2018, Sensirion AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Sensirion AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "sensirion_common.h" #include "sensirion_config.h" uint16_t sensirion_common_bytes_to_uint16_t(const uint8_t* bytes) { return (uint16_t)bytes[0] << 8 | (uint16_t)bytes[1]; } uint32_t sensirion_common_bytes_to_uint32_t(const uint8_t* bytes) { return (uint32_t)bytes[0] << 24 | (uint32_t)bytes[1] << 16 | (uint32_t)bytes[2] << 8 | (uint32_t)bytes[3]; } int16_t sensirion_common_bytes_to_int16_t(const uint8_t* bytes) { return (int16_t)sensirion_common_bytes_to_uint16_t(bytes); } int32_t sensirion_common_bytes_to_int32_t(const uint8_t* bytes) { return (int32_t)sensirion_common_bytes_to_uint32_t(bytes); } float sensirion_common_bytes_to_float(const uint8_t* bytes) { union { uint32_t u32_value; float float32; } tmp; tmp.u32_value = sensirion_common_bytes_to_uint32_t(bytes); return tmp.float32; } void sensirion_common_uint32_t_to_bytes(const uint32_t value, uint8_t* bytes) { bytes[0] = value >> 24; bytes[1] = value >> 16; bytes[2] = value >> 8; bytes[3] = value; } void sensirion_common_uint16_t_to_bytes(const uint16_t value, uint8_t* bytes) { bytes[0] = value >> 8; bytes[1] = value; } void sensirion_common_int32_t_to_bytes(const int32_t value, uint8_t* bytes) { bytes[0] = value >> 24; bytes[1] = value >> 16; bytes[2] = value >> 8; bytes[3] = value; } void sensirion_common_int16_t_to_bytes(const int16_t value, uint8_t* bytes) { bytes[0] = value >> 8; bytes[1] = value; } void sensirion_common_float_to_bytes(const float value, uint8_t* bytes) { union { uint32_t u32_value; float float32; } tmp; tmp.float32 = value; sensirion_common_uint32_t_to_bytes(tmp.u32_value, bytes); } void sensirion_common_copy_bytes(const uint8_t* source, uint8_t* destination, uint16_t data_length) { uint16_t i; for (i = 0; i < data_length; i++) { destination[i] = source[i]; } }
Sensirion/raspberry-pi-i2c-sgp41
sgp41_i2c.h
/* * THIS FILE IS AUTOMATICALLY GENERATED * * I2C-Generator: 0.3.0 * Yaml Version: 0.1.0 * Template Version: 0.7.0-62-g3d691f9 */ /* * Copyright (c) 2021, Sensirion AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Sensirion AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef SGP41_I2C_H #define SGP41_I2C_H #ifdef __cplusplus extern "C" { #endif #include "sensirion_config.h" /** * sgp41_execute_conditioning() - This command starts the conditioning, i.e., * the VOC pixel will be operated at the same temperature as it is by calling * the sgp41_measure_raw command while the NOx pixel will be operated at a * different temperature for conditioning. This command returns only the * measured raw signal of the VOC pixel SRAW_VOC as 2 bytes (+ 1 CRC byte). * * @param default_rh Default conditions for relative humidty. * * @param default_t Default conditions for temperature. * * @param sraw_voc u16 unsigned integer directly provides the raw signal * SRAW_VOC in ticks which is proportional to the logarithm of the resistance of * the sensing element. * * @return 0 on success, an error code otherwise */ int16_t sgp41_execute_conditioning(uint16_t default_rh, uint16_t default_t, uint16_t* sraw_voc); /** * sgp41_measure_raw_signals() - This command starts/continues the VOC+NOx * measurement mode * * @param relative_humidity Leaves humidity compensation disabled by sending the * default value 0x8000 (50%RH) or enables humidity compensation when sending * the relative humidity in ticks (ticks = %RH * 65535 / 100) * * @param temperature Leaves humidity compensation disabled by sending the * default value 0x6666 (25 degC) or enables humidity compensation when sending * the temperature in ticks (ticks = (degC + 45) * 65535 / 175) * * @param sraw_voc u16 unsigned integer directly provides the raw signal * SRAW_VOC in ticks which is proportional to the logarithm of the resistance of * the sensing element. * * @param sraw_nox u16 unsigned integer directly provides the raw signal * SRAW_NOX in ticks which is proportional to the logarithm of the resistance of * the sensing element. * * @return 0 on success, an error code otherwise */ int16_t sgp41_measure_raw_signals(uint16_t relative_humidity, uint16_t temperature, uint16_t* sraw_voc, uint16_t* sraw_nox); /** * sgp41_execute_self_test() - This command triggers the built-in self-test * checking for integrity of both hotplate and MOX material and returns the * result of this test as 2 bytes * * @param test_result 0xXX 0xYY: ignore most significant byte 0xXX. The four * least significant bits of the least significant byte 0xYY provide information * if the self-test has or has not passed for each individual pixel. All zero * mean all tests passed successfully. Check the datasheet for more detailed * information. * * @return 0 on success, an error code otherwise */ int16_t sgp41_execute_self_test(uint16_t* test_result); /** * sgp41_turn_heater_off() - This command turns the hotplate off and stops the * measurement. Subsequently, the sensor enters the idle mode. * * @return 0 on success, an error code otherwise */ int16_t sgp41_turn_heater_off(void); /** * sgp41_get_serial_number() - This command provides the decimal serial number * of the SGP41 chip by returning 3x2 bytes. * * @param serial_number 48-bit unique serial number * * @return 0 on success, an error code otherwise */ int16_t sgp41_get_serial_number(uint16_t* serial_number, uint8_t serial_number_size); #ifdef __cplusplus } #endif #endif /* SGP41_I2C_H */
Sensirion/raspberry-pi-i2c-sgp41
sgp41_i2c_example_usage.c
/* * I2C-Generator: 0.3.0 * Yaml Version: 0.1.0 * Template Version: 0.7.0-62-g3d691f9 */ /* * Copyright (c) 2021, Sensirion AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Sensirion AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <inttypes.h> #include <stdio.h> // printf #include "sensirion_common.h" #include "sensirion_i2c_hal.h" #include "sgp41_i2c.h" /* * TO USE CONSOLE OUTPUT (PRINTF) YOU MAY NEED TO ADAPT THE INCLUDE ABOVE OR * DEFINE IT ACCORDING TO YOUR PLATFORM: * #define printf(...) */ int main(void) { int16_t error = 0; // Parameters for deactivated humidity compensation: uint16_t default_rh = 0x8000; uint16_t default_t = 0x6666; sensirion_i2c_hal_init(); uint16_t serial_number[3]; uint8_t serial_number_size = 3; error = sgp41_get_serial_number(serial_number, serial_number_size); if (error) { printf("Error executing sgp41_get_serial_number(): %i\n", error); } else { printf("Serial number: %" PRIu64 "\n", (((uint64_t)serial_number[0]) << 32) | (((uint64_t)serial_number[1]) << 16) | ((uint64_t)serial_number[2])); } uint16_t test_result; error = sgp41_execute_self_test(&test_result); if (error) { printf("Error executing sgp41_execute_self_test(): %i\n", error); } else { printf("Test result: %u\n", test_result); } // SGP41 conditioning during 10 seconds before measuring for (int i = 0; i < 10; i++) { uint16_t sraw_voc; sensirion_i2c_hal_sleep_usec(1000000); error = sgp41_execute_conditioning(default_rh, default_t, &sraw_voc); if (error) { printf("Error executing sgp41_execute_conditioning(): " "%i\n", error); } else { printf("SRAW VOC: %u\n", sraw_voc); printf("SRAW NOx: conditioning\n"); } } // Start Measurement for (int i = 0; i < 60; i++) { uint16_t sraw_voc; uint16_t sraw_nox; sensirion_i2c_hal_sleep_usec(1000000); error = sgp41_measure_raw_signals(default_rh, default_t, &sraw_voc, &sraw_nox); if (error) { printf("Error executing sgp41_measure_raw_signals(): " "%i\n", error); } else { printf("SRAW VOC: %u\n", sraw_voc); printf("SRAW NOx: %u\n", sraw_nox); } } return 0; }
Harjas12/instagram
instagram/Header.h
// // Header.h // instagram // // Created by <NAME> on 2/2/18. // Copyright © 2018 <NAME>. All rights reserved. // #ifndef Header_h #define Header_h #import <Parse/Parse.h> #import <Bolts/BFTask.h> #endif /* Header_h */
polopoints/polopoints
src/noui.h
<reponame>polopoints/polopoints // Copyright (c) 2013 The DACRS developers // Copyright (c) 2016 The Polopoints developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef POLOPOINTS_NOUI_H #define POLOPOINTS_NOUI_H extern void noui_connect(); extern void ThreadSendMessageToUI(); #endif
polopoints/polopoints
src/wallet/walletdb.h
// Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2013 The Dacrs developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef POLOPOINTS_WALLETDB_H #define POLOPOINTS_WALLETDB_H #include "key.h" #include <list> #include <stdint.h> #include <string> #include <utility> #include <vector> #include "stdio.h" #include "db.h" class CAccountInfo; class CAccountingEntry; struct CBlockLocator; class CKeyPool; class CMasterKey; class CWallet; class uint160; class uint256; class CRegID; class CAccountTx; class CKeyCombi; /** Error statuses for the wallet database */ enum DBErrors { DB_LOAD_OK, DB_CORRUPT, DB_NONCRITICAL_ERROR, DB_TOO_NEW, DB_LOAD_FAIL, DB_NEED_REWRITE }; /*class CKeyMetadata { public: static const int CURRENT_VERSION=1; int nVersion; int64_t nCreateTime; // 0 means unknown CKeyMetadata() { SetNull(); } CKeyMetadata(int64_t nCreateTime_) { nVersion = CKeyMetadata::CURRENT_VERSION; nCreateTime = nCreateTime_; } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nCreateTime); ) void SetNull() { nVersion = CKeyMetadata::CURRENT_VERSION; nCreateTime = 0; } };*/ /** Access to the wallet database (wallet.dat) */ class CWalletDB : public CDB { public: CWalletDB(const std::string& strFilename, const char* pszMode = "r+", bool fFlushOnClose = true) : CDB(strFilename, pszMode, fFlushOnClose) { } private: CWalletDB(const CWalletDB&); void operator=(const CWalletDB&); public: bool WriteCryptedKey(const CPubKey& pubkey, const std::vector<unsigned char>& vchCryptedSecret); bool WriteKeyStoreValue(const CKeyID &keyId, const CKeyCombi& KeyStoreValue, int nVersion); bool EraseKeyStoreValue(const CKeyID &keyId); bool WriteBlockTx(const uint256 &hash, const CAccountTx& atx); bool EraseBlockTx(const uint256& hash); bool WriteUnComFirmedTx(const uint256 &hash, const std::shared_ptr<CBaseTransaction> &tx); bool EraseUnComFirmedTx(const uint256& hash); bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey); bool EraseMasterKey(unsigned int nID); bool WriteVersion(const int version) ; bool WriteMinVersion(const int version) ; int GetMinVersion(void); int GetVersion(void); DBErrors LoadWallet(CWallet* pwallet); static unsigned int nWalletDBUpdated ; static bool Recover(CDBEnv& dbenv, string filename, bool fOnlyKeys); static bool Recover(CDBEnv& dbenv, string filename); }; bool BackupWallet(const CWallet& wallet, const string& strDest); extern void ThreadFlushWalletDB(const string& strFile); extern void ThreadRelayTx(CWallet* pWallet); #endif // POLOPOINTS_WALLETDB_H
polopoints/polopoints
src/vm/testmcu.h
<reponame>polopoints/polopoints /* * TestMcu.h * * Created on: Aug 6, 2014 * Author: ranger.shi */ #ifndef TESTMCU_H_ #define TESTMCU_H_ #include <boost/format.hpp> #include "vm8051.h" #include <stdio.h> #include <string.h> #include <iostream> using namespace boost; class CTestMcu { CVm8051 *pCVir8051; public: static bool IsOdd(unsigned char un); string AJMPTest(int space); string NOPTest(int space); string LJMPTest(int space); string RR_ATest(int space); string INC_ATest(int space); string INC_DirectTest(int space); string INC_Ri_1Test(int space); string INC_RnTest(int space); string JBC_Bit_RelTest(int space); string ACALL_Addr11Test(int space); string LCALL_Addr16Test(int space); string RRC_ATest(int space); string DEC_ATest(int space); string DEC_DirectTest(int space); string DEC_Ri_1Test(int space); string DEC_RnTest(int space); string JB_Bit_RelTest(int space); string RETTest(int space); string RL_ATest(int space); string ADD_A_DataTest(int space); string ADD_A_DirectTest(int space); string ADD_A_Ri_1Test(int space); string ADD_A_RnTest(int space); string JNB_Bit_RelTest(int space); string RETITest(int space); string RLC_ATest(int space); string ADDC_A_DataTest(int space); string ADDC_A_DirectTest(int space); string ADDC_A_RnTest(int space); string ADDC_A_RiTest(int space); string JC_RelTest(int space); string ORL_Direct_ATest(int space); string ORL_Direct_DataTest(int space); string ORL_A_Data_And_DirectTest(int space); string ORL_A_Rn_1Test(int space); string ORL_A_Ri_1Test(int space); string ANL_Direct_ATest(int space); string ANL_Direct_DataTest(int space); string ANL_A_Data_And_DirectTest(int space); string ANL_A_Rn_1Test(int space); string ANL_A_Ri_1Test(int space); string JZ_RelTest(int space); string XRL_Direct_ATest(int space); string XRL_Direct_DataTest(int space); string XRL_A_Data_And_DirectTest(int space); string XRL_A_Rn_1Test(int space); string XRL_A_Ri_1Test(int space); string JNZ_RelTest(int space); string ORL_C_DirectTest(int space); string JMP_A_DPTRTest(int space); string MOV_A_DataTest(int space); string MOV_Direct_DataTest(int space); string MOV_Ri_DataTest(int space); string MOV_Rn_DataTest(int space); string SJMP_RelTest(int space); string ANL_C_BitTest(int space); string MOVC_A_PCTest(int space); string DIV_ABTest(int space); string MOV_Direct_DirectTest(int space); string MOV_Direct_Rn_1Test(int space); string MOV_Rn_ATest(int space); string MOV_Direct_ATest(int space); string CPL_ATest(int space); string MOVX_Ri_1_ATest(int space); string MOVX_DPTR_ATest(int space); string MOV_A_Rn_1Test(int space); string MOV_A_Ri_1Test(int space); string MOV_A_DirectTest(int space); string CLR_ATest(int space); string MOVX_A_Ri_1Test(int space); string MOVX_A_DPTRTest(int space); string DJNZ_Rn_RelRTest(int space); string XCHD_A_Ri_1Test(int space); string DJNZ_Direct_RelTest(int space); string DA_ATest(int space); string SETB_CTest(int space); string SETB_BitTest(int space); string POP_DirectTest(int space); string XCH_A_RnTest(int space); string XCH_A_DirectTest(int space); string SWAP_ATest(int space); string CLR_CTest(int space); string CLR_BitTest(int space); string PUSH_DirectTest(int space); //86spark string MOV_Direct_Rn_Test(int space); string MOV_Direct_Ri_Test(int space); string MOV_DPTR_Data_Test(int space); string MOV_Bit_C_Test(int space); string MOV_C_Bit_Test(int space); string MOVC_A_DPTR_Test(int space); string SUBB_A_Data_Test(int space); string SUBB_A_RnTest(int space); string SUBB_A_RiTest(int space); string SUBB_A_DirectTest(int space); string MOV_Rn_Direct_Test(int space); string MOV_Ri_Direct_Test(int space); string CJNE_Rn_Data_Rel_Test(int space); string CJNE_Ri_Data_Rel_Test(int space); string CJNE_A_Direct_Rel_Test(int space); string CJNE_A_Data_Rel_Test(int space); string CPL_C_Test(int space); string CPL_Bit_Test(int space); string ACALL_Addr11_Test(int space); string ANL_C_Bit_1_Test(int space); string MUL_AB_Test(int space); string INC_DPTR_Test(int space); string AJMP_Addr11_Test(int space); string ORL_C_Bit_Test(int space); string MOV_Ri_ATest(int space); string XCH_A_RiTest(int space); string JNC_RelTest(int space); void TestRun(); string PrintCMDUntested(void); CTestMcu(CVm8051 *pCVir8051); virtual ~CTestMcu(); }; #endif /* TESTMCU_H_ */
rickytan/RTIconButton
Example/RTIconButton/RTTableViewController.h
<reponame>rickytan/RTIconButton // // RTTableViewController.h // RTIconButton // // Created by Ricky on 2017/7/25. // Copyright © 2017年 rickytan. All rights reserved. // #import <UIKit/UIKit.h> @interface RTTableViewController : UITableViewController @end
rickytan/RTIconButton
Example/RTIconButton/RTViewController.h
<gh_stars>10-100 // // RTViewController.h // RTIconButton // // Created by rickytan on 09/28/2015. // Copyright (c) 2015 rickytan. All rights reserved. // @import UIKit; @interface RTViewController : UIViewController @end
dk-dev/bitlash
src/eeprom.c
/*** eeprom.c: minimal eeprom interface The author can be reached at: <EMAIL> Copyright (C) 2008-2012 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***/ #include "bitlash.h" #if defined(EEPROM_MICROCHIP_24XX32A) #include "Wire.h" // A cache to speed up eeprom reads uint8_t cache_eeprom[ENDEEPROM]; // read a 32 byte page from eeprom // source: https://github.com/IngloriousEngineer/Arduino void extEEPROMreadPage(int EEPROM_addr, int addr, uint8_t* data_target, int amount, int offset) { Wire.beginTransmission(EEPROM_addr); Wire.write(highByte(addr)); Wire.write(lowByte(addr)); Wire.endTransmission(true); Wire.requestFrom(EEPROM_addr, amount, true); while(Wire.available() == 0) {} for(int i = 0; i<amount; i++) data_target[offset + i] = Wire.read(); } // initializes I2C bus and loads eeprom contents into cache void eeinit(void) { Wire.begin(); for(int offset=0; offset<=ENDEEPROM; offset+=32) { extEEPROMreadPage(EEPROM_ADDRESS, offset, cache_eeprom, 32, offset); } } // write a single byte to eeprom // source: https://github.com/IngloriousEngineer/Arduino void eewrite(int addr, uint8_t value) { // update cache first cache_eeprom[addr] = value; // write back to eeprom Wire.beginTransmission(EEPROM_ADDRESS); Wire.write(highByte(addr)); Wire.write(lowByte(addr)); Wire.write((byte) value); Wire.endTransmission(true); delay(6); } uint8_t eeread(int addr) { return cache_eeprom[addr]; } #elif (defined(AVR_BUILD)) || ( (defined(ARM_BUILD)) && (ARM_BUILD==2)) // AVR or Teensy 3 #include "avr/eeprom.h" void eewrite(int addr, uint8_t value) { eeprom_write_byte((unsigned char *) addr, value); } uint8_t eeread(int addr) { return eeprom_read_byte((unsigned char *) addr); } #if defined(ARM_BUILD) // Initialize Teensy 3 eeprom void eeinit(void) { eeprom_initialize(); } #endif #elif defined(ARM_BUILD) #if ARM_BUILD!=2 // A little fake eeprom for ARM testing char virtual_eeprom[E2END]; void eeinit(void) { for (int i=0; i<E2END; i++) virtual_eeprom[i] = 255; } void eewrite(int addr, uint8_t value) { virtual_eeprom[addr] = value; } uint8_t eeread(int addr) { return virtual_eeprom[addr]; } #endif #endif
lasiqueira/8080emu
main.c
<filename>main.c #include <stdio.h> #include <stdlib.h> int disassemble_8080_op(unsigned char *code_buffer, int pos); void unimplemented_instruction(State8080* state); int emulate_8080_op(State8080* state); int parity(int x, int size); typedef struct ConditionCodes{ uint8_t z:1; uint8_t s:1; uint8_t p:1; uint8_t cy:1; uint8_t ac:1; uint8_t pad:3; }ConditionCodes; typedef struct State8080{ uint8_t a; uint8_t b; uint8_t c; uint8_t d; uint8_t e; uint8_t h; uint8_t l; uint16_t sp; uint16_t pc; uint8_t *memory; struct ConditionCodes cc; uint8_t int_enable; } State8080; int main(int argc, char**argv) { FILE *file = fopen(argv[1], "rb"); if(file == NULL) { printf("error: Could't open %s\n", argv[1]); } //Get the file size and read it into a memory buffer fseek(file, 0L, SEEK_END); int file_size = ftell(file); fseek(file, 0L, SEEK_SET); unsigned char *buffer = malloc(file_size); fread(buffer, file_size, 1, file); fclose(file); int pc= 0; while(pc < file_size) { pc += disassemble_8080_op(buffer, pc); } return 0; } int disassemble_8080_op(unsigned char *code_buffer, int pc) { unsigned char *code = &code_buffer[pc]; int op_bytes = 1; printf("%04x ", pc); switch(*code){ case 0x00: printf("NOP"); break; case 0x01: printf("LXI B,#$%02x%02x", code[2], code[1]); op_bytes=3; break; case 0x02: printf("STAX B"); break; case 0x03: printf("INX B"); break; case 0x04: printf("INR B"); break; case 0x05: printf("DCR B"); break; case 0x06: printf("MVI B,#$%02x", code[1]); op_bytes=2; break; case 0x07: printf("RLC"); break; case 0x08: printf("NOP"); break; case 0x09: printf("DAD B"); break; case 0x0a: printf("LDAX B"); break; case 0x0b: printf("DCX B"); break; case 0x0c: printf("INR C"); break; case 0x0d: printf("DCR C"); break; case 0x0e: printf("MVI C,#$02x", code[1]); op_bytes=2; break; case 0x0f: printf("RRC"); break; case 0x10: printf("NOP"); break; case 0x11: printf("LXI D,#$%02x%02x", code[2], code[1]); op_bytes=3; break; case 0x12: printf("STAX D"); break; case 0x13: printf("INX D"); break; case 0x14: printf("INR D"); break; case 0x15: printf("DCR D"); break; case 0x16: printf("MVI D,#$%02x", code[1]); op_bytes=2; break; case 0x17: printf("RAL"); break; case 0x18: printf("NOP"); break; case 0x19: printf("DAD D"); break; case 0x1a: printf("LDAX D"); break; case 0x1b: printf("DCX D"); break; case 0x1c: printf("INR E"); break; case 0x1d: printf("DCR E"); break; case 0x1e: printf("MVI E,#$%02x", code[1]); op_bytes=2; break; case 0x1f: printf("RAR"); break; case 0x20: printf("RIM"); break; case 0x21: printf("LXI H,#$%02x%02x", code[2], code[1]); op_bytes=3; break; case 0x22: printf("SHLD $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0x23: printf("INX H"); break; case 0x24: printf("INR H"); break; case 0x25: printf("DCR H"); break; case 0x26: printf("MVI H,#$02x", code[1]); op_bytes=2; break; case 0x27: printf("DAA"); break; case 0x28: printf("NOP"); break; case 0x29: printf("DAD H"); break; case 0x2a: printf("LHLD $02x%02x", code[2], code[1]); op_bytes=3; break; case 0x2b: printf("DCX H"); break; case 0x2c: printf("INR L"); break; case 0x2d: printf("DCR L"); break; case 0x2e: printf("MVI L,#$%02x", code[1]); op_bytes=2; break; case 0x2f: printf("CMA"); break; case 0x30: printf("SIM"); break; case 0x31: printf("LXI SP,%$02x%02x", code[2], code[1]); op_bytes=3; break; case 0x32: printf("STA $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0x33: printf("INX SP"); break; case 0x34: printf("INR M"); break; case 0x35: printf("DCR M"); break; case 0x36: printf("MVI M,#$%02x", code[1]); op_bytes=2; break; case 0x37: printf("STC"); break; case 0x38: printf("NOP"); break; case 0x39: printf("DAD SP"); break; case 0x3a: printf("LDA $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0x3b: printf("DCX SP"); break; case 0x3c: printf("INR A"); break; case 0x3d: printf("DCR A"); break; case 0x3e: printf("MVI A,#$%02x", code[1]); op_bytes=2; break; case 0x3f: printf("CMC"); break; case 0x40: printf("MOV B,B"); break; case 0x41: printf("MOV B,C"); break; case 0x42: printf("MOV B,D"); break; case 0x43: printf("MOV B,E"); break; case 0x44: printf("MOV B,H"); break; case 0x45: printf("MOV B,L"); break; case 0x46: printf("MOV B,M"); break; case 0x47: printf("MOV B,A"); break; case 0x48: printf("MOV C,B"); break; case 0x49: printf("MOV C,C"); break; case 0x4a: printf("MOV C,D"); break; case 0x4b: printf("MOV C,E"); break; case 0x4c: printf("MOV C,H"); break; case 0x4d: printf("MOV C,L"); break; case 0x4e: printf("MOV C,M"); break; case 0x4f: printf("MOV C,A"); break; case 0x50: printf("MOV D,B"); break; case 0x51: printf("MOV D,C"); break; case 0x52: printf("MOV D,D"); break; case 0x53: printf("MOV D,E"); break; case 0x54: printf("MOV D,H"); break; case 0x55: printf("MOV D,L"); break; case 0x56: printf("MOV D,M"); break; case 0x57: printf("MOV D,A"); break; case 0x58: printf("MOV E,B"); break; case 0x59: printf("MOV E,C"); break; case 0x5a: printf("MOV E,D"); break; case 0x5b: printf("MOV E,E"); break; case 0x5c: printf("MOV E,H"); break; case 0x5d: printf("MOV E,L"); break; case 0x5e: printf("MOV E,M"); break; case 0x5f: printf("MOV E,A"); break; case 0x60: printf("MOV H,B"); break; case 0x61: printf("MOV H,C"); break; case 0x62: printf("MOV H,D"); break; case 0x63: printf("MOV H,E"); break; case 0x64: printf("MOV H,H"); break; case 0x65: printf("MOV H,L"); break; case 0x66: printf("MOV H,M"); break; case 0x67: printf("MOV H,A"); break; case 0x68: printf("MOV L,B"); break; case 0x69: printf("MOV L,C"); break; case 0x6a: printf("MOV L,D"); break; case 0x6b: printf("MOV L,E"); break; case 0x6c: printf("MOV L,H"); break; case 0x6d: printf("MOV L,L"); break; case 0x6e: printf("MOV L,M"); break; case 0x6f: printf("MOV L,A"); break; case 0x70: printf("MOV M,B"); break; case 0x71: printf("MOV M,C"); break; case 0x72: printf("MOV M,D"); break; case 0x73: printf("MOV M,E"); break; case 0x74: printf("MOV M,H"); break; case 0x75: printf("MOV M,L"); break; case 0x76: printf("HLT"); break; case 0x77: printf("MOV M,A"); break; case 0x78: printf("MOV A,B"); break; case 0x79: printf("MOV A,C"); break; case 0x7a: printf("MOV A,D"); break; case 0x7b: printf("MOV A,E"); break; case 0x7c: printf("MOV A,H"); break; case 0x7d: printf("MOV A,L"); break; case 0x7e: printf("MOV A,M"); break; case 0x7f: printf("MOV A,A"); break; case 0x80: printf("ADD B"); break; case 0x81: printf("ADD C"); break; case 0x82: printf("ADD D"); break; case 0x83: printf("ADD E"); break; case 0x84: printf("ADD H"); break; case 0x85: printf("ADD L"); break; case 0x86: printf("ADD M"); break; case 0x87: printf("ADD A"); break; case 0x88: printf("ADC B"); break; case 0x89: printf("ADC C"); break; case 0x8a: printf("ADC D"); break; case 0x8b: printf("ADC E"); break; case 0x8c: printf("ADC H"); break; case 0x8d: printf("ADC L"); break; case 0x8e: printf("ADC M"); break; case 0x8f: printf("ADC A"); break; case 0x90: printf("SUB B"); break; case 0x91: printf("SUB C"); break; case 0x92: printf("SUB D"); break; case 0x93: printf("SUB E"); break; case 0x94: printf("SUB H"); break; case 0x95: printf("SUB L"); break; case 0x96: printf("SUB M"); break; case 0x97: printf("SUB A"); break; case 0x98: printf("SBB B"); break; case 0x99: printf("SBB C"); break; case 0x9a: printf("SBB D"); break; case 0x9b: printf("SBB E"); break; case 0x9c: printf("SBB H"); break; case 0x9d: printf("SBB L"); break; case 0x9e: printf("SBB M"); break; case 0x9f: printf("SBB A"); break; case 0xa0: printf("ANA B"); break; case 0xa1: printf("ANA C"); break; case 0xa2: printf("ANA D"); break; case 0xa3: printf("ANA E"); break; case 0xa4: printf("ANA H"); break; case 0xa5: printf("ANA L"); break; case 0xa6: printf("ANA M"); break; case 0xa7: printf("ANA A"); break; case 0xa8: printf("XRA B"); break; case 0xa9: printf("XRA C"); break; case 0xaa: printf("XRA D"); break; case 0xab: printf("XRA E"); break; case 0xac: printf("XRA H"); break; case 0xad: printf("XRA L"); break; case 0xae: printf("XRA M"); break; case 0xaf: printf("XRA A"); break; case 0xb0: printf("ORA B"); break; case 0xb1: printf("ORA C"); break; case 0xb2: printf("ORA D"); break; case 0xb3: printf("ORA E"); break; case 0xb4: printf("ORA H"); break; case 0xb5: printf("ORA L"); break; case 0xb6: printf("ORA M"); break; case 0xb7: printf("ORA A"); break; case 0xb8: printf("CMP B"); break; case 0xb9: printf("CMP C"); break; case 0xba: printf("CMP D"); break; case 0xbb: printf("CMP E"); break; case 0xbc: printf("CMP H"); break; case 0xbd: printf("CMP L"); break; case 0xbe: printf("CMP M"); break; case 0xbf: printf("CMP A"); break; case 0xc0: printf("RNZ"); break; case 0xc1: printf("POP B"); break; case 0xc2: printf("JNZ $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xc3: printf("JMP $%02x%02x",code[2],code[1]); op_bytes=3; break; case 0xc4: printf("CNZ $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xc5: printf("PUSH B"); break; case 0xc6: printf("ADI D,#$%02x", code[1]); op_bytes=2; break; case 0xc7: printf("RST 0"); break; case 0xc8: printf("RZ"); break; case 0xc9: printf("RET"); break; case 0xca: printf("JZ $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xcb: printf("NOP"); break; case 0xcc: printf("CZ $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xcd: printf("CALL $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xce: printf("ACI #$%02x", code[1]); op_bytes=2; break; case 0xcf: printf("RST 1"); break; case 0xd0: printf("RNC"); break; case 0xd1: printf("POP D"); break; case 0xd2: printf("JNC $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xd3: printf("OUT #$%02x", code[1]); op_bytes=2; break; case 0xd4: printf("CNC $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xd5: printf("PUSH D"); break; case 0xd6: printf("SUI #$%02x", code[1]); op_bytes=2; break; case 0xd7: printf("RST 2"); break; case 0xd8: printf("RC"); break; case 0xd9: printf("NOP"); break; case 0xda: printf("JC $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xdb: printf("IN #$%02x", code[1]); op_bytes=2; break; case 0xdc: printf("CC $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xdd: printf("NOP"); break; case 0xde: printf("SBI #$%02x", code[1]); op_bytes=2; break; case 0xdf: printf("RST 3"); break; case 0xe0: printf("RPO"); break; case 0xe1: printf("POP H"); break; case 0xe2: printf("JPO $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xe3: printf("XTHL"); break; case 0xe4: printf("CPO $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xe5: printf("PUSH H"); break; case 0xe6: printf("ANI #$%02x", code[1]); op_bytes=2; break; case 0xe7: printf("RST 4"); break; case 0xe8: printf("RPE"); break; case 0xe9: printf("PCHL"); break; case 0xea: printf("JPE $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xeb: printf("XCHG"); break; case 0xec: printf("CPE $%02x%02x", code[2, code[1]]); op_bytes=3; break; case 0xed: printf("NOP"); break; case 0xee: printf("XRI #$%02x", code[1]); op_bytes=2; break; case 0xef: printf("RST 5"); break; case 0xf0: printf("RP"); break; case 0xf1: printf("POP PSW"); break; case 0xf2: printf("JP $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xf3: printf("DI"); break; case 0xf4: printf("CP $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xf5: printf("PUSH PSW"); break; case 0xf6: printf("ORI #$%02x", code[1]); op_bytes=2; break; case 0xf7: printf("RST 6"); break; case 0xf8: printf("RM"); break; case 0xf9: printf("SPHL"); break; case 0xfa: printf("JM $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xfb: printf("EI"); break; case 0xfc: printf("CM $%02x%02x", code[2], code[1]); op_bytes=3; break; case 0xfd: printf("NOP"); break; case 0xfe: printf("CPI #$%02x", code[1]); op_bytes=2; break; case 0xff: printf("RST 7"); break; } printf("\n"); return op_bytes; } void unimplemented_instruction(State8080* state) { //pc will have advanced one, so undo that printf ("Error: Unimplemented instruction\n"); exit(1); } int emulate_8080_op(State8080* state) { unsigned char *op_code = &state->memory[state->pc]; switch(*op_code) { case 0x00: break; case 0x01: state->b = op_code[2]; state->c = op_code[1]; state->pc += 2; break; case 0x02: unimplemented_instruction(state); break; case 0x03: unimplemented_instruction(state); break; case 0x04: unimplemented_instruction(state); break; case 0x05: unimplemented_instruction(state); break; case 0x06: unimplemented_instruction(state); break; case 0x07: unimplemented_instruction(state); break; case 0x08: break; case 0x09: unimplemented_instruction(state); break; case 0x0a: unimplemented_instruction(state); break; case 0x0b: unimplemented_instruction(state); break; case 0x0c: unimplemented_instruction(state); break; case 0x0d: unimplemented_instruction(state); break; case 0x0e: unimplemented_instruction(state); break; case 0x0f: unimplemented_instruction(state); break; case 0x10: break; case 0x11: state->d = op_code[2]; state->e = op_code[1]; state->pc += 2; break; case 0x12: unimplemented_instruction(state); break; case 0x13: unimplemented_instruction(state); break; case 0x14: unimplemented_instruction(state); break; case 0x15: unimplemented_instruction(state); break; case 0x16: unimplemented_instruction(state); break; case 0x17: unimplemented_instruction(state); break; case 0x18: break; case 0x19: unimplemented_instruction(state); break; case 0x1a: unimplemented_instruction(state); break; case 0x1b: unimplemented_instruction(state); break; case 0x1c: unimplemented_instruction(state); break; case 0x1d: unimplemented_instruction(state); break; case 0x1e: unimplemented_instruction(state); break; case 0x1f: unimplemented_instruction(state); break; case 0x20: unimplemented_instruction(state); break; case 0x21: state->h = op_code[2]; state->l = op_code[1]; state->pc += 2; break; break; case 0x22: unimplemented_instruction(state); break; case 0x23: unimplemented_instruction(state); break; case 0x24: unimplemented_instruction(state); break; case 0x25: unimplemented_instruction(state); break; case 0x26: unimplemented_instruction(state); break; case 0x27: unimplemented_instruction(state); break; case 0x28: break; case 0x29: unimplemented_instruction(state); break; case 0x2a: unimplemented_instruction(state); break; case 0x2b: unimplemented_instruction(state); break; case 0x2c: unimplemented_instruction(state); break; case 0x2d: unimplemented_instruction(state); break; case 0x2e: unimplemented_instruction(state); break; case 0x2f: unimplemented_instruction(state); break; case 0x30: unimplemented_instruction(state); break; case 0x31: unimplemented_instruction(state); break; case 0x32: unimplemented_instruction(state); break; case 0x33: unimplemented_instruction(state); break; case 0x34: unimplemented_instruction(state); break; case 0x35: unimplemented_instruction(state); break; case 0x36: unimplemented_instruction(state); break; case 0x37: unimplemented_instruction(state); break; case 0x38: break; case 0x39: unimplemented_instruction(state); break; case 0x3a: unimplemented_instruction(state); break; case 0x3b: unimplemented_instruction(state); break; case 0x3c: unimplemented_instruction(state); break; case 0x3d: unimplemented_instruction(state); break; case 0x3e: unimplemented_instruction(state); break; case 0x3f: unimplemented_instruction(state); break; case 0x40: state->b = state->b; break; case 0x41: state->b = state->c; break; case 0x42: state->b = state->d; break; case 0x43: state->b = state->e; break; case 0x44: state->b = state->h; break; case 0x45: state->b = state->l; break; case 0x46: unimplemented_instruction(state); break; case 0x47: state->b = state->a; break; case 0x48: state->c = state->b; break; case 0x49: state->c = state->c; break; case 0x4a: state->c = state->d; break; case 0x4b: state->c = state->e; break; case 0x4c: state->c = state->h; break; case 0x4d: state->c = state->l; break; case 0x4e: unimplemented_instruction(state); break; case 0x4f: state->c = state->a; break; case 0x50: state->d = state->b; break; case 0x51: state->d = state->c; break; case 0x52: state->d = state->d; break; case 0x53: state->d = state->e; break; case 0x54: state->d = state->h; break; case 0x55: state->d = state->l; break; case 0x56: unimplemented_instruction(state); break; case 0x57: state->d = state->a; break; case 0x58: state->e = state->b; break; case 0x59: state->e = state->c; break; case 0x5a: state->e = state->d; break; case 0x5b: state->e = state->e; break; case 0x5c: state->e = state->h; break; case 0x5d: state->e = state->l; break; case 0x5e: unimplemented_instruction(state); break; case 0x5f: state->e = state->a; break; case 0x60: state->h = state->b; break; case 0x61: state->h = state->c; break; case 0x62: state->h = state->d; break; case 0x63: state->h = state->e; break; case 0x64: state->h = state->h; break; case 0x65: state->h = state->l; break; case 0x66: unimplemented_instruction(state); break; case 0x67: state->h = state->a; break; case 0x68: state->l = state->b; break; case 0x69: state->l = state->c; break; case 0x6a: state->l = state->d; break; case 0x6b: state->l = state->e; break; case 0x6c: state->l = state->h; break; case 0x6d: state->l = state->l; break; case 0x6e: unimplemented_instruction(state); break; case 0x6f: state->l = state->a; break; case 0x70: unimplemented_instruction(state); break; case 0x71: unimplemented_instruction(state); break; case 0x72: unimplemented_instruction(state); break; case 0x73: unimplemented_instruction(state); break; case 0x74: unimplemented_instruction(state); break; case 0x75: unimplemented_instruction(state); break; case 0x76: unimplemented_instruction(state); break; case 0x77: unimplemented_instruction(state); break; case 0x78: state->a = state->b; break; case 0x79: state->a = state->c; break; case 0x7a: state->a = state->d; break; case 0x7b: state->a = state->e; break; case 0x7c: state->a = state->h; break; case 0x7d: state->a = state->l; break; case 0x7e: unimplemented_instruction(state); break; case 0x7f: state->a = state->a; break; case 0x80: { uint16_t answer = (uint16_t) state->a + (uint16_t) state->b; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0x81: { uint16_t answer = (uint16_t) state->a + (uint16_t) state->c; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0x82: { uint16_t answer = (uint16_t) state->a + (uint16_t) state->d; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0x83: { uint16_t answer = (uint16_t) state->a + (uint16_t) state->e; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0x84: { uint16_t answer = (uint16_t) state->a + (uint16_t) state->h; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0x85: { uint16_t answer = (uint16_t) state->a + (uint16_t) state->l; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0x86: unimplemented_instruction(state); break; case 0x87: { uint16_t answer = (uint16_t) state->a + (uint16_t) state->a; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0x88: unimplemented_instruction(state); break; case 0x89: unimplemented_instruction(state); break; case 0x8a: unimplemented_instruction(state); break; case 0x8b: unimplemented_instruction(state); break; case 0x8c: unimplemented_instruction(state); break; case 0x8d: unimplemented_instruction(state); break; case 0x8e: unimplemented_instruction(state); break; case 0x8f: unimplemented_instruction(state); break; case 0x90: unimplemented_instruction(state); break; case 0x91: unimplemented_instruction(state); break; case 0x92: unimplemented_instruction(state); break; case 0x93: unimplemented_instruction(state); break; case 0x94: unimplemented_instruction(state); break; case 0x95: unimplemented_instruction(state); break; case 0x96: unimplemented_instruction(state); break; case 0x97: unimplemented_instruction(state); break; case 0x98: unimplemented_instruction(state); break; case 0x99: unimplemented_instruction(state); break; case 0x9a: unimplemented_instruction(state); break; case 0x9b: unimplemented_instruction(state); break; case 0x9c: unimplemented_instruction(state); break; case 0x9d: unimplemented_instruction(state); break; case 0x9e: unimplemented_instruction(state); break; case 0x9f: unimplemented_instruction(state); break; case 0xa0: unimplemented_instruction(state); break; case 0xa1: unimplemented_instruction(state); break; case 0xa2: unimplemented_instruction(state); break; case 0xa3: unimplemented_instruction(state); break; case 0xa4: unimplemented_instruction(state); break; case 0xa5: unimplemented_instruction(state); break; case 0xa6: unimplemented_instruction(state); break; case 0xa7: unimplemented_instruction(state); break; case 0xa8: unimplemented_instruction(state); break; case 0xa9: unimplemented_instruction(state); break; case 0xaa: unimplemented_instruction(state); break; case 0xab: unimplemented_instruction(state); break; case 0xac: unimplemented_instruction(state); break; case 0xad: unimplemented_instruction(state); break; case 0xae: unimplemented_instruction(state); break; case 0xaf: unimplemented_instruction(state); break; case 0xb0: unimplemented_instruction(state); break; case 0xb1: unimplemented_instruction(state); break; case 0xb2: unimplemented_instruction(state); break; case 0xb3: unimplemented_instruction(state); break; case 0xb4: unimplemented_instruction(state); break; case 0xb5: unimplemented_instruction(state); break; case 0xb6: unimplemented_instruction(state); break; case 0xb7: unimplemented_instruction(state); break; case 0xb8: unimplemented_instruction(state); break; case 0xb9: unimplemented_instruction(state); break; case 0xba: unimplemented_instruction(state); break; case 0xbb: unimplemented_instruction(state); break; case 0xbc: unimplemented_instruction(state); break; case 0xbd: unimplemented_instruction(state); break; case 0xbe: unimplemented_instruction(state); break; case 0xbf: unimplemented_instruction(state); break; case 0xc0: unimplemented_instruction(state); break; case 0xc1: unimplemented_instruction(state); break; case 0xc2: unimplemented_instruction(state); break; case 0xc3: unimplemented_instruction(state); break; case 0xc4: unimplemented_instruction(state); break; case 0xc5: unimplemented_instruction(state); break; case 0xc6: { uint16_t answer = (uint16_t) state->a + (uint16_t) opcode[1]; state->cc.z = ((answer & 0xff) == 0); state->cc.s = ((answer & 0x80) != 0); state->cc.cy = (answer > 0xff); state->cc.p = Parity(answer&0xff); state->a = answer & 0xff; } break; case 0xc7: unimplemented_instruction(state); break; case 0xc8: unimplemented_instruction(state); break; case 0xc9: unimplemented_instruction(state); break; case 0xca: unimplemented_instruction(state); break; case 0xcb: break; case 0xcc: unimplemented_instruction(state); break; case 0xcd: unimplemented_instruction(state); break; case 0xce: unimplemented_instruction(state); break; case 0xcf: unimplemented_instruction(state); break; case 0xd0: unimplemented_instruction(state); break; case 0xd1: unimplemented_instruction(state); break; case 0xd2: unimplemented_instruction(state); break; case 0xd3: unimplemented_instruction(state); break; case 0xd4: unimplemented_instruction(state); break; case 0xd5: unimplemented_instruction(state); break; case 0xd6: unimplemented_instruction(state); break; case 0xd7: unimplemented_instruction(state); break; case 0xd8: unimplemented_instruction(state); break; case 0xd9: break; case 0xda: unimplemented_instruction(state); break; case 0xdb: unimplemented_instruction(state); break; case 0xdc: unimplemented_instruction(state); break; case 0xdd: break; case 0xde: unimplemented_instruction(state); break; case 0xdf: unimplemented_instruction(state); break; case 0xe0: unimplemented_instruction(state); break; case 0xe1: unimplemented_instruction(state); break; case 0xe2: unimplemented_instruction(state); break; case 0xe3: unimplemented_instruction(state); break; case 0xe4: unimplemented_instruction(state); break; case 0xe5: unimplemented_instruction(state); break; case 0xe6: unimplemented_instruction(state); break; case 0xe7: unimplemented_instruction(state); break; case 0xe8: unimplemented_instruction(state); break; case 0xe9: unimplemented_instruction(state); break; case 0xea: unimplemented_instruction(state); break; case 0xeb: unimplemented_instruction(state); break; case 0xec: unimplemented_instruction(state); break; case 0xed: break; case 0xee: unimplemented_instruction(state); break; case 0xef: unimplemented_instruction(state); break; case 0xf0: unimplemented_instruction(state); break; case 0xf1: unimplemented_instruction(state); break; case 0xf2: unimplemented_instruction(state); break; case 0xf3: unimplemented_instruction(state); break; case 0xf4: unimplemented_instruction(state); break; case 0xf5: unimplemented_instruction(state); break; case 0xf6: unimplemented_instruction(state); break; case 0xf7: unimplemented_instruction(state); break; case 0xf8: unimplemented_instruction(state); break; case 0xf9: unimplemented_instruction(state); break; case 0xfa: unimplemented_instruction(state); break; case 0xfb: unimplemented_instruction(state); break; case 0xfc: unimplemented_instruction(state); break; case 0xfd: break; case 0xfe: unimplemented_instruction(state); break; case 0xff: unimplemented_instruction(state); break; } state->pc+=1; //for the opcode } int parity(int x, int size) { int i; int p = 0; x = (x & ((1<<size)-1)); for (i=0; i<size; i++) { if (x & 0x1) p++; x = x >> 1; } return (0 == (p & 0x1)); }
Schumbi/mqtt-schalter
src/schalter.h
#ifndef SCHALTER_H #define SCHALTER_H #include <Arduino.h> #include <ESP8266HTTPUpdateServer.h> #include <ESP8266WebServer.h> #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #include <PubSubClient.h> #include <TickerScheduler.h> #include <WiFiUdp.h> #include "conf.hpp" #define STARTDATE 1514761200l // net_dev static const char* hostname = WEBNAME; // wifi static const char* myssid = wifi_config::ssid; static const char* mypass = wifi_config::ssid_password; // mqtt static const char* mqtt_server = net_dev::mqtt_device::mqtt_server; static const int mqtt_server_port = net_dev::mqtt_device::mqtt_server_port; static const String mqtt_state_string = net_dev::mqtt_device::mqtt_device_topic; static const String mqtt_time_string = net_dev::mqtt_device::mqtt_device_topic_time; static const String mqtt_time_tick = net_dev::mqtt_device::mqtt_device_topic_timetick; static const String mqtt_date_string = net_dev::mqtt_device::mqtt_device_topic_date; // web update static const char* update_path = net_dev::update::web_update_path; static const int update_port = net_dev::update::update_port; static const char* update_username = net_dev::update::user; static const char* update_passwort = net_dev::update::pass; #endif // SCHALTER_H
qwqw3qee/cryptography_with_c
MD5/MD5.h
<reponame>qwqw3qee/cryptography_with_c<filename>MD5/MD5.h #ifndef MD5_H_INCLUDED #define MD5_H_INCLUDED /** https://blog.csdn.net/chudongfang2015/article/details/51736426 **/ #include <stdio.h> #include <math.h> #include <string.h> #define ROTATE_LEFT(x,n) (((x) << (n)) | ((x) >> (32-(n)))) #define F(x,y,z) (((x)&(y))|(((~(x))&(z)))) #define G(x,y,z) (((x)&(z))|((y)&(~(z)))) #define H(x,y,z) ((x)^(y)^(z)) #define I(x,y,z) ((y)^((x)|(~(z)))) #define FF(a,b,c,d,m,y,rol) {(a)+=F((b),(c),(d))+(m)+(y);(a)=ROTATE_LEFT((a),(rol));(a)+=(b);} #define GG(a,b,c,d,m,y,rol) {(a)+=G((b),(c),(d))+(m)+(y);(a)=ROTATE_LEFT((a),(rol));(a)+=(b);} #define HH(a,b,c,d,m,y,rol) {(a)+=H((b),(c),(d))+(m)+(y);(a)=ROTATE_LEFT((a),(rol));(a)+=(b);} #define II(a,b,c,d,m,y,rol) {(a)+=I((b),(c),(d))+(m)+(y);(a)=ROTATE_LEFT((a),(rol));(a)+=(b);} typedef long long ll; typedef struct { unsigned int count[2]; unsigned int state[4]; unsigned char buffer[64]; }MD5_CTX; void MD5Init(MD5_CTX *context); //void initConY(unsigned int* conY); void MD5Update(MD5_CTX* context,unsigned char* input,unsigned int inputlen); void MD5Final(MD5_CTX* context,unsigned char digest[16]); void MD5Transform(unsigned int state[4],unsigned char block[64]); #endif // MD5_H_INCLUDED
qwqw3qee/cryptography_with_c
ELGamal/ELGamal.h
<filename>ELGamal/ELGamal.h #ifndef ELGAMAL_H_INCLUDED #define ELGAMAL_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <string.h> #include "BIGNUM_BIN_32.h" #include "BASE64.h" #include "MD5.h" #define KEYSIZE 512 typedef struct elgamalkey { int type; BIGNUM y,g,p; BIGNUM x; }ELGKEY,*pELGKEY; typedef struct elgamalsign { int valid; BIGNUM m,r,s; }ELGSIGN,*pELGSIGN; int MD5_gets(unsigned char* md5val,unsigned char* str,int len); int MD52char(char* md5,unsigned char* md5val); int ELG_genKey(pELGKEY priKey,pELGKEY pubKey); void ELG_key_printf(const ELGKEY* a,int base); void ELG_sign_printf(const ELGSIGN* sign,int base); int ELG_sign(pELGSIGN elgSign,const BIGNUM* m,const ELGKEY* priKey); int ELG_verify(const ELGSIGN* elgSign,const ELGKEY* pubKey); int ELG_bn2base64(char* s,const BIGNUM* bn,int blen); int ELG_base642bn(pBIGNUM bn,const char* s,int len); int ELG_key2base64(char* s,const ELGKEY* key); int ELG_base642key(ELGKEY* key,const char* s); int ELG_sign2base64(char* s,const ELGSIGN* sign); int ELG_base642sign(pELGSIGN sign,const char* s,int len); int ELG_char2bn(pBIGNUM bn,const char* str,int len); int ELG_bn2char(char* str,const BIGNUM* bn,int len); int ELG_sign_md5(pELGSIGN elgSign,const char* md5,const ELGKEY* priKey); int ELG_sign_text(pELGSIGN elgSign,const char* str,int len,const ELGKEY* priKey); int ELG_cmp_signature_text(const char* str,int len,const ELGSIGN* elgSign); int ELG_cmp_signature_md5(const char* md5,const ELGSIGN* elgSign); int ELG_key2file(const char* filename,const ELGKEY* key); int ELG_file2key(pELGKEY key,const char* filename); int ELG_getfile_md5(char* md5,const char* filename); #endif // ELGAMAL_H_INCLUDED
dj95/fn-notify
src/config.h
#define BG_COLOR "A0171717" #define FG_COLOR "FFFFFFFF" #define FG_MUTED "FF5D5D5D"
dj95/fn-notify
src/fn-notify.c
<gh_stars>1-10 /* * * fn-notify * * (c) 2017 <NAME> */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pwd.h> #include <math.h> #include <signal.h> #include <pthread.h> #include <sys/types.h> #include <fcntl.h> #include <errno.h> #include "draw.h" #define MAX(a,b) ((a) > (b) ? (a) : (b)) Display *display; Window window; XSetWindowAttributes attributes; XGCValues gc_values; GC gc; int depth; int screen; Colormap colormap; int num; struct timespec tstart={0,0}, tend={0,0}; double executionLength = 1; void drawRoundCorners(void) { // get window attributes for width and height XWindowAttributes win_attr; XGetWindowAttributes(display, window, &win_attr); // extract window width and height int width = win_attr.width + win_attr.border_width; int height = win_attr.height + win_attr.border_width; // create a pixmap to draw the shaped window in Pixmap mask = XCreatePixmap(display, window, width, height, 1); XGCValues xgcv; // create a graphics context for the shaped window GC shape_gc = XCreateGC(display, mask, 0, &xgcv); // set radius und diameter int rad = 10; int dia = 2 * rad; // flush the gc XSetForeground(display, shape_gc, 0); XFillRectangle( display, mask, shape_gc, 0, 0, width, height); // draw the rounded corners first XSetForeground(display, shape_gc, 1); XFillArc( display, mask, shape_gc, 0, 0, dia, dia, 0, 360 * 64); XFillArc( display, mask, shape_gc, width - dia - 1, 0, dia, dia, 0, 360 * 64); XFillArc( display, mask, shape_gc, 0, height - dia - 1, dia, dia, 0, 360 * 64); XFillArc( display, mask, shape_gc, width - dia - 1, height - dia - 1, dia, dia, 0, 360 * 64); // draw the center rectangles of the window XFillRectangle( display, mask, shape_gc, rad, 0, width-dia, height); XFillRectangle( display, mask, shape_gc, 0, rad, width, height-dia); // combine the shape we created in the pixmap with a mask XShapeCombineMask(display, window, ShapeBounding, 0, 0, mask, ShapeSet); // free the pixmap XFreePixmap(display, mask); // apply the shape onto the window XShapeSelectInput(display, window, ShapeNotifyMask); } void* checkExit(void *args) { double diff_t; // get the start and end time clock_gettime(CLOCK_MONOTONIC, &tstart); clock_gettime(CLOCK_MONOTONIC, &tend); // create the difference between those times diff_t = ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec); // while the time difference is shorter than the execution time... while (diff_t < executionLength) { // ...get the actual time... clock_gettime(CLOCK_MONOTONIC, &tend); // ...calculate the new difference... diff_t = ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec); // ...and wait 100 milliseconds usleep(100); } // if the execution time is reache, exit gracefully exit(0); } char* concat(const char *s1, const char *s2) { // get length of both strings const size_t len1 = strlen(s1); const size_t len2 = strlen(s2); // allocate memory for both strings + null byte char *result = malloc(len1 + len2 + 1); // copy the strings into the result buffer memcpy(result, s1, len1); memcpy(result + len1, s2, len2 + 1); // return it return result; } int CheckForAnotherInstance(char* homedir) { #ifndef _MSC_VER int fd; struct flock fl; // path of the lock file in home char* path = "/.cache/fn-control.lock"; // conecatenate with path from homedir char* full_path = concat(homedir, path); // open the file or create it, if its non existant fd = open(full_path, O_RDWR | O_CREAT, S_IRWXU); // if an error occured, return 0 if (fd == -1) { printf("%s\n", strerror(errno)); return 0; } // set file lock parameter fl.l_type = F_WRLCK; // F_RDLCK, F_WRLCK, F_UNLCK fl.l_whence = SEEK_SET; // SEEK_SET, SEEK_CUR, SEEK_END fl.l_start = 0; // Offset from l_whence fl.l_len = 0; // length, 0 = to EOF fl.l_pid = getpid(); // our PID // try to create a file lock if( fcntl(fd, F_SETLK, &fl) == -1) { // we failed to create a file lock, meaning it's already locked if( errno == EACCES || errno == EAGAIN) { return 1; } } #endif return 0; } void sighandler(int signum) { printf("Caught signal %d, coming out...\n", signum); // get the new value FILE *fp; int i; // get the home directory char *homedir = getenv("HOME"); if (homedir == NULL) { printf("Error! Cannot get homedir\n"); } double diff_t; // get the actual time clock_gettime(CLOCK_MONOTONIC, &tend); // calculate the recent execution time diff_t = ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec); // set the new execution length to 1 second in the future executionLength = diff_t + 1; char* path = "/.cache/fn-control.save"; char* full_path = concat(homedir, path); // get value from save file fp = fopen(full_path, "r"); fscanf (fp, "%d", &i); fclose(fp); // get the mute status int mute = (int) ((i % 100) / 10); printf("%d\n", i); printf("%d\n", mute); int mode = i % 2; // get the volume value i = (int) i / 100; // calculate slider length int sliderLength = (int) (i * 1.6); // erase the old slider XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillRectangle(display, window, gc, 20, 175, 160, 5); // change color if muted if (mute) { drawVolumeIconMuted(); // draw a new one XSetForeground(display, gc, strtoul(FG_MUTED, 0, 16)); XFillRectangle(display, window, gc, 20, 175, sliderLength, 5); } else { switch (mode) { case 1: drawVolumeIcon(); break; case 2: drawBrightnessIcon(); break; default: break; } // draw a new one XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); XFillRectangle(display, window, gc, 20, 175, sliderLength, 5); } // flush the display to show the changes XFlush(display); } void init_window() { // open the display connection display = XOpenDisplay(NULL); // get screen properties XWindowAttributes xwAttr; XGetWindowAttributes( display, DefaultRootWindow(display), &xwAttr ); int screenWidth = xwAttr.width; int screenHeight = xwAttr.height; int width = 200; int height = 200; int x = (screenWidth / 2) - (width / 2); int y = (screenHeight / 2) - (height / 2); // build matching visual XVisualInfo vinfo; XMatchVisualInfo( display, DefaultScreen(display), 32, TrueColor, &vinfo ); // set window attributes XSetWindowAttributes attr; attr.colormap = XCreateColormap( display, DefaultRootWindow(display), vinfo.visual, AllocNone ); attr.border_pixel = 0; attr.background_pixel = strtoul(BG_COLOR, 0, 16); attr.override_redirect = 1; attr.event_mask = KeyPressMask | KeyReleaseMask | ExposureMask | SubstructureNotifyMask; // create the window window = XCreateWindow( display, DefaultRootWindow(display), x, y, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, CWColormap | CWBorderPixel | CWBackPixel | CWOverrideRedirect | CWEventMask, &attr ); XSelectInput(display, window, StructureNotifyMask); // create graphic context gc = XCreateGC(display, window, 0, 0); // set wm protocols Atom wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0); XSetWMProtocols(display, window, &wm_delete_window, 1); // set drawing color XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); drawRoundCorners(); // map the window and display it XMapWindow(display, window); } int main(int argc, char *argv[]) { // check if arguments are provided if (argc != 3 && argc != 4) { //TODO: multiple arguments and help text printf("No arguments provided\n"); exit(-1); } int mute = 0; int mode = 0; if (strncmp(argv[1], "vol", 3) == 0) { mode = 1; } if (strncmp(argv[1], "brig", 4) == 0) { mode = 2; } // check if the mute flag is set if (argc == 4) { printf("%s\n", argv[3]); if (strncmp(argv[3], "--mute", 6) == 0) { mute = 1; } } // get the home directory char *homedir = getenv("HOME"); if (homedir == NULL) { printf("Error! Cannot get homedir\n"); } // check if another instance is running int isRunning; isRunning = CheckForAnotherInstance(homedir); // initialize variables for the arguments char *p; num = 0; long conv = strtol(argv[2], &p, 10); errno = 0; // Check for errors: e.g., the string does not represent an integer // or the integer is larger than int if (errno != 0 || *p != '\0') { //TODO: handle wrong values } else { // No error num = conv; } if (isRunning == 1) { FILE *fp; char* path = "/.cache/fn-control.save"; char* full_path = concat(homedir, path); // write value to save file fp = fopen(full_path, "w+"); if (mute) { fprintf(fp, "%03d1%d", num, mode); } else { fprintf(fp, "%03d0%d", num, mode); } fclose(fp); printf("running\n"); // get pid of the running process char line[20]; FILE * command = popen("pidof fn-notify | cut -d' ' -f 2", "r"); fgets(line, 20, command); char number[strlen(line) + 1]; snprintf(number, strlen(line) + 1,"%s", line); pid_t pid = strtoul(number,NULL,10); pclose(command); // send SIGUSR1 to other process kill(pid, 10); // exit exit(0); } // initialize window init_window(); // calculate slider length int sliderLength = (int) (num * 1.6); if (mute == 1) { drawVolumeIconMuted(); // set slider color XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); // draw the slider XFillRectangle(display, window, gc, 20, 175, sliderLength, 5); } else { switch (mode) { case 1: drawVolumeIcon(); break; case 2: drawBrightnessIcon(); break; default: break; } // set slider color XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); // draw the slider XFillRectangle(display, window, gc, 20, 175, sliderLength, 5); } // flush the display to show the drawn objects XFlush(display); // register the signal handler signal(SIGUSR1, sighandler); // set the execution time to 1 second executionLength = 1; // start the main loop to display the window 1 second checkExit(NULL); }
dj95/fn-notify
src/draw.h
<reponame>dj95/fn-notify #include <stdlib.h> #include <X11/X.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #include <X11/Xresource.h> #include <X11/extensions/shape.h> #include "config.h" void drawBrightnessIcon(); void drawVolumeIcon(); void drawVolumeIconMuted();
dj95/fn-notify
src/draw.c
#include "draw.h" extern Display *display; extern Window window; extern GC gc; void drawBrightnessIcon() { // get window attributes for width and height XWindowAttributes win_attr; XGetWindowAttributes(display, window, &win_attr); // extract window width and height int width = win_attr.width; int height = win_attr.height; XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillRectangle(display, window, gc, 0, 0, width, height); XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); for (int i=0; i < 12; i++) { XFillArc( display, window, gc, 60, 60, 80, 80, 30 * i * 64, 5 * 64); } XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillArc( display, window, gc, 75, 75, 50, 50, 0 * 64, 360 * 64); XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); XFillArc( display, window, gc, 85, 85, 30, 30, 0 * 64, 360 * 64); } void drawVolumeIcon() { // get window attributes for width and height XWindowAttributes win_attr; XGetWindowAttributes(display, window, &win_attr); // extract window width and height int width = win_attr.width; int height = win_attr.height; XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillRectangle(display, window, gc, 0, 0, width, height); XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); XFillArc( display, window, gc, 50, 50, 100, 100, -45 * 64, 90 * 64); XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillArc( display, window, gc, 55, 55, 90, 90, -45 * 64, 90 * 64); XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); XFillArc( display, window, gc, 60, 60, 80, 80, -45 * 64, 90 * 64); XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillArc( display, window, gc, 65, 65, 70, 70, -45 * 64, 90 * 64); XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); XFillArc( display, window, gc, 70, 70, 60, 60, -45 * 64, 90 * 64); XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillArc( display, window, gc, 75, 75, 50, 50, -45 * 64, 90 * 64); XSetForeground(display, gc, strtoul(FG_COLOR, 0, 16)); XFillRectangle(display, window, gc, 55, 75, 50, 50); XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillArc( display, window, gc, 50, 60, 60, 60, 45 * 64, 135 * 64); XFillArc( display, window, gc, 50, 80, 60, 60, 180 * 64, 135 * 64); } void drawVolumeIconMuted() { // get window attributes for width and height XWindowAttributes win_attr; XGetWindowAttributes(display, window, &win_attr); // extract window width and height int width = win_attr.width; int height = win_attr.height; XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillRectangle(display, window, gc, 0, 0, width, height); XSetForeground(display, gc, strtoul(FG_MUTED, 0, 16)); XFillRectangle(display, window, gc, 55, 75, 50, 50); XSetForeground(display, gc, strtoul(BG_COLOR, 0, 16)); XFillArc( display, window, gc, 50, 60, 60, 60, 45 * 64, 135 * 64); XFillArc( display, window, gc, 50, 80, 60, 60, 180 * 64, 135 * 64); }
YChungHsu/hid_rw_register
src/hid_rw_registers.c
<filename>src/hid_rw_registers.c #include <stdint.h> #include <stdio.h> #include <linux/hidraw.h> #include <fcntl.h> #include <sys/types.h> #include <string.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <unistd.h> void set_feature(int fd, uint8_t report_id, uint8_t *data, int length) { int ret; uint8_t buffer[length + 1]; memcpy(buffer + 1, data, length); buffer[0] = report_id; ret = ioctl(fd, HIDIOCSFEATURE(length + 1), buffer); printf("set_feature: %d\n", ret); } void write_register(int fd, uint8_t bank, uint8_t address, uint8_t value) { uint8_t buffer[] = {address, bank, value}; set_feature(fd, 0x42, buffer, 3); } uint8_t get_feature(int fd, uint8_t report_id, uint8_t *data, int* length, int max_length) { uint8_t buffer[max_length]; memset(buffer, 0xcc, max_length); buffer[0] = report_id; int res = ioctl(fd, HIDIOCGFEATURE(max_length), buffer); if(res < 0) { printf("get_feature: error\n"); return res; } else { *length = res; memcpy(data, buffer, res); return res; } } uint8_t read_register(int fd, uint8_t bank, uint8_t address) { uint8_t buffer[4]; int len = 0; write_register(fd, bank | 0x10, address, 0); get_feature(fd, 0x42, buffer, &len, 4); return buffer[3]; } int main(int argc, char **argv) { char * path = argv[1]; printf("PATH: %s\n", path); printf("argc: %d\n", argc); int fd = open(path, O_RDWR|O_NONBLOCK); if(fd < 0) { printf("error main\n"); } write_register(fd, 6, 0x74, 0x64); uint8_t read_value = read_register(fd, 6, 0x74); printf("main: return value: 0x%02x", read_value); return 0; }
thetrapest/TheSuperTinyCompilerInJava
src/main/resources/HelloWorld.c
#include <stdio.h> int sum(int, int); int sum(int a, int b){ return a+b; } int main(int argc, char** argv){ int x = 10, y = 20; int z = sum(x,y); printf("sum is: %d\n", z); return 0; }
dotsimon/openssl
crypto/evp/keymgmt_lib.c
<gh_stars>1-10 /* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/nelem.h" #include "crypto/evp.h" #include "crypto/asn1.h" #include "internal/core.h" #include "internal/provider.h" #include "evp_local.h" struct import_data_st { EVP_KEYMGMT *keymgmt; void *keydata; int selection; }; static int try_import(const OSSL_PARAM params[], void *arg) { struct import_data_st *data = arg; return evp_keymgmt_import(data->keymgmt, data->keydata, data->selection, params); } void *evp_keymgmt_util_export_to_provider(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt) { void *keydata = NULL; size_t i, j; /* * If there is an underlying legacy key and it has changed, invalidate * the cache of provider keys. */ if (pk->pkey.ptr != NULL) { /* * If there is no dirty counter, this key can't be used with * providers. */ if (pk->ameth->dirty_cnt == NULL) return NULL; if (pk->ameth->dirty_cnt(pk) != pk->dirty_cnt_copy) evp_keymgmt_util_clear_pkey_cache(pk); } /* * See if we have exported to this provider already. * If we have, return immediately. */ for (i = 0; i < OSSL_NELEM(pk->pkeys) && pk->pkeys[i].keymgmt != NULL; i++) { if (keymgmt == pk->pkeys[i].keymgmt) return pk->pkeys[i].keydata; } if ((keydata = evp_keymgmt_newdata(keymgmt)) == NULL) return NULL; if (pk->pkey.ptr != NULL) { /* There is a legacy key, try to export that one to the provider */ /* * If the legacy key doesn't have an export function or the export * function fails, give up */ if (pk->ameth->export_to == NULL || !pk->ameth->export_to(pk, keydata, keymgmt)) { evp_keymgmt_freedata(keymgmt, keydata); return NULL; } /* Synchronize the dirty count */ pk->dirty_cnt_copy = pk->ameth->dirty_cnt(pk); } else { /* * Here, there is no legacy key, so we look at the already cached * provider keys, and import from the first that supports it * (i.e. use its export function), and export the imported data to * the new provider. */ /* Setup for the export callback */ struct import_data_st import_data; import_data.keydata = keydata; import_data.keymgmt = keymgmt; import_data.selection = OSSL_KEYMGMT_SELECT_ALL; for (j = 0; j < i && pk->pkeys[j].keymgmt != NULL; j++) { EVP_KEYMGMT *exp_keymgmt = pk->pkeys[i].keymgmt; void *exp_keydata = pk->pkeys[i].keydata; /* * TODO(3.0) consider an evp_keymgmt_export() return value that * indicates that the method is unsupported. */ if (exp_keymgmt->export == NULL) continue; /* * The export function calls the callback (try_import), which * does the import for us. If successful, we're done. */ if (evp_keymgmt_export(exp_keymgmt, exp_keydata, OSSL_KEYMGMT_SELECT_ALL, &try_import, &import_data)) break; /* If there was an error, bail out */ evp_keymgmt_freedata(keymgmt, keydata); return NULL; } } /* * TODO(3.0) Right now, we assume we have ample space. We will * have to think about a cache aging scheme, though, if |i| indexes * outside the array. */ if (!ossl_assert(i < OSSL_NELEM(pk->pkeys))) return NULL; evp_keymgmt_util_cache_pkey(pk, i, keymgmt, keydata); return keydata; } void evp_keymgmt_util_clear_pkey_cache(EVP_PKEY *pk) { size_t i; if (pk != NULL) { for (i = 0; i < OSSL_NELEM(pk->pkeys) && pk->pkeys[i].keymgmt != NULL; i++) { EVP_KEYMGMT *keymgmt = pk->pkeys[i].keymgmt; void *keydata = pk->pkeys[i].keydata; pk->pkeys[i].keymgmt = NULL; pk->pkeys[i].keydata = NULL; evp_keymgmt_freedata(keymgmt, keydata); EVP_KEYMGMT_free(keymgmt); } pk->cache.size = 0; pk->cache.bits = 0; pk->cache.security_bits = 0; } } void evp_keymgmt_util_cache_pkey(EVP_PKEY *pk, size_t index, EVP_KEYMGMT *keymgmt, void *keydata) { if (keydata != NULL) { EVP_KEYMGMT_up_ref(keymgmt); pk->pkeys[index].keydata = keydata; pk->pkeys[index].keymgmt = keymgmt; /* * Cache information about the key object. Only needed for the * "original" provider side key. * * This services functions like EVP_PKEY_size, EVP_PKEY_bits, etc */ if (index == 0) { int bits = 0; int security_bits = 0; int size = 0; OSSL_PARAM params[4]; params[0] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_BITS, &bits); params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_SECURITY_BITS, &security_bits); params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_MAX_SIZE, &size); params[3] = OSSL_PARAM_construct_end(); if (evp_keymgmt_get_params(keymgmt, keydata, params)) { pk->cache.size = size; pk->cache.bits = bits; pk->cache.security_bits = security_bits; } } } } void *evp_keymgmt_util_fromdata(EVP_PKEY *target, EVP_KEYMGMT *keymgmt, int selection, const OSSL_PARAM params[]) { void *keydata = evp_keymgmt_newdata(keymgmt); if (keydata != NULL) { if (!evp_keymgmt_import(keymgmt, keydata, selection, params)) { evp_keymgmt_freedata(keymgmt, keydata); return NULL; } evp_keymgmt_util_clear_pkey_cache(target); evp_keymgmt_util_cache_pkey(target, 0, keymgmt, keydata); } return keydata; }
dotsimon/openssl
providers/implementations/serializers/serializer_rsa.c
<filename>providers/implementations/serializers/serializer_rsa.c<gh_stars>1-10 /* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "crypto/rsa.h" /* rsa_get0_all_params() */ #include "prov/bio.h" /* ossl_prov_bio_printf() */ #include "prov/implementations.h" /* rsa_keymgmt_functions */ #include "serializer_local.h" DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM) OSSL_OP_keymgmt_new_fn *ossl_prov_get_keymgmt_rsa_new(void) { return ossl_prov_get_keymgmt_new(rsa_keymgmt_functions); } OSSL_OP_keymgmt_free_fn *ossl_prov_get_keymgmt_rsa_free(void) { return ossl_prov_get_keymgmt_free(rsa_keymgmt_functions); } OSSL_OP_keymgmt_import_fn *ossl_prov_get_keymgmt_rsa_import(void) { return ossl_prov_get_keymgmt_import(rsa_keymgmt_functions); } int ossl_prov_print_rsa(BIO *out, RSA *rsa, int priv) { const char *modulus_label; const char *exponent_label; const BIGNUM *rsa_d = NULL, *rsa_n = NULL, *rsa_e = NULL; STACK_OF(BIGNUM_const) *factors = sk_BIGNUM_const_new_null(); STACK_OF(BIGNUM_const) *exps = sk_BIGNUM_const_new_null(); STACK_OF(BIGNUM_const) *coeffs = sk_BIGNUM_const_new_null(); int ret = 0; if (rsa == NULL || factors == NULL || exps == NULL || coeffs == NULL) goto err; RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); rsa_get0_all_params(rsa, factors, exps, coeffs); if (priv && rsa_d != NULL) { if (ossl_prov_bio_printf(out, "Private-Key: (%d bit, %d primes)\n", BN_num_bits(rsa_n), sk_BIGNUM_const_num(factors)) <= 0) goto err; modulus_label = "modulus:"; exponent_label = "publicExponent:"; } else { if (ossl_prov_bio_printf(out, "Public-Key: (%d bit)\n", BN_num_bits(rsa_n)) <= 0) goto err; modulus_label = "Modulus:"; exponent_label = "Exponent:"; } if (!ossl_prov_print_labeled_bignum(out, modulus_label, rsa_n)) goto err; if (!ossl_prov_print_labeled_bignum(out, exponent_label, rsa_e)) goto err; if (priv) { int i; if (!ossl_prov_print_labeled_bignum(out, "privateExponent:", rsa_d)) goto err; if (!ossl_prov_print_labeled_bignum(out, "prime1:", sk_BIGNUM_const_value(factors, 0))) goto err; if (!ossl_prov_print_labeled_bignum(out, "prime2:", sk_BIGNUM_const_value(factors, 1))) goto err; if (!ossl_prov_print_labeled_bignum(out, "exponent1:", sk_BIGNUM_const_value(exps, 0))) goto err; if (!ossl_prov_print_labeled_bignum(out, "exponent2:", sk_BIGNUM_const_value(exps, 1))) goto err; if (!ossl_prov_print_labeled_bignum(out, "coefficient:", sk_BIGNUM_const_value(coeffs, 0))) goto err; for (i = 2; i < sk_BIGNUM_const_num(factors); i++) { if (ossl_prov_bio_printf(out, "prime%d:", i + 1) <= 0) goto err; if (!ossl_prov_print_labeled_bignum(out, NULL, sk_BIGNUM_const_value(factors, i))) goto err; if (ossl_prov_bio_printf(out, "exponent%d:", i + 1) <= 0) goto err; if (!ossl_prov_print_labeled_bignum(out, NULL, sk_BIGNUM_const_value(exps, i))) goto err; if (ossl_prov_bio_printf(out, "coefficient%d:", i + 1) <= 0) goto err; if (!ossl_prov_print_labeled_bignum(out, NULL, sk_BIGNUM_const_value(coeffs, i - 1))) goto err; } } ret = 1; err: sk_BIGNUM_const_free(factors); sk_BIGNUM_const_free(exps); sk_BIGNUM_const_free(coeffs); return ret; }
dotsimon/openssl
include/crypto/dsa.h
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/dsa.h> #define DSA_PARAMGEN_TYPE_FIPS_186_2 1 /* Use legacy FIPS186-2 standard */ #define DSA_PARAMGEN_TYPE_FIPS_186_4 2 /* Use FIPS186-4 standard */ int dsa_generate_parameters_ctx(OPENSSL_CTX *libctx, DSA *dsa, int bits, const unsigned char *seed_in, int seed_len, int *counter_ret, unsigned long *h_ret, BN_GENCB *cb); int dsa_generate_ffc_parameters(OPENSSL_CTX *libctx, DSA *dsa, int type, int pbits, int qbits, int gindex, BN_GENCB *cb); int dsa_sign_int(OPENSSL_CTX *libctx, int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa); int dsa_generate_key_ctx(OPENSSL_CTX *libctx, DSA *dsa); const unsigned char *dsa_algorithmidentifier_encoding(int md_nid, size_t *len);
dotsimon/openssl
crypto/dsa/dsa_aid.c
<filename>crypto/dsa/dsa_aid.c /* * Copyright 2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <openssl/objects.h> #include "crypto/dsa.h" #define ASN1_SEQUENCE 0x30 #define ASN1_OID 0x06 /* dsaWithSHA OIDs are of the form: (1 3 14 3 2 |n|) */ #define ENCODE_ALGORITHMIDENTIFIER_SHA(name, n) \ static const unsigned char algorithmidentifier_##name##_der[] = { \ ASN1_SEQUENCE, 0x07, \ ASN1_OID, 0x05, 1 * 40 + 3, 14, 3, 2, n \ } ENCODE_ALGORITHMIDENTIFIER_SHA(sha, 13); ENCODE_ALGORITHMIDENTIFIER_SHA(sha1, 27); /* dsaWithSHA OIDs are of the form: (2 16 840 1 101 3 4 3 |n|) */ #define ENCODE_ALGORITHMIDENTIFIER_SHAx(name, n) \ static const unsigned char algorithmidentifier_##name##_der[] = { \ ASN1_SEQUENCE, 0x0b, \ ASN1_OID, 0x09, 2 * 40 + 16, 0x86, 0x48, 1, 101, 3, 4, 3, n \ } ENCODE_ALGORITHMIDENTIFIER_SHAx(sha224, 1); ENCODE_ALGORITHMIDENTIFIER_SHAx(sha256, 2); ENCODE_ALGORITHMIDENTIFIER_SHAx(sha384, 3); ENCODE_ALGORITHMIDENTIFIER_SHAx(sha512, 4); ENCODE_ALGORITHMIDENTIFIER_SHAx(sha3_224, 5); ENCODE_ALGORITHMIDENTIFIER_SHAx(sha3_256, 6); ENCODE_ALGORITHMIDENTIFIER_SHAx(sha3_384, 7); ENCODE_ALGORITHMIDENTIFIER_SHAx(sha3_512, 8); #define MD_CASE(name) \ case NID_##name: \ *len = sizeof(algorithmidentifier_##name##_der); \ return algorithmidentifier_##name##_der const unsigned char *dsa_algorithmidentifier_encoding(int md_nid, size_t *len) { switch (md_nid) { MD_CASE(sha); MD_CASE(sha1); MD_CASE(sha224); MD_CASE(sha256); MD_CASE(sha384); MD_CASE(sha512); MD_CASE(sha3_224); MD_CASE(sha3_256); MD_CASE(sha3_384); MD_CASE(sha3_512); default: return NULL; } }
dotsimon/openssl
crypto/http/http_client.c
/* * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2018-2020 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "e_os.h" #include <stdio.h> #include <stdlib.h> #include "crypto/ctype.h" #include <string.h> #include <openssl/asn1.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/httperr.h> #include <openssl/cmperr.h> #include <openssl/buffer.h> #include <openssl/http.h> #include "internal/sockets.h" #include "internal/cryptlib.h" #include "http_local.h" #define HTTP_PREFIX "HTTP/" #define HTTP_VERSION_PATT "1." /* allow 1.x */ #define HTTP_VERSION_STR_LEN 3 #define HTTP_LINE1_MINLEN ((int)strlen(HTTP_PREFIX HTTP_VERSION_PATT "x 200\n")) #define HTTP_VERSION_MAX_REDIRECTIONS 50 #define HTTP_STATUS_CODE_OK 200 #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301 #define HTTP_STATUS_CODE_FOUND 302 /* Stateful HTTP request code, supporting blocking and non-blocking I/O */ /* Opaque HTTP request status structure */ struct ossl_http_req_ctx_st { int state; /* Current I/O state */ unsigned char *iobuf; /* Line buffer */ int iobuflen; /* Line buffer length */ BIO *wbio; /* BIO to send request to */ BIO *rbio; /* BIO to read response from */ BIO *mem; /* Memory BIO response is built into */ int method_GET; /* HTTP method "GET" or "POST" */ const char *expected_ct; /* expected Content-Type, or NULL */ int expect_asn1; /* response must be ASN.1-encoded */ unsigned long resp_len; /* length of response */ unsigned long max_resp_len; /* Maximum length of response */ time_t max_time; /* Maximum end time of the transfer, or 0 */ char *redirection_url; /* Location given with HTTP status 301/302 */ }; #define HTTP_DEFAULT_MAX_LINE_LENGTH (4 * 1024) #define HTTP_DEFAULT_MAX_RESP_LEN (100 * 1024) /* HTTP states */ #define OHS_NOREAD 0x1000 /* If set no reading should be performed */ #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */ #define OHS_FIRSTLINE 1 /* First line being read */ #define OHS_REDIRECT 0xa /* Looking for redirection location */ #define OHS_HEADERS 2 /* MIME headers being read */ #define OHS_ASN1_HEADER 3 /* HTTP initial header (tag+length) being read */ #define OHS_CONTENT 4 /* HTTP content octets being read */ #define OHS_WRITE_INIT (5 | OHS_NOREAD) /* 1st call: ready to start I/O */ #define OHS_WRITE (6 | OHS_NOREAD) /* Request being sent */ #define OHS_FLUSH (7 | OHS_NOREAD) /* Request being flushed */ #define OHS_DONE (8 | OHS_NOREAD) /* Completed */ #define OHS_HTTP_HEADER (9 | OHS_NOREAD) /* Headers set, w/o final \r\n */ OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int method_GET, int maxline, unsigned long max_resp_len, int timeout, const char *expected_content_type, int expect_asn1) { OSSL_HTTP_REQ_CTX *rctx; if (wbio == NULL || rbio == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL) return NULL; rctx->state = OHS_ERROR; rctx->iobuflen = maxline > 0 ? maxline : HTTP_DEFAULT_MAX_LINE_LENGTH; rctx->iobuf = OPENSSL_malloc(rctx->iobuflen); rctx->wbio = wbio; rctx->rbio = rbio; rctx->mem = BIO_new(BIO_s_mem()); if (rctx->iobuf == NULL || rctx->mem == NULL) { OSSL_HTTP_REQ_CTX_free(rctx); return NULL; } rctx->method_GET = method_GET; rctx->expected_ct = expected_content_type; rctx->expect_asn1 = expect_asn1; rctx->resp_len = 0; OSSL_HTTP_REQ_CTX_set_max_response_length(rctx, max_resp_len); rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0; return rctx; } void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) return; BIO_free(rctx->mem); /* this may indirectly call ERR_clear_error() */ OPENSSL_free(rctx->iobuf); OPENSSL_free(rctx); } BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(OSSL_HTTP_REQ_CTX *rctx) { if (rctx == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } return rctx->mem; } void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx, unsigned long len) { if (rctx == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return; } rctx->max_resp_len = len != 0 ? len : HTTP_DEFAULT_MAX_RESP_LEN; } /* * Create HTTP header using given op and path (or "/" in case path is NULL). * Server name (and port) must be given if and only if plain HTTP proxy is used. */ int OSSL_HTTP_REQ_CTX_header(OSSL_HTTP_REQ_CTX *rctx, const char *server, const char *port, const char *path) { if (rctx == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (BIO_printf(rctx->mem, "%s ", rctx->method_GET ? "GET" : "POST") <= 0) return 0; if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */ /* * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only * allowed when using a proxy */ if (BIO_printf(rctx->mem, "http://%s", server) <= 0) return 0; if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0) return 0; } /* Make sure path includes a forward slash */ if (path == NULL) path = "/"; if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0) return 0; if (BIO_printf(rctx->mem, "%s "HTTP_PREFIX"1.0\r\n", path) <= 0) return 0; rctx->state = OHS_HTTP_HEADER; return 1; } int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx, const char *name, const char *value) { if (rctx == NULL || name == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (BIO_puts(rctx->mem, name) <= 0) return 0; if (value != NULL) { if (BIO_write(rctx->mem, ": ", 2) != 2) return 0; if (BIO_puts(rctx->mem, value) <= 0) return 0; } if (BIO_write(rctx->mem, "\r\n", 2) != 2) return 0; rctx->state = OHS_HTTP_HEADER; return 1; } static int OSSL_HTTP_REQ_CTX_content(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, BIO *req_mem) { const unsigned char *req; long req_len; if (rctx == NULL || req_mem == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (content_type != NULL && BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0) return 0; if ((req_len = BIO_get_mem_data(req_mem, &req)) <= 0) return 0; rctx->state = OHS_WRITE_INIT; return BIO_printf(rctx->mem, "Content-Length: %ld\r\n\r\n", req_len) > 0 && BIO_write(rctx->mem, req, req_len) == (int)req_len; } BIO *HTTP_asn1_item2bio(const ASN1_ITEM *it, ASN1_VALUE *val) { BIO *res; if (it == NULL || val == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((res = BIO_new(BIO_s_mem())) == NULL) return NULL; if (ASN1_item_i2d_bio(it, res, val) <= 0) { BIO_free(res); res = NULL; } return res; } int OSSL_HTTP_REQ_CTX_i2d(OSSL_HTTP_REQ_CTX *rctx, const char *content_type, const ASN1_ITEM *it, ASN1_VALUE *req) { BIO *mem; int res; if (rctx == NULL || it == NULL || req == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return 0; } res = (mem = HTTP_asn1_item2bio(it, req)) != NULL && OSSL_HTTP_REQ_CTX_content(rctx, content_type, mem); BIO_free(mem); return res; } static int OSSL_HTTP_REQ_CTX_add1_headers(OSSL_HTTP_REQ_CTX *rctx, const STACK_OF(CONF_VALUE) *headers, const char *host) { int i; int add_host = 1; CONF_VALUE *hdr; for (i = 0; i < sk_CONF_VALUE_num(headers); i++) { hdr = sk_CONF_VALUE_value(headers, i); if (add_host && strcasecmp("host", hdr->name) == 0) add_host = 0; if (!OSSL_HTTP_REQ_CTX_add1_header(rctx, hdr->name, hdr->value)) return 0; } if (add_host && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Host", host)) return 0; return 1; } /*- * Create OSSL_HTTP_REQ_CTX structure using the values provided. * If !use_http_proxy then the 'server' and 'port' parameters are ignored. * If req_mem == NULL then use GET and ignore content_type, else POST. */ OSSL_HTTP_REQ_CTX *HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int use_http_proxy, const char *server, const char *port, const char *path, const STACK_OF(CONF_VALUE) *headers, const char *content_type, BIO *req_mem, int maxline, unsigned long max_resp_len, int timeout, const char *expected_content_type, int expect_asn1) { OSSL_HTTP_REQ_CTX *rctx; if (use_http_proxy && (server == NULL || port == NULL)) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } /* remaining parameters are checked indirectly by the functions called */ if ((rctx = OSSL_HTTP_REQ_CTX_new(wbio, rbio, req_mem == NULL, maxline, max_resp_len, timeout, expected_content_type, expect_asn1)) == NULL) return NULL; if (OSSL_HTTP_REQ_CTX_header(rctx, use_http_proxy ? server : NULL, port, path) && OSSL_HTTP_REQ_CTX_add1_headers(rctx, headers, server) && (req_mem == NULL || OSSL_HTTP_REQ_CTX_content(rctx, content_type, req_mem))) return rctx; OSSL_HTTP_REQ_CTX_free(rctx); return NULL; } /* * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK". * We need to obtain the numeric code and (optional) informational message. */ static int parse_http_line1(char *line) { int retcode; char *code, *reason, *end; /* Skip to first whitespace (past protocol info) */ for (code = line; *code != '\0' && !ossl_isspace(*code); code++) continue; if (*code == '\0') { HTTPerr(0, HTTP_R_SERVER_RESPONSE_PARSE_ERROR); return 0; } /* Skip past whitespace to start of response code */ while (*code != '\0' && ossl_isspace(*code)) code++; if (*code == '\0') { HTTPerr(0, HTTP_R_SERVER_RESPONSE_PARSE_ERROR); return 0; } /* Find end of response code: first whitespace after start of code */ for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++) continue; if (*reason == '\0') { HTTPerr(0, HTTP_R_SERVER_RESPONSE_PARSE_ERROR); return 0; } /* Set end of response code and start of message */ *reason++ = '\0'; /* Attempt to parse numeric code */ retcode = strtoul(code, &end, 10); if (*end != '\0') return 0; /* Skip over any leading whitespace in message */ while (*reason != '\0' && ossl_isspace(*reason)) reason++; if (*reason != '\0') { /* * Finally zap any trailing whitespace in message (include CRLF) */ /* chop any trailing whitespace from reason */ /* We know reason has a non-whitespace character so this is OK */ for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--) *end = '\0'; } switch (retcode) { case HTTP_STATUS_CODE_OK: case HTTP_STATUS_CODE_MOVED_PERMANENTLY: case HTTP_STATUS_CODE_FOUND: return retcode; default: if (retcode < 400) HTTPerr(0, HTTP_R_STATUS_CODE_UNSUPPORTED); else HTTPerr(0, HTTP_R_SERVER_SENT_ERROR); if (*reason == '\0') ERR_add_error_data(2, "Code=", code); else ERR_add_error_data(4, "Code=", code, ",Reason=", reason); return 0; } } static int check_set_resp_len(OSSL_HTTP_REQ_CTX *rctx, unsigned long len) { const char *tag = NULL; unsigned long val = 0; if (len > rctx->max_resp_len) { HTTPerr(0, HTTP_R_MAX_RESP_LEN_EXCEEDED); tag = ",max="; val = rctx->max_resp_len; } if (rctx->resp_len != 0 && rctx->resp_len != len) { HTTPerr(0, HTTP_R_INCONSISTENT_CONTENT_LENGTH); tag = ",before="; val = rctx->resp_len; } if (tag != NULL) { char len_str[32]; char str[32]; BIO_snprintf(len_str, sizeof(len_str), "%lu", len); BIO_snprintf(str, sizeof(str), "%lu", val); ERR_add_error_data(4, "length=", len_str, tag, str); return 0; } rctx->resp_len = len; return 1; } /* * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx. * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry. */ int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx) { int i; long n, n_to_send = 0; unsigned long resp_len; const unsigned char *p; char *key, *value, *line_end = NULL; if (rctx == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return 0; } rctx->redirection_url = NULL; next_io: if ((rctx->state & OHS_NOREAD) == 0) { n = BIO_read(rctx->rbio, rctx->iobuf, rctx->iobuflen); if (n <= 0) { if (BIO_should_retry(rctx->rbio)) return -1; return 0; } /* Write data to memory BIO */ if (BIO_write(rctx->mem, rctx->iobuf, n) != n) return 0; } switch (rctx->state) { case OHS_HTTP_HEADER: /* Last operation was adding headers: need a final \r\n */ if (BIO_write(rctx->mem, "\r\n", 2) != 2) { rctx->state = OHS_ERROR; return 0; } rctx->state = OHS_WRITE_INIT; /* fall thru */ case OHS_WRITE_INIT: n_to_send = BIO_get_mem_data(rctx->mem, NULL); rctx->state = OHS_WRITE; /* fall thru */ case OHS_WRITE: n = BIO_get_mem_data(rctx->mem, &p); i = BIO_write(rctx->wbio, p + (n - n_to_send), n_to_send); if (i <= 0) { if (BIO_should_retry(rctx->wbio)) return -1; rctx->state = OHS_ERROR; return 0; } n_to_send -= i; if (n_to_send > 0) goto next_io; rctx->state = OHS_FLUSH; (void)BIO_reset(rctx->mem); /* fall thru */ case OHS_FLUSH: i = BIO_flush(rctx->wbio); if (i > 0) { rctx->state = OHS_FIRSTLINE; goto next_io; } if (BIO_should_retry(rctx->wbio)) return -1; rctx->state = OHS_ERROR; return 0; case OHS_ERROR: return 0; case OHS_FIRSTLINE: case OHS_HEADERS: case OHS_REDIRECT: /* Attempt to read a line in */ next_line: /* * Due to strange memory BIO behavior with BIO_gets we have to check * there's a complete line in there before calling BIO_gets or we'll * just get a partial read. */ n = BIO_get_mem_data(rctx->mem, &p); if (n <= 0 || memchr(p, '\n', n) == 0) { if (n >= rctx->iobuflen) { rctx->state = OHS_ERROR; return 0; } goto next_io; } n = BIO_gets(rctx->mem, (char *)rctx->iobuf, rctx->iobuflen); if (n <= 0) { if (BIO_should_retry(rctx->mem)) goto next_io; rctx->state = OHS_ERROR; return 0; } /* Don't allow excessive lines */ if (n == rctx->iobuflen) { HTTPerr(0, HTTP_R_RESPONSE_LINE_TOO_LONG); rctx->state = OHS_ERROR; return 0; } /* First line */ if (rctx->state == OHS_FIRSTLINE) { switch (parse_http_line1((char *)rctx->iobuf)) { case HTTP_STATUS_CODE_OK: rctx->state = OHS_HEADERS; goto next_line; case HTTP_STATUS_CODE_MOVED_PERMANENTLY: case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */ if (rctx->method_GET) { rctx->state = OHS_REDIRECT; goto next_line; } HTTPerr(0, HTTP_R_REDIRECTION_NOT_ENABLED); /* redirection is not supported/recommended for POST */ /* fall through */ default: rctx->state = OHS_ERROR; return 0; } } key = (char *)rctx->iobuf; value = strchr(key, ':'); if (value != NULL) { *(value++) = '\0'; while (ossl_isspace(*value)) value++; line_end = strchr(value, '\r'); if (line_end == NULL) line_end = strchr(value, '\n'); if (line_end != NULL) *line_end = '\0'; } if (value != NULL && line_end != NULL) { if (rctx->state == OHS_REDIRECT && strcmp(key, "Location") == 0) { rctx->redirection_url = value; return 0; } if (rctx->expected_ct != NULL && strcmp(key, "Content-Type") == 0) { if (strcmp(rctx->expected_ct, value) != 0) { HTTPerr(0, HTTP_R_UNEXPECTED_CONTENT_TYPE); ERR_add_error_data(4, "expected=", rctx->expected_ct, ",actual=", value); return 0; } rctx->expected_ct = NULL; /* content-type has been found */ } if (strcmp(key, "Content-Length") == 0) { resp_len = strtoul(value, &line_end, 10); if (line_end == value || *line_end != '\0') { HTTPerr(0, HTTP_R_ERROR_PARSING_CONTENT_LENGTH); ERR_add_error_data(2, "input=", value); return 0; } if (!check_set_resp_len(rctx, resp_len)) return 0; } } /* Look for blank line: end of headers */ for (p = rctx->iobuf; *p != '\0' ; p++) { if (*p != '\r' && *p != '\n') break; } if (*p != '\0') /* not end of headers */ goto next_line; if (rctx->expected_ct != NULL) { HTTPerr(0, HTTP_R_MISSING_CONTENT_TYPE); ERR_add_error_data(2, "expected=", rctx->expected_ct); return 0; } if (rctx->state == OHS_REDIRECT) { /* http status code indicated redirect but there was no Location */ HTTPerr(0, HTTP_R_MISSING_REDIRECT_LOCATION); return 0; } if (!rctx->expect_asn1) { rctx->state = OHS_CONTENT; goto content; } rctx->state = OHS_ASN1_HEADER; /* Fall thru */ case OHS_ASN1_HEADER: /* * Now reading ASN1 header: can read at least 2 bytes which is enough * for ASN1 SEQUENCE header and either length field or at least the * length of the length field. */ n = BIO_get_mem_data(rctx->mem, &p); if (n < 2) goto next_io; /* Check it is an ASN1 SEQUENCE */ if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { HTTPerr(0, HTTP_R_MISSING_ASN1_ENCODING); return 0; } /* Check out length field */ if ((*p & 0x80) != 0) { /* * If MSB set on initial length octet we can now always read 6 * octets: make sure we have them. */ if (n < 6) goto next_io; n = *p & 0x7F; /* Not NDEF or excessive length */ if (n == 0 || (n > 4)) { HTTPerr(0, HTTP_R_ERROR_PARSING_ASN1_LENGTH); return 0; } p++; resp_len = 0; for (i = 0; i < n; i++) { resp_len <<= 8; resp_len |= *p++; } resp_len += n + 2; } else { resp_len = *p + 2; } if (!check_set_resp_len(rctx, resp_len)) return 0; content: rctx->state = OHS_CONTENT; /* Fall thru */ case OHS_CONTENT: default: n = BIO_get_mem_data(rctx->mem, NULL); if (n < (long)rctx->resp_len /* may be 0 if no Content-Type or ASN.1 */) goto next_io; rctx->state = OHS_DONE; return 1; } } #ifndef OPENSSL_NO_SOCK /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */ static BIO *HTTP_new_bio(const char *server, const char *server_port, const char *proxy, const char *proxy_port) { const char *host = server; const char *port = server_port; BIO *cbio; if (server == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (proxy != NULL) { host = proxy; port = proxy_port; } cbio = BIO_new_connect(host); if (cbio == NULL) goto end; if (port != NULL) (void)BIO_set_conn_port(cbio, port); end: return cbio; } static ASN1_VALUE *BIO_mem_d2i(BIO *mem, const ASN1_ITEM *it) { const unsigned char *p; long len = BIO_get_mem_data(mem, &p); ASN1_VALUE *resp = ASN1_item_d2i(NULL, &p, len, it); if (resp == NULL) HTTPerr(0, HTTP_R_SERVER_RESPONSE_PARSE_ERROR); return resp; } static BIO *OSSL_HTTP_REQ_CTX_transfer(OSSL_HTTP_REQ_CTX *rctx) { int sending = 1; int rv; if (rctx == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } for (;;) { rv = OSSL_HTTP_REQ_CTX_nbio(rctx); if (rv != -1) break; /* BIO_should_retry was true */ sending = 0; /* will not actually wait if rctx->max_time == 0 */ if (BIO_wait(rctx->rbio, rctx->max_time) <= 0) return NULL; } if (rv == 0) { if (rctx->redirection_url == NULL) { /* an error occurred */ if (sending && (rctx->state & OHS_NOREAD) != 0) HTTPerr(0, HTTP_R_ERROR_SENDING); else HTTPerr(0, HTTP_R_ERROR_RECEIVING); } return NULL; } if (!BIO_up_ref(rctx->mem)) return NULL; return rctx->mem; } /* Exchange ASN.1-encoded request and response via HTTP on (non-)blocking BIO */ ASN1_VALUE *OSSL_HTTP_REQ_CTX_sendreq_d2i(OSSL_HTTP_REQ_CTX *rctx, const ASN1_ITEM *it) { if (rctx == NULL || it == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } return BIO_mem_d2i(OSSL_HTTP_REQ_CTX_transfer(rctx), it); } static int update_timeout(int timeout, time_t start_time) { long elapsed_time; if (timeout == 0) return 0; elapsed_time = (long)(time(NULL) - start_time); /* this might overflow */ return timeout <= elapsed_time ? -1 : timeout - elapsed_time; } /*- * Exchange HTTP request and response with the given server. * If req_mem == NULL then use GET and ignore content_type, else POST. * The redirection_url output (freed by caller) parameter is used only for GET. * * Typically the bio and rbio parameters are NULL and a network BIO is created * internally for connecting to the given server and port, optionally via a * proxy and its port, and is then used for exchanging the request and response. * If bio is given and rbio is NULL then this BIO is used instead. * If both bio and rbio are given (which may be memory BIOs for instance) * then no explicit connection is attempted, * bio is used for writing the request, and rbio for reading the response. * * bio_update_fn is an optional BIO connect/disconnect callback function, * which has the prototype * BIO *(*OSSL_HTTP_bio_cb_t) (BIO *bio, void *arg, int conn, int detail); * The callback may modify the HTTP BIO provided in the bio argument, * whereby it may make use of any custom defined argument 'arg'. * During connection establishment, just after BIO_connect_retry(), * the callback function is invoked with the 'conn' argument being 1 * 'detail' indicating whether a HTTPS (i.e., TLS) connection is requested. * On disconnect 'conn' is 0 and 'detail' indicates that no error occurred. * For instance, on connect the funct may prepend a TLS BIO to implement HTTPS; * after disconnect it may do some error diagnostics and/or specific cleanup. * The function should return NULL to indicate failure. * After disconnect the modified BIO will be deallocated using BIO_free_all(). */ BIO *OSSL_HTTP_transfer(const char *server, const char *port, const char *path, int use_ssl, const char *proxy, const char *proxy_port, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, const STACK_OF(CONF_VALUE) *headers, const char *content_type, BIO *req_mem, int maxline, unsigned long max_resp_len, int timeout, const char *expected_ct, int expect_asn1, char **redirection_url) { time_t start_time = timeout > 0 ? time(NULL) : 0; BIO *cbio; /* = bio if present, used as connection BIO if rbio is NULL */ OSSL_HTTP_REQ_CTX *rctx; BIO *resp = NULL; if (redirection_url != NULL) *redirection_url = NULL; /* do this beforehand to prevent dbl free */ if (use_ssl && bio_update_fn == NULL) { HTTPerr(0, HTTP_R_TLS_NOT_ENABLED); return NULL; } if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) { HTTPerr(0, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } /* remaining parameters are checked indirectly by the functions called */ if (bio != NULL) cbio = bio; else if ((cbio = HTTP_new_bio(server, port, proxy, proxy_port)) == NULL) return NULL; (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */ if (rbio == NULL && BIO_connect_retry(cbio, timeout) <= 0) goto end; /* now timeout is guaranteed to be >= 0 */ /* callback can be used to wrap or prepend TLS session */ if (bio_update_fn != NULL) { BIO *orig_bio = cbio; cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl); if (cbio == NULL) { cbio = orig_bio; goto end; } } rctx = HTTP_REQ_CTX_new(cbio, rbio != NULL ? rbio : cbio, !use_ssl && proxy != NULL, server, port, path, headers, content_type, req_mem, maxline, max_resp_len, update_timeout(timeout, start_time), expected_ct, expect_asn1); if (rctx == NULL) goto end; resp = OSSL_HTTP_REQ_CTX_transfer(rctx); if (resp == NULL) { if (rctx->redirection_url != NULL) { if (redirection_url == NULL) HTTPerr(0, HTTP_R_REDIRECTION_NOT_ENABLED); else /* may be NULL if out of memory: */ *redirection_url = OPENSSL_strdup(rctx->redirection_url); } else { char buf[200]; unsigned long err = ERR_peek_error(); int lib = ERR_GET_LIB(err); int reason = ERR_GET_REASON(err); if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT) || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR) # ifndef OPENSSL_NO_CMP || (lib == ERR_LIB_CMP && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE) # endif ) { BIO_snprintf(buf, 200, "server=%s:%s", server, port); ERR_add_error_data(1, buf); if (err == 0) { BIO_snprintf(buf, 200, "server has disconnected%s", use_ssl ? " violating the protocol" : ", likely because it requires the use of TLS"); ERR_add_error_data(1, buf); } } } } OSSL_HTTP_REQ_CTX_free(rctx); /* callback can be used to clean up TLS session */ if (bio_update_fn != NULL && (*bio_update_fn)(cbio, arg, 0, resp != NULL) == NULL) { BIO_free(resp); resp = NULL; } end: /* * Use BIO_free_all() because bio_update_fn may prepend or append to cbio. * This also frees any (e.g., SSL/TLS) BIOs linked with bio and, * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer. */ if (bio == NULL) /* cbio was not provided by caller */ BIO_free_all(cbio); if (resp != NULL) /* remove any spurious error queue entries by ssl_add_cert_chain() */ (void)ERR_pop_to_mark(); else (void)ERR_clear_last_mark(); return resp; } static int redirection_ok(int n_redir, const char *old_url, const char *new_url) { static const char https[] = "https:"; int https_len = 6; /* strlen(https) */ if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) { HTTPerr(0, HTTP_R_TOO_MANY_REDIRECTIONS); return 0; } if (*new_url == '/') /* redirection to same server => same protocol */ return 1; if (strncmp(old_url, https, https_len) == 0 && strncmp(new_url, https, https_len) != 0) { HTTPerr(0, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP); return 0; } return 1; } /* Get data via HTTP from server at given URL, potentially with redirection */ BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *proxy_port, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, const STACK_OF(CONF_VALUE) *headers, int maxline, unsigned long max_resp_len, int timeout, const char *expected_content_type, int expect_asn1) { time_t start_time = timeout > 0 ? time(NULL) : 0; char *current_url, *redirection_url; int n_redirs = 0; char *host; char *port; char *path; int use_ssl; BIO *resp = NULL; if (url == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((current_url = OPENSSL_strdup(url)) == NULL) return NULL; for (;;) { if (!OSSL_HTTP_parse_url(current_url, &host, &port, &path, &use_ssl)) break; new_rpath: resp = OSSL_HTTP_transfer(host, port, path, use_ssl, proxy, proxy_port, bio, rbio, bio_update_fn, arg, headers, NULL, NULL, maxline, max_resp_len, update_timeout(timeout, start_time), expected_content_type, expect_asn1, &redirection_url); OPENSSL_free(path); if (resp == NULL && redirection_url != NULL) { if (redirection_ok(++n_redirs, current_url, redirection_url)) { (void)BIO_reset(bio); OPENSSL_free(current_url); current_url = redirection_url; if (*redirection_url == '/') { /* redirection to same server */ path = OPENSSL_strdup(redirection_url); goto new_rpath; } OPENSSL_free(host); OPENSSL_free(port); continue; } OPENSSL_free(redirection_url); } OPENSSL_free(host); OPENSSL_free(port); break; } OPENSSL_free(current_url); return resp; } /* Get ASN.1-encoded data via HTTP from server at given URL */ ASN1_VALUE *OSSL_HTTP_get_asn1(const char *url, const char *proxy, const char *proxy_port, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, const STACK_OF(CONF_VALUE) *headers, int maxline, unsigned long max_resp_len, int timeout, const char *expected_content_type, const ASN1_ITEM *it) { BIO *mem; ASN1_VALUE *resp = NULL; if (url == NULL || it == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if ((mem = OSSL_HTTP_get(url, proxy, proxy_port, bio, rbio, bio_update_fn, arg, headers, maxline, max_resp_len, timeout, expected_content_type, 1 /* expect_asn1 */)) != NULL) resp = BIO_mem_d2i(mem, it); BIO_free(mem); return resp; } /* Post ASN.1-encoded request via HTTP to server return ASN.1 response */ ASN1_VALUE *OSSL_HTTP_post_asn1(const char *server, const char *port, const char *path, int use_ssl, const char *proxy, const char *proxy_port, BIO *bio, BIO *rbio, OSSL_HTTP_bio_cb_t bio_update_fn, void *arg, const STACK_OF(CONF_VALUE) *headers, const char *content_type, ASN1_VALUE *req, const ASN1_ITEM *req_it, int maxline, unsigned long max_resp_len, int timeout, const char *expected_ct, const ASN1_ITEM *rsp_it) { BIO *req_mem; BIO *res_mem; ASN1_VALUE *resp = NULL; if (req == NULL) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); return NULL; } /* remaining parameters are checked indirectly */ req_mem = HTTP_asn1_item2bio(req_it, req); res_mem = OSSL_HTTP_transfer(server, port, path, use_ssl, proxy, proxy_port, bio, rbio, bio_update_fn, arg, headers, content_type, req_mem /* may be NULL */, maxline, max_resp_len, timeout, expected_ct, 1 /* expect_asn1 */, NULL); BIO_free(req_mem); if (res_mem != NULL) resp = BIO_mem_d2i(res_mem, rsp_it); BIO_free(res_mem); return resp; } /* BASE64 encoder used for encoding basic proxy authentication credentials */ static char *base64encode(const void *buf, size_t len) { int i; size_t outl; char *out; /* Calculate size of encoded data */ outl = (len / 3); if (len % 3 > 0) outl++; outl <<= 2; out = OPENSSL_malloc(outl + 1); if (out == NULL) return 0; i = EVP_EncodeBlock((unsigned char *)out, buf, len); if (!ossl_assert(0 <= i && (size_t)i <= outl)) { OPENSSL_free(out); return NULL; } return out; } /* * Promote the given connection BIO using the CONNECT method for a TLS proxy. * This is typically called by an app, so bio_err and prog are used unless NULL * to print additional diagnostic information in a user-oriented way. */ int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port, const char *proxyuser, const char *proxypass, int timeout, BIO *bio_err, const char *prog) { # undef BUF_SIZE # define BUF_SIZE (8 * 1024) char *mbuf = OPENSSL_malloc(BUF_SIZE); char *mbufp; int read_len = 0; int rv; int ret = 0; BIO *fbio = BIO_new(BIO_f_buffer()); time_t max_time = timeout > 0 ? time(NULL) + timeout : 0; if (bio == NULL || server == NULL || port == NULL || (bio_err != NULL && prog == NULL)) { HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER); goto end; } if (mbuf == NULL || fbio == NULL) { BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog); goto end; } BIO_push(fbio, bio); BIO_printf(fbio, "CONNECT %s:%s "HTTP_PREFIX"1.0\r\n", server, port); /* * Workaround for broken proxies which would otherwise close * the connection when entering tunnel mode (e.g., Squid 2.6) */ BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n"); /* Support for basic (base64) proxy authentication */ if (proxyuser != NULL) { size_t len = strlen(proxyuser) + 1; char *proxyauth, *proxyauthenc = NULL; if (proxypass != NULL) len += strlen(proxypass); proxyauth = OPENSSL_malloc(len + 1); if (proxyauth == NULL) goto end; if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser, proxypass != NULL ? proxypass : "") != (int)len) goto proxy_end; proxyauthenc = base64encode(proxyauth, len); if (proxyauthenc != NULL) { BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc); OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc)); } proxy_end: OPENSSL_clear_free(proxyauth, len); if (proxyauthenc == NULL) goto end; } /* Terminate the HTTP CONNECT request */ BIO_printf(fbio, "\r\n"); for (;;) { if (BIO_flush(fbio) != 0) break; /* potentially needs to be retried if BIO is non-blocking */ if (!BIO_should_retry(fbio)) break; } for (;;) { /* will not actually wait if timeout == 0 */ rv = BIO_wait(fbio, max_time); if (rv <= 0) { BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog, rv == 0 ? "timed out" : "failed waiting for data"); goto end; } /*- * The first line is the HTTP response. * According to RFC 7230, it is formatted exactly like this: * HTTP/d.d ddd Reason text\r\n */ read_len = BIO_gets(fbio, mbuf, BUF_SIZE); /* the BIO may not block, so we must wait for the 1st line to come in */ if (read_len < HTTP_LINE1_MINLEN) continue; /* RFC 7231 4.3.6: any 2xx status code is valid */ if (strncmp(mbuf, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) { HTTPerr(0, HTTP_R_SERVER_RESPONSE_PARSE_ERROR); BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n", prog); /* Wrong protocol, not even HTTP, so stop reading headers */ goto end; } mbufp = mbuf + strlen(HTTP_PREFIX); if (strncmp(mbufp, HTTP_VERSION_PATT, strlen(HTTP_VERSION_PATT)) != 0) { HTTPerr(0, HTTP_R_SERVER_SENT_WRONG_HTTP_VERSION); BIO_printf(bio_err, "%s: HTTP CONNECT failed, bad HTTP version %.*s\n", prog, HTTP_VERSION_STR_LEN, mbufp); goto end; } mbufp += HTTP_VERSION_STR_LEN; if (strncmp(mbufp, " 2", strlen(" 2")) != 0) { mbufp += 1; /* chop any trailing whitespace */ while (read_len > 0 && ossl_isspace(mbuf[read_len - 1])) read_len--; mbuf[read_len] = '\0'; HTTPerr(0, HTTP_R_CONNECT_FAILURE); ERR_add_error_data(2, "Reason=", mbufp); BIO_printf(bio_err, "%s: HTTP CONNECT failed, Reason=%s\n", prog, mbufp); goto end; } ret = 1; break; } /* Read past all following headers */ do { /* * TODO: This does not necessarily catch the case when the full * HTTP response came in in more than a single TCP message. */ read_len = BIO_gets(fbio, mbuf, BUF_SIZE); } while (read_len > 2); end: if (fbio != NULL) { (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); } OPENSSL_free(mbuf); return ret; # undef BUF_SIZE } #endif /* !defined(OPENSSL_NO_SOCK) */
dotsimon/openssl
providers/fips/self_test_kats.c
/* * Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/evp.h> #include <openssl/kdf.h> #include "internal/cryptlib.h" #include "internal/nelem.h" #include "self_test.h" #include "self_test_data.inc" static int self_test_digest(const ST_KAT_DIGEST *t, OSSL_ST_EVENT *event, OPENSSL_CTX *libctx) { int ok = 0; unsigned char out[EVP_MAX_MD_SIZE]; unsigned int out_len = 0; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); EVP_MD *md = EVP_MD_fetch(libctx, t->algorithm, NULL); SELF_TEST_EVENT_onbegin(event, OSSL_SELF_TEST_TYPE_KAT_DIGEST, t->desc); if (ctx == NULL || md == NULL || !EVP_DigestInit_ex(ctx, md, NULL) || !EVP_DigestUpdate(ctx, t->pt, t->pt_len) || !EVP_DigestFinal(ctx, out, &out_len)) goto err; /* Optional corruption */ SELF_TEST_EVENT_oncorrupt_byte(event, out); if (out_len != t->expected_len || memcmp(out, t->expected, out_len) != 0) goto err; ok = 1; err: SELF_TEST_EVENT_onend(event, ok); EVP_MD_free(md); EVP_MD_CTX_free(ctx); return ok; } /* * Helper function to setup a EVP_CipherInit * Used to hide the complexity of Authenticated ciphers. */ static int cipher_init(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const ST_KAT_CIPHER *t, int enc) { unsigned char *in_tag = NULL; int pad = 0, tmp; /* Flag required for Key wrapping */ EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); if (t->tag == NULL) { /* Use a normal cipher init */ return EVP_CipherInit_ex(ctx, cipher, NULL, t->key, t->iv, enc) && EVP_CIPHER_CTX_set_padding(ctx, pad); } /* The authenticated cipher init */ if (!enc) in_tag = (unsigned char *)t->tag; return EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc) && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, t->iv_len, NULL) && (in_tag == NULL || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, t->tag_len, in_tag)) && EVP_CipherInit_ex(ctx, NULL, NULL, t->key, t->iv, enc) && EVP_CIPHER_CTX_set_padding(ctx, pad) && EVP_CipherUpdate(ctx, NULL, &tmp, t->aad, t->aad_len); } /* Test a single KAT for encrypt/decrypt */ static int self_test_cipher(const ST_KAT_CIPHER *t, OSSL_ST_EVENT *event, OPENSSL_CTX *libctx) { int ret = 0, encrypt = 1, len, ct_len = 0, pt_len = 0; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; unsigned char ct_buf[256] = { 0 }; unsigned char pt_buf[256] = { 0 }; SELF_TEST_EVENT_onbegin(event, OSSL_SELF_TEST_TYPE_KAT_CIPHER, t->base.desc); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) goto end; cipher = EVP_CIPHER_fetch(libctx, t->base.algorithm, ""); if (cipher == NULL) goto end; /* Encrypt plain text message */ if (!cipher_init(ctx, cipher, t, encrypt) || !EVP_CipherUpdate(ctx, ct_buf, &len, t->base.pt, t->base.pt_len) || !EVP_CipherFinal_ex(ctx, ct_buf + len, &ct_len)) goto end; SELF_TEST_EVENT_oncorrupt_byte(event, ct_buf); ct_len += len; if (ct_len != (int)t->base.expected_len || memcmp(t->base.expected, ct_buf, ct_len) != 0) goto end; if (t->tag != NULL) { unsigned char tag[16] = { 0 }; if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, t->tag_len, tag) || memcmp(tag, t->tag, t->tag_len) != 0) goto end; } if (!(cipher_init(ctx, cipher, t, !encrypt) && EVP_CipherUpdate(ctx, pt_buf, &len, ct_buf, ct_len) && EVP_CipherFinal_ex(ctx, pt_buf + len, &pt_len))) goto end; pt_len += len; if (pt_len != (int)t->base.pt_len || memcmp(pt_buf, t->base.pt, pt_len) != 0) goto end; ret = 1; end: EVP_CIPHER_free(cipher); EVP_CIPHER_CTX_free(ctx); SELF_TEST_EVENT_onend(event, ret); return ret; } static int self_test_kdf(const ST_KAT_KDF *t, OSSL_ST_EVENT *event, OPENSSL_CTX *libctx) { int ret = 0; int i, numparams; unsigned char out[64]; EVP_KDF *kdf = NULL; EVP_KDF_CTX *ctx = NULL; OSSL_PARAM params[16]; const OSSL_PARAM *settables = NULL; numparams = OSSL_NELEM(params); SELF_TEST_EVENT_onbegin(event, OSSL_SELF_TEST_TYPE_KAT_KDF, t->desc); /* Zeroize the params array to avoid mem leaks on error */ for (i = 0; i < numparams; ++i) params[i] = OSSL_PARAM_construct_end(); kdf = EVP_KDF_fetch(libctx, t->algorithm, ""); ctx = EVP_KDF_CTX_new(kdf); if (ctx == NULL) goto end; settables = EVP_KDF_settable_ctx_params(kdf); for (i = 0; t->ctrls[i].name != NULL; ++i) { if (!ossl_assert(i < (numparams - 1))) goto end; if (!OSSL_PARAM_allocate_from_text(&params[i], settables, t->ctrls[i].name, t->ctrls[i].value, strlen(t->ctrls[i].value))) goto end; } if (!EVP_KDF_CTX_set_params(ctx, params)) goto end; if (t->expected_len > sizeof(out)) goto end; if (EVP_KDF_derive(ctx, out, t->expected_len) <= 0) goto end; SELF_TEST_EVENT_oncorrupt_byte(event, out); if (memcmp(out, t->expected, t->expected_len) != 0) goto end; ret = 1; end: for (i = 0; params[i].key != NULL; ++i) OPENSSL_free(params[i].data); EVP_KDF_free(kdf); EVP_KDF_CTX_free(ctx); SELF_TEST_EVENT_onend(event, ret); return ret; } /* * Test a data driven list of KAT's for digest algorithms. * All tests are run regardless of if they fail or not. * Return 0 if any test fails. */ static int self_test_digests(OSSL_ST_EVENT *event, OPENSSL_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_digest_tests); ++i) { if (!self_test_digest(&st_kat_digest_tests[i], event, libctx)) ret = 0; } return ret; } static int self_test_ciphers(OSSL_ST_EVENT *event, OPENSSL_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_cipher_tests); ++i) { if (!self_test_cipher(&st_kat_cipher_tests[i], event, libctx)) ret = 0; } return ret; } static int self_test_kdfs(OSSL_ST_EVENT *event, OPENSSL_CTX *libctx) { int i, ret = 1; for (i = 0; i < (int)OSSL_NELEM(st_kat_kdf_tests); ++i) { if (!self_test_kdf(&st_kat_kdf_tests[i], event, libctx)) ret = 0; } return ret; } /* * Run the algorithm KAT's. * Return 1 is successful, otherwise return 0. * This runs all the tests regardless of if any fail. * * TODO(3.0) Add self tests for KA, DRBG, Sign/Verify when they become available */ int SELF_TEST_kats(OSSL_ST_EVENT *event, OPENSSL_CTX *libctx) { int ret = 1; if (!self_test_digests(event, libctx)) ret = 0; if (!self_test_ciphers(event, libctx)) ret = 0; if (!self_test_kdfs(event, libctx)) ret = 0; return ret; }
dotsimon/openssl
providers/implementations/serializers/serializer_local.h
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core.h> #include <openssl/core_numbers.h> #include <openssl/bn.h> #include <openssl/asn1.h> /* i2d_of_void */ #include <openssl/x509.h> /* X509_SIG */ #include <openssl/types.h> struct pkcs8_encrypt_ctx_st { /* Set to 1 if intending to encrypt/decrypt, otherwise 0 */ int cipher_intent; EVP_CIPHER *cipher; int pbe_nid; /* For future variation */ /* Passphrase that was passed by the caller */ void *cipher_pass; size_t cipher_pass_length; /* This callback is only used of |cipher_pass| is NULL */ OSSL_PASSPHRASE_CALLBACK *cb; void *cbarg; }; OSSL_OP_keymgmt_new_fn *ossl_prov_get_keymgmt_new(const OSSL_DISPATCH *fns); OSSL_OP_keymgmt_free_fn *ossl_prov_get_keymgmt_free(const OSSL_DISPATCH *fns); OSSL_OP_keymgmt_import_fn *ossl_prov_get_keymgmt_import(const OSSL_DISPATCH *fns); OSSL_OP_keymgmt_new_fn *ossl_prov_get_keymgmt_rsa_new(void); OSSL_OP_keymgmt_free_fn *ossl_prov_get_keymgmt_rsa_free(void); OSSL_OP_keymgmt_import_fn *ossl_prov_get_keymgmt_rsa_import(void); OSSL_OP_keymgmt_new_fn *ossl_prov_get_keymgmt_dh_new(void); OSSL_OP_keymgmt_free_fn *ossl_prov_get_keymgmt_dh_free(void); OSSL_OP_keymgmt_import_fn *ossl_prov_get_keymgmt_dh_import(void); OSSL_OP_keymgmt_new_fn *ossl_prov_get_keymgmt_dsa_new(void); OSSL_OP_keymgmt_free_fn *ossl_prov_get_keymgmt_dsa_free(void); OSSL_OP_keymgmt_import_fn *ossl_prov_get_keymgmt_dsa_import(void); int ossl_prov_prepare_dh_params(const void *dh, int nid, ASN1_STRING **pstr, int *pstrtype); int ossl_prov_dh_pub_to_der(const void *dh, unsigned char **pder); int ossl_prov_dh_priv_to_der(const void *dh, unsigned char **pder); int ossl_prov_prepare_dsa_params(const void *dsa, int nid, ASN1_STRING **pstr, int *pstrtype); /* * Special variant of ossl_prov_prepare_dsa_params() that requires all * three parameters (P, Q and G) to be set. This is used when serializing * the public key. */ int ossl_prov_prepare_all_dsa_params(const void *dsa, int nid, ASN1_STRING **pstr, int *pstrtype); int ossl_prov_dsa_pub_to_der(const void *dsa, unsigned char **pder); int ossl_prov_dsa_priv_to_der(const void *dsa, unsigned char **pder); int ossl_prov_print_labeled_bignum(BIO *out, const char *label, const BIGNUM *bn); int ossl_prov_print_rsa(BIO *out, RSA *rsa, int priv); enum dh_print_type { dh_print_priv, dh_print_pub, dh_print_params }; int ossl_prov_print_dh(BIO *out, DH *dh, enum dh_print_type type); enum dsa_print_type { dsa_print_priv, dsa_print_pub, dsa_print_params }; int ossl_prov_print_dsa(BIO *out, DSA *dsa, enum dsa_print_type type); int ossl_prov_write_priv_der_from_obj(BIO *out, const void *obj, int obj_nid, int (*p2s)(const void *obj, int nid, ASN1_STRING **str, int *strtype), int (*k2d)(const void *obj, unsigned char **pder), struct pkcs8_encrypt_ctx_st *ctx); int ossl_prov_write_priv_pem_from_obj(BIO *out, const void *obj, int obj_nid, int (*p2s)(const void *obj, int nid, ASN1_STRING **str, int *strtype), int (*k2d)(const void *obj, unsigned char **pder), struct pkcs8_encrypt_ctx_st *ctx); int ossl_prov_write_pub_der_from_obj(BIO *out, const void *obj, int obj_nid, int (*p2s)(const void *obj, int nid, ASN1_STRING **str, int *strtype), int (*k2d)(const void *obj, unsigned char **pder)); int ossl_prov_write_pub_pem_from_obj(BIO *out, const void *obj, int obj_nid, int (*p2s)(const void *obj, int nid, ASN1_STRING **str, int *strtype), int (*k2d)(const void *obj, unsigned char **pder));
dotsimon/openssl
test/evp_pkey_provided_test.c
<gh_stars>1-10 /* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/serializer.h> #include <openssl/provider.h> #include <openssl/params.h> #include <openssl/core_names.h> #include "internal/nelem.h" #include "crypto/evp.h" /* For the internal API */ #include "testutil.h" static int test_print_key_using_pem(const EVP_PKEY *pk) { if (!TEST_true(EVP_PKEY_print_private(bio_out, pk, 0, NULL)) /* Public key in PEM form */ || !TEST_true(PEM_write_bio_PUBKEY(bio_out, pk)) /* Unencrypted private key in PEM form */ || !TEST_true(PEM_write_bio_PrivateKey(bio_out, pk, NULL, NULL, 0, NULL, NULL)) /* Encrypted private key in PEM form */ || !TEST_true(PEM_write_bio_PrivateKey(bio_out, pk, EVP_aes_256_cbc(), (unsigned char *)"pass", 4, NULL, NULL))) return 0; return 1; } static int test_print_key_using_serializer(const EVP_PKEY *pk) { const char *pq = OSSL_SERIALIZER_PrivateKey_TO_PEM_PQ; OSSL_SERIALIZER_CTX *ctx = NULL; int ret = 1; /* Make a context, it's valid for several prints */ TEST_note("Setting up a OSSL_SERIALIZER context with passphrase"); if (!TEST_ptr(ctx = OSSL_SERIALIZER_CTX_new_by_EVP_PKEY(pk, pq)) /* Check that this operation is supported */ || !TEST_ptr(OSSL_SERIALIZER_CTX_get_serializer(ctx)) /* Set a passphrase to be used later */ || !TEST_true(OSSL_SERIALIZER_CTX_set_passphrase(ctx, (unsigned char *)"pass", 4))) goto err; /* Use no cipher. This should give us an unencrypted PEM */ TEST_note("Displaying PEM with no encryption"); if (!TEST_true(OSSL_SERIALIZER_to_bio(ctx, bio_out))) ret = 0; /* Use a valid cipher name */ TEST_note("Displaying PEM encrypted with AES-256-CBC"); if (!TEST_true(OSSL_SERIALIZER_CTX_set_cipher(ctx, "AES-256-CBC", NULL)) || !TEST_true(OSSL_SERIALIZER_to_bio(ctx, bio_out))) ret = 0; /* Use an invalid cipher name, which should generate no output */ TEST_note("NOT Displaying PEM encrypted with (invalid) FOO"); if (!TEST_false(OSSL_SERIALIZER_CTX_set_cipher(ctx, "FOO", NULL)) || !TEST_false(OSSL_SERIALIZER_to_bio(ctx, bio_out))) ret = 0; /* Clear the cipher. This should give us an unencrypted PEM again */ TEST_note("Displaying PEM with encryption cleared (no encryption)"); if (!TEST_true(OSSL_SERIALIZER_CTX_set_cipher(ctx, NULL, NULL)) || !TEST_true(OSSL_SERIALIZER_to_bio(ctx, bio_out))) ret = 0; err: OSSL_SERIALIZER_CTX_free(ctx); return ret; } /* Array indexes used in test_fromdata_rsa */ #define N 0 #define E 1 #define D 2 #define P 3 #define Q 4 #define DP 5 #define DQ 6 #define QINV 7 static int test_fromdata_rsa(void) { int ret = 0; EVP_PKEY_CTX *ctx = NULL, *key_ctx = NULL; EVP_PKEY *pk = NULL; /* * 32-bit RSA key, extracted from this command, * executed with OpenSSL 1.0.2: * * openssl genrsa 32 | openssl rsa -text */ static unsigned long key_numbers[] = { 0xbc747fc5, /* N */ 0x10001, /* E */ 0x7b133399, /* D */ 0xe963, /* P */ 0xceb7, /* Q */ 0x8599, /* DP */ 0xbd87, /* DQ */ 0xcc3b, /* QINV */ }; OSSL_PARAM fromdata_params[] = { OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_N, &key_numbers[N]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_E, &key_numbers[E]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_D, &key_numbers[D]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_FACTOR, &key_numbers[P]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_FACTOR, &key_numbers[Q]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_EXPONENT, &key_numbers[DP]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_EXPONENT, &key_numbers[DQ]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_RSA_COEFFICIENT, &key_numbers[QINV]), OSSL_PARAM_END }; if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "RSA", NULL))) goto err; if (!TEST_true(EVP_PKEY_key_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pk, fromdata_params)) || !TEST_int_eq(EVP_PKEY_bits(pk), 32) || !TEST_int_eq(EVP_PKEY_security_bits(pk), 8) || !TEST_int_eq(EVP_PKEY_size(pk), 4)) goto err; if (!TEST_ptr(key_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pk, ""))) goto err; if (!TEST_true(EVP_PKEY_check(key_ctx)) || !TEST_true(EVP_PKEY_public_check(key_ctx)) || !TEST_true(EVP_PKEY_private_check(key_ctx)) || !TEST_true(EVP_PKEY_pairwise_check(key_ctx))) goto err; ret = test_print_key_using_pem(pk) | test_print_key_using_serializer(pk); err: EVP_PKEY_free(pk); EVP_PKEY_CTX_free(key_ctx); EVP_PKEY_CTX_free(ctx); return ret; } #ifndef OPENSSL_NO_DH /* Array indexes used in test_fromdata_dh */ #define PRIV_KEY 0 #define PUB_KEY 1 #define FFC_P 2 #define FFC_G 3 static int test_fromdata_dh(void) { int ret = 0; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pk = NULL; /* * 32-bit DH key, extracted from this command, * executed with OpenSSL 1.0.2: * * openssl dhparam -out dhp.pem 32 * openssl genpkey -paramfile dhp.pem | openssl pkey -text */ static unsigned long key_numbers[] = { 0x666c2b06, /* priv-key */ 0x6fa6de50, /* pub-key */ 0x8bb45f53, /* P */ 0x2, /* G */ }; OSSL_PARAM fromdata_params[] = { OSSL_PARAM_ulong(OSSL_PKEY_PARAM_PRIV_KEY, &key_numbers[PRIV_KEY]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_PUB_KEY, &key_numbers[PUB_KEY]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_FFC_P, &key_numbers[FFC_P]), OSSL_PARAM_ulong(OSSL_PKEY_PARAM_FFC_G, &key_numbers[FFC_G]), OSSL_PARAM_END }; if (!TEST_ptr(ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL))) goto err; if (!TEST_true(EVP_PKEY_key_fromdata_init(ctx)) || !TEST_true(EVP_PKEY_fromdata(ctx, &pk, fromdata_params)) || !TEST_int_eq(EVP_PKEY_bits(pk), 32) || !TEST_int_eq(EVP_PKEY_security_bits(pk), 0) /* Missing Q */ || !TEST_int_eq(EVP_PKEY_size(pk), 4)) goto err; ret = test_print_key_using_pem(pk) | test_print_key_using_serializer(pk); err: EVP_PKEY_free(pk); EVP_PKEY_CTX_free(ctx); return ret; } #endif int setup_tests(void) { ADD_TEST(test_fromdata_rsa); #ifndef OPENSSL_NO_DH ADD_TEST(test_fromdata_dh); #endif return 1; }
dotsimon/openssl
crypto/asn1/i2d_pr.c
<gh_stars>1-10 /* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/serializer.h> #include <openssl/buffer.h> #include <openssl/x509.h> #include "crypto/asn1.h" #include "crypto/evp.h" int i2d_PrivateKey(const EVP_PKEY *a, unsigned char **pp) { if (a->ameth && a->ameth->old_priv_encode) { return a->ameth->old_priv_encode(a, pp); } if (a->ameth && a->ameth->priv_encode) { PKCS8_PRIV_KEY_INFO *p8 = EVP_PKEY2PKCS8(a); int ret = 0; if (p8 != NULL) { ret = i2d_PKCS8_PRIV_KEY_INFO(p8, pp); PKCS8_PRIV_KEY_INFO_free(p8); } return ret; } if (a->pkeys[0].keymgmt != NULL) { const char *serprop = OSSL_SERIALIZER_PrivateKey_TO_DER_PQ; OSSL_SERIALIZER_CTX *ctx = OSSL_SERIALIZER_CTX_new_by_EVP_PKEY(a, serprop); BIO *out = BIO_new(BIO_s_mem()); BUF_MEM *buf = NULL; int ret = -1; if (ctx != NULL && out != NULL && OSSL_SERIALIZER_CTX_get_serializer(ctx) != NULL && OSSL_SERIALIZER_to_bio(ctx, out) && BIO_get_mem_ptr(out, &buf) > 0) { ret = buf->length; if (pp != NULL) { if (*pp == NULL) { *pp = (unsigned char *)buf->data; buf->length = 0; buf->data = NULL; } else { memcpy(*pp, buf->data, ret); *pp += ret; } } } BIO_free(out); OSSL_SERIALIZER_CTX_free(ctx); return ret; } ASN1err(ASN1_F_I2D_PRIVATEKEY, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE); return -1; }
dotsimon/openssl
providers/implementations/asymciphers/rsa_enc.c
<filename>providers/implementations/asymciphers/rsa_enc.c /* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/crypto.h> #include <openssl/evp.h> #include <openssl/core_numbers.h> #include <openssl/core_names.h> #include <openssl/rsa.h> #include <openssl/params.h> #include <openssl/err.h> /* Just for SSL_MAX_MASTER_KEY_LENGTH */ #include <openssl/ssl.h> #include "internal/constant_time.h" #include "internal/sizes.h" #include "crypto/rsa.h" #include "prov/providercommonerr.h" #include "prov/provider_ctx.h" #include "prov/implementations.h" #include <stdlib.h> static OSSL_OP_asym_cipher_newctx_fn rsa_newctx; static OSSL_OP_asym_cipher_encrypt_init_fn rsa_init; static OSSL_OP_asym_cipher_encrypt_fn rsa_encrypt; static OSSL_OP_asym_cipher_decrypt_init_fn rsa_init; static OSSL_OP_asym_cipher_decrypt_fn rsa_decrypt; static OSSL_OP_asym_cipher_freectx_fn rsa_freectx; static OSSL_OP_asym_cipher_dupctx_fn rsa_dupctx; static OSSL_OP_asym_cipher_get_ctx_params_fn rsa_get_ctx_params; static OSSL_OP_asym_cipher_gettable_ctx_params_fn rsa_gettable_ctx_params; static OSSL_OP_asym_cipher_set_ctx_params_fn rsa_set_ctx_params; static OSSL_OP_asym_cipher_settable_ctx_params_fn rsa_settable_ctx_params; static OSSL_ITEM padding_item[] = { { RSA_PKCS1_PADDING, "pkcs1" }, { RSA_SSLV23_PADDING, "sslv23" }, { RSA_NO_PADDING, "none" }, { RSA_PKCS1_OAEP_PADDING, "oaep" }, /* Correct spelling first */ { RSA_PKCS1_OAEP_PADDING, "oeap" }, { RSA_X931_PADDING, "x931" }, { RSA_PKCS1_PSS_PADDING, "pss" }, { 0, NULL } }; /* * What's passed as an actual key is defined by the KEYMGMT interface. * We happen to know that our KEYMGMT simply passes RSA structures, so * we use that here too. */ typedef struct { OPENSSL_CTX *libctx; RSA *rsa; int pad_mode; /* OAEP message digest */ EVP_MD *oaep_md; /* message digest for MGF1 */ EVP_MD *mgf1_md; /* OAEP label */ unsigned char *oaep_label; size_t oaep_labellen; /* TLS padding */ unsigned int client_version; unsigned int alt_version; } PROV_RSA_CTX; static void *rsa_newctx(void *provctx) { PROV_RSA_CTX *prsactx = OPENSSL_zalloc(sizeof(PROV_RSA_CTX)); if (prsactx == NULL) return NULL; prsactx->libctx = PROV_LIBRARY_CONTEXT_OF(provctx); return prsactx; } static int rsa_init(void *vprsactx, void *vrsa) { PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx; if (prsactx == NULL || vrsa == NULL || !RSA_up_ref(vrsa)) return 0; RSA_free(prsactx->rsa); prsactx->rsa = vrsa; prsactx->pad_mode = RSA_PKCS1_PADDING; return 1; } static int rsa_encrypt(void *vprsactx, unsigned char *out, size_t *outlen, size_t outsize, const unsigned char *in, size_t inlen) { PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx; int ret; if (out == NULL) { size_t len = RSA_size(prsactx->rsa); if (len == 0) { ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY); return 0; } *outlen = len; return 1; } if (prsactx->pad_mode == RSA_PKCS1_OAEP_PADDING) { int rsasize = RSA_size(prsactx->rsa); unsigned char *tbuf; if ((tbuf = OPENSSL_malloc(rsasize)) == NULL) { PROVerr(0, ERR_R_MALLOC_FAILURE); return 0; } if (prsactx->oaep_md == NULL) { prsactx->oaep_md = EVP_MD_fetch(prsactx->libctx, "SHA-1", NULL); PROVerr(0, ERR_R_INTERNAL_ERROR); return 0; } ret = RSA_padding_add_PKCS1_OAEP_mgf1(tbuf, rsasize, in, inlen, prsactx->oaep_label, prsactx->oaep_labellen, prsactx->oaep_md, prsactx->mgf1_md); if (!ret) { OPENSSL_free(tbuf); return 0; } ret = RSA_public_encrypt(rsasize, tbuf, out, prsactx->rsa, RSA_NO_PADDING); OPENSSL_free(tbuf); } else { ret = RSA_public_encrypt(inlen, in, out, prsactx->rsa, prsactx->pad_mode); } /* A ret value of 0 is not an error */ if (ret < 0) return ret; *outlen = ret; return 1; } static int rsa_decrypt(void *vprsactx, unsigned char *out, size_t *outlen, size_t outsize, const unsigned char *in, size_t inlen) { PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx; int ret; size_t len = RSA_size(prsactx->rsa); if (prsactx->pad_mode == RSA_PKCS1_WITH_TLS_PADDING) { if (out == NULL) { *outlen = SSL_MAX_MASTER_KEY_LENGTH; return 1; } if (outsize < SSL_MAX_MASTER_KEY_LENGTH) { ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH); return 0; } } else { if (out == NULL) { if (len == 0) { ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY); return 0; } *outlen = len; return 1; } if (outsize < len) { ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH); return 0; } } if (prsactx->pad_mode == RSA_PKCS1_OAEP_PADDING || prsactx->pad_mode == RSA_PKCS1_WITH_TLS_PADDING) { unsigned char *tbuf; if ((tbuf = OPENSSL_malloc(len)) == NULL) { PROVerr(0, ERR_R_MALLOC_FAILURE); return 0; } ret = RSA_private_decrypt(inlen, in, tbuf, prsactx->rsa, RSA_NO_PADDING); /* * With no padding then, on success ret should be len, otherwise an * error occurred (non-constant time) */ if (ret != (int)len) { OPENSSL_free(tbuf); ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_DECRYPT); return 0; } if (prsactx->pad_mode == RSA_PKCS1_OAEP_PADDING) { if (prsactx->oaep_md == NULL) { prsactx->oaep_md = EVP_MD_fetch(prsactx->libctx, "SHA-1", NULL); if (prsactx->oaep_md == NULL) { PROVerr(0, ERR_R_INTERNAL_ERROR); return 0; } } ret = RSA_padding_check_PKCS1_OAEP_mgf1(out, outsize, tbuf, len, len, prsactx->oaep_label, prsactx->oaep_labellen, prsactx->oaep_md, prsactx->mgf1_md); } else { /* RSA_PKCS1_WITH_TLS_PADDING */ if (prsactx->client_version <= 0) { ERR_raise(ERR_LIB_PROV, PROV_R_BAD_TLS_CLIENT_VERSION); return 0; } ret = rsa_padding_check_PKCS1_type_2_TLS(out, outsize, tbuf, len, prsactx->client_version, prsactx->alt_version); } OPENSSL_free(tbuf); } else { ret = RSA_private_decrypt(inlen, in, out, prsactx->rsa, prsactx->pad_mode); } *outlen = constant_time_select_s(constant_time_msb_s(ret), *outlen, ret); ret = constant_time_select_int(constant_time_msb(ret), 0, 1); return ret; } static void rsa_freectx(void *vprsactx) { PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx; RSA_free(prsactx->rsa); EVP_MD_free(prsactx->oaep_md); EVP_MD_free(prsactx->mgf1_md); OPENSSL_free(prsactx); } static void *rsa_dupctx(void *vprsactx) { PROV_RSA_CTX *srcctx = (PROV_RSA_CTX *)vprsactx; PROV_RSA_CTX *dstctx; dstctx = OPENSSL_zalloc(sizeof(*srcctx)); if (dstctx == NULL) return NULL; *dstctx = *srcctx; if (dstctx->rsa != NULL && !RSA_up_ref(dstctx->rsa)) { OPENSSL_free(dstctx); return NULL; } if (dstctx->oaep_md != NULL && !EVP_MD_up_ref(dstctx->oaep_md)) { RSA_free(dstctx->rsa); OPENSSL_free(dstctx); return NULL; } if (dstctx->mgf1_md != NULL && !EVP_MD_up_ref(dstctx->mgf1_md)) { RSA_free(dstctx->rsa); EVP_MD_free(dstctx->oaep_md); OPENSSL_free(dstctx); return NULL; } return dstctx; } static int rsa_get_ctx_params(void *vprsactx, OSSL_PARAM *params) { PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx; OSSL_PARAM *p; if (prsactx == NULL || params == NULL) return 0; p = OSSL_PARAM_locate(params, OSSL_ASYM_CIPHER_PARAM_PAD_MODE); if (p != NULL) switch (p->data_type) { case OSSL_PARAM_INTEGER: /* Support for legacy pad mode number */ if (!OSSL_PARAM_set_int(p, prsactx->pad_mode)) return 0; break; case OSSL_PARAM_UTF8_STRING: { int i; const char *word = NULL; for (i = 0; padding_item[i].id != 0; i++) { if (prsactx->pad_mode == (int)padding_item[i].id) { word = padding_item[i].ptr; break; } } if (word != NULL) { if (!OSSL_PARAM_set_utf8_string(p, word)) return 0; } else { ERR_raise(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR); } } break; default: return 0; } p = OSSL_PARAM_locate(params, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST); if (p != NULL && !OSSL_PARAM_set_utf8_string(p, prsactx->oaep_md == NULL ? "" : EVP_MD_name(prsactx->oaep_md))) return 0; p = OSSL_PARAM_locate(params, OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST); if (p != NULL) { EVP_MD *mgf1_md = prsactx->mgf1_md == NULL ? prsactx->oaep_md : prsactx->mgf1_md; if (!OSSL_PARAM_set_utf8_string(p, mgf1_md == NULL ? "" : EVP_MD_name(mgf1_md))) return 0; } p = OSSL_PARAM_locate(params, OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL); if (p != NULL && !OSSL_PARAM_set_octet_ptr(p, prsactx->oaep_label, 0)) return 0; p = OSSL_PARAM_locate(params, OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL_LEN); if (p != NULL && !OSSL_PARAM_set_size_t(p, prsactx->oaep_labellen)) return 0; p = OSSL_PARAM_locate(params, OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION); if (p != NULL && !OSSL_PARAM_set_uint(p, prsactx->client_version)) return 0; p = OSSL_PARAM_locate(params, OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION); if (p != NULL && !OSSL_PARAM_set_uint(p, prsactx->alt_version)) return 0; return 1; } static const OSSL_PARAM known_gettable_ctx_params[] = { OSSL_PARAM_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, NULL, 0), OSSL_PARAM_utf8_string(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, NULL, 0), OSSL_PARAM_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST, NULL, 0), OSSL_PARAM_DEFN(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, OSSL_PARAM_OCTET_PTR, NULL, 0), OSSL_PARAM_size_t(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL_LEN, NULL), OSSL_PARAM_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION, NULL), OSSL_PARAM_uint(OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION, NULL), OSSL_PARAM_END }; static const OSSL_PARAM *rsa_gettable_ctx_params(void) { return known_gettable_ctx_params; } static int rsa_set_ctx_params(void *vprsactx, const OSSL_PARAM params[]) { PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx; const OSSL_PARAM *p; char mdname[OSSL_MAX_NAME_SIZE]; char mdprops[OSSL_MAX_PROPQUERY_SIZE] = { '\0' }; char *str = mdname; if (prsactx == NULL || params == NULL) return 0; p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST); if (p != NULL) { if (!OSSL_PARAM_get_utf8_string(p, &str, sizeof(mdname))) return 0; str = mdprops; p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS); if (p != NULL) { if (!OSSL_PARAM_get_utf8_string(p, &str, sizeof(mdprops))) return 0; } EVP_MD_free(prsactx->oaep_md); prsactx->oaep_md = EVP_MD_fetch(prsactx->libctx, mdname, mdprops); if (prsactx->oaep_md == NULL) return 0; } p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_PAD_MODE); if (p != NULL) { int pad_mode = 0; switch (p->data_type) { case OSSL_PARAM_INTEGER: /* Support for legacy pad mode number */ if (!OSSL_PARAM_get_int(p, &pad_mode)) return 0; break; case OSSL_PARAM_UTF8_STRING: { int i; if (p->data == NULL) return 0; for (i = 0; padding_item[i].id != 0; i++) { if (strcmp(p->data, padding_item[i].ptr) == 0) { pad_mode = padding_item[i].id; break; } } } break; default: return 0; } /* * PSS padding is for signatures only so is not compatible with * asymmetric cipher use. */ if (pad_mode == RSA_PKCS1_PSS_PADDING) return 0; if (pad_mode == RSA_PKCS1_OAEP_PADDING && prsactx->oaep_md == NULL) { prsactx->oaep_md = EVP_MD_fetch(prsactx->libctx, "SHA1", mdprops); if (prsactx->oaep_md == NULL) return 0; } prsactx->pad_mode = pad_mode; } p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST); if (p != NULL) { if (!OSSL_PARAM_get_utf8_string(p, &str, sizeof(mdname))) return 0; str = mdprops; p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST_PROPS); if (p != NULL) { if (!OSSL_PARAM_get_utf8_string(p, &str, sizeof(mdprops))) return 0; } else { str = NULL; } EVP_MD_free(prsactx->mgf1_md); prsactx->mgf1_md = EVP_MD_fetch(prsactx->libctx, mdname, str); if (prsactx->mgf1_md == NULL) return 0; } p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL); if (p != NULL) { void *tmp_label = NULL; size_t tmp_labellen; if (!OSSL_PARAM_get_octet_string(p, &tmp_label, 0, &tmp_labellen)) return 0; OPENSSL_free(prsactx->oaep_label); prsactx->oaep_label = (unsigned char *)tmp_label; prsactx->oaep_labellen = tmp_labellen; } p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION); if (p != NULL) { unsigned int client_version; if (!OSSL_PARAM_get_uint(p, &client_version)) return 0; prsactx->client_version = client_version; } p = OSSL_PARAM_locate_const(params, OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION); if (p != NULL) { unsigned int alt_version; if (!OSSL_PARAM_get_uint(p, &alt_version)) return 0; prsactx->alt_version = alt_version; } return 1; } static const OSSL_PARAM known_settable_ctx_params[] = { OSSL_PARAM_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, NULL, 0), OSSL_PARAM_utf8_string(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, NULL, 0), OSSL_PARAM_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST, NULL, 0), OSSL_PARAM_utf8_string(OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST_PROPS, NULL, 0), OSSL_PARAM_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, NULL, 0), OSSL_PARAM_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION, NULL), OSSL_PARAM_uint(OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION, NULL), OSSL_PARAM_END }; static const OSSL_PARAM *rsa_settable_ctx_params(void) { return known_settable_ctx_params; } const OSSL_DISPATCH rsa_asym_cipher_functions[] = { { OSSL_FUNC_ASYM_CIPHER_NEWCTX, (void (*)(void))rsa_newctx }, { OSSL_FUNC_ASYM_CIPHER_ENCRYPT_INIT, (void (*)(void))rsa_init }, { OSSL_FUNC_ASYM_CIPHER_ENCRYPT, (void (*)(void))rsa_encrypt }, { OSSL_FUNC_ASYM_CIPHER_DECRYPT_INIT, (void (*)(void))rsa_init }, { OSSL_FUNC_ASYM_CIPHER_DECRYPT, (void (*)(void))rsa_decrypt }, { OSSL_FUNC_ASYM_CIPHER_FREECTX, (void (*)(void))rsa_freectx }, { OSSL_FUNC_ASYM_CIPHER_DUPCTX, (void (*)(void))rsa_dupctx }, { OSSL_FUNC_ASYM_CIPHER_GET_CTX_PARAMS, (void (*)(void))rsa_get_ctx_params }, { OSSL_FUNC_ASYM_CIPHER_GETTABLE_CTX_PARAMS, (void (*)(void))rsa_gettable_ctx_params }, { OSSL_FUNC_ASYM_CIPHER_SET_CTX_PARAMS, (void (*)(void))rsa_set_ctx_params }, { OSSL_FUNC_ASYM_CIPHER_SETTABLE_CTX_PARAMS, (void (*)(void))rsa_settable_ctx_params }, { 0, NULL } };
dotsimon/openssl
test/cmp_msg_test.c
<gh_stars>1-10 /* * Copyright 2007-2019 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "cmp_testlib.h" static const char *server_cert_f; static const char *pkcs10_f; typedef struct test_fixture { const char *test_case_name; OSSL_CMP_CTX *cmp_ctx; /* for msg create tests */ int bodytype; int err_code; /* for certConf */ int fail_info; /* for protection tests */ OSSL_CMP_MSG *msg; int expected; /* for error and response messages */ OSSL_CMP_PKISI *si; } CMP_MSG_TEST_FIXTURE; static unsigned char ref[CMP_TEST_REFVALUE_LENGTH]; static void tear_down(CMP_MSG_TEST_FIXTURE *fixture) { OSSL_CMP_CTX_free(fixture->cmp_ctx); OSSL_CMP_MSG_free(fixture->msg); OSSL_CMP_PKISI_free(fixture->si); OPENSSL_free(fixture); } #define SET_OPT_UNPROTECTED_SEND(ctx, val) \ OSSL_CMP_CTX_set_option((ctx), OSSL_CMP_OPT_UNPROTECTED_SEND, (val)) static CMP_MSG_TEST_FIXTURE *set_up(const char *const test_case_name) { CMP_MSG_TEST_FIXTURE *fixture; if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture)))) return NULL; fixture->test_case_name = test_case_name; if (!TEST_ptr(fixture->cmp_ctx = OSSL_CMP_CTX_new()) || !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 1)) || !TEST_true(OSSL_CMP_CTX_set1_referenceValue(fixture->cmp_ctx, ref, sizeof(ref)))) { tear_down(fixture); return NULL; } return fixture; } static EVP_PKEY *newkey = NULL; static X509 *cert = NULL; #define EXECUTE_MSG_CREATION_TEST(expr) \ do { \ OSSL_CMP_MSG *msg = NULL; \ int good = fixture->expected != 0 ? \ TEST_ptr(msg = (expr)) && TEST_true(valid_asn1_encoding(msg)) : \ TEST_ptr_null(msg = (expr)); \ \ OSSL_CMP_MSG_free(msg); \ return good; \ } while (0) /*- * The following tests call a cmp message creation function. * if fixture->expected != 0: * returns 1 if the message is created and syntactically correct. * if fixture->expected == 0 * returns 1 if message creation returns NULL */ static int execute_certreq_create_test(CMP_MSG_TEST_FIXTURE *fixture) { EXECUTE_MSG_CREATION_TEST(ossl_cmp_certReq_new(fixture->cmp_ctx, fixture->bodytype, fixture->err_code)); } static int execute_errormsg_create_test(CMP_MSG_TEST_FIXTURE *fixture) { EXECUTE_MSG_CREATION_TEST(ossl_cmp_error_new(fixture->cmp_ctx, fixture->si, fixture->err_code, NULL /* fixture->free_text */, 0)); } static int execute_rr_create_test(CMP_MSG_TEST_FIXTURE *fixture) { EXECUTE_MSG_CREATION_TEST(ossl_cmp_rr_new(fixture->cmp_ctx)); } static int execute_certconf_create_test(CMP_MSG_TEST_FIXTURE *fixture) { EXECUTE_MSG_CREATION_TEST(ossl_cmp_certConf_new (fixture->cmp_ctx, fixture->fail_info, NULL)); } static int execute_genm_create_test(CMP_MSG_TEST_FIXTURE *fixture) { EXECUTE_MSG_CREATION_TEST(ossl_cmp_genm_new(fixture->cmp_ctx)); } static int execute_pollreq_create_test(CMP_MSG_TEST_FIXTURE *fixture) { EXECUTE_MSG_CREATION_TEST(ossl_cmp_pollReq_new(fixture->cmp_ctx, 4711)); } static int execute_pkimessage_create_test(CMP_MSG_TEST_FIXTURE *fixture) { EXECUTE_MSG_CREATION_TEST(ossl_cmp_msg_create (fixture->cmp_ctx, fixture->bodytype)); } static int set1_newPkey(OSSL_CMP_CTX *ctx, EVP_PKEY* pkey) { if (!EVP_PKEY_up_ref(pkey)) return 0; if (!OSSL_CMP_CTX_set0_newPkey(ctx, 1, pkey)) { EVP_PKEY_free(pkey); return 0; } return 1; } static int test_cmp_create_ir_protection_set(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); OSSL_CMP_CTX *ctx = fixture->cmp_ctx; unsigned char secret[16]; fixture->bodytype = OSSL_CMP_PKIBODY_IR; fixture->err_code = -1; fixture->expected = 1; if (!TEST_int_eq(1, RAND_bytes(secret, sizeof(secret))) || !TEST_true(SET_OPT_UNPROTECTED_SEND(ctx, 0)) || !TEST_true(set1_newPkey(ctx, newkey)) || !TEST_true(OSSL_CMP_CTX_set1_secretValue(ctx, secret, sizeof(secret)))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_ir_protection_fails(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->bodytype = OSSL_CMP_PKIBODY_IR; fixture->err_code = -1; fixture->expected = 0; if (!TEST_true(OSSL_CMP_CTX_set1_pkey(fixture->cmp_ctx, newkey)) || !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 0)) || !TEST_true(OSSL_CMP_CTX_set1_clCert(fixture->cmp_ctx, cert))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_cr_without_key(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->bodytype = OSSL_CMP_PKIBODY_CR; fixture->err_code = -1; fixture->expected = 0; EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_cr(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->bodytype = OSSL_CMP_PKIBODY_CR; fixture->err_code = -1; fixture->expected = 1; if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_certreq_with_invalid_bodytype(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->bodytype = OSSL_CMP_PKIBODY_RR; fixture->err_code = -1; fixture->expected = 0; if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_p10cr(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); OSSL_CMP_CTX *ctx = fixture->cmp_ctx; X509_REQ *p10cr = NULL; fixture->bodytype = OSSL_CMP_PKIBODY_P10CR; fixture->err_code = CMP_R_ERROR_CREATING_P10CR; fixture->expected = 1; if (!TEST_ptr(p10cr = load_csr(pkcs10_f)) || !TEST_true(set1_newPkey(ctx, newkey)) || !TEST_true(OSSL_CMP_CTX_set1_p10CSR(ctx, p10cr))) { tear_down(fixture); fixture = NULL; } X509_REQ_free(p10cr); EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_p10cr_null(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->bodytype = OSSL_CMP_PKIBODY_P10CR; fixture->err_code = CMP_R_ERROR_CREATING_P10CR; fixture->expected = 0; if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_kur(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->bodytype = OSSL_CMP_PKIBODY_KUR; fixture->err_code = -1; fixture->expected = 1; if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey)) || !TEST_true(OSSL_CMP_CTX_set1_oldCert(fixture->cmp_ctx, cert))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_kur_without_oldcert(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->bodytype = OSSL_CMP_PKIBODY_KUR; fixture->err_code = -1; fixture->expected = 0; if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certreq_create_test, tear_down); return result; } static int test_cmp_create_certconf(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->fail_info = 0; fixture->expected = 1; if (!TEST_true(ossl_cmp_ctx_set0_newCert(fixture->cmp_ctx, X509_dup(cert)))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certconf_create_test, tear_down); return result; } static int test_cmp_create_certconf_badAlg(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_badAlg; fixture->expected = 1; if (!TEST_true(ossl_cmp_ctx_set0_newCert(fixture->cmp_ctx, X509_dup(cert)))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certconf_create_test, tear_down); return result; } static int test_cmp_create_certconf_fail_info_max(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_MAX; fixture->expected = 1; if (!TEST_true(ossl_cmp_ctx_set0_newCert(fixture->cmp_ctx, X509_dup(cert)))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_certconf_create_test, tear_down); return result; } static int test_cmp_create_error_msg(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->si = ossl_cmp_statusinfo_new(OSSL_CMP_PKISTATUS_rejection, OSSL_CMP_PKIFAILUREINFO_systemFailure, NULL); fixture->err_code = -1; fixture->expected = 1; /* Expected: Message creation is successful */ if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_errormsg_create_test, tear_down); return result; } static int test_cmp_create_pollreq(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->expected = 1; EXECUTE_TEST(execute_pollreq_create_test, tear_down); return result; } static int test_cmp_create_rr(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->expected = 1; if (!TEST_true(OSSL_CMP_CTX_set1_oldCert(fixture->cmp_ctx, cert))) { tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_rr_create_test, tear_down); return result; } static int test_cmp_create_genm(void) { OSSL_CMP_ITAV *iv = NULL; SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); fixture->expected = 1; iv = OSSL_CMP_ITAV_create(OBJ_nid2obj(NID_id_it_implicitConfirm), NULL); if (!TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 1)) || !TEST_ptr(iv) || !TEST_true(OSSL_CMP_CTX_push0_genm_ITAV(fixture->cmp_ctx, iv))) { OSSL_CMP_ITAV_free(iv); tear_down(fixture); fixture = NULL; } EXECUTE_TEST(execute_genm_create_test, tear_down); return result; } static int execute_certrep_create(CMP_MSG_TEST_FIXTURE *fixture) { OSSL_CMP_CERTREPMESSAGE *crepmsg = OSSL_CMP_CERTREPMESSAGE_new(); OSSL_CMP_CERTRESPONSE *read_cresp, *cresp = OSSL_CMP_CERTRESPONSE_new(); EVP_PKEY *privkey; X509 *certfromresp = NULL; int res = 0; if (crepmsg == NULL || cresp == NULL) goto err; if (!ASN1_INTEGER_set(cresp->certReqId, 99)) goto err; if ((cresp->certifiedKeyPair = OSSL_CMP_CERTIFIEDKEYPAIR_new()) == NULL) goto err; cresp->certifiedKeyPair->certOrEncCert->type = OSSL_CMP_CERTORENCCERT_CERTIFICATE; if ((cresp->certifiedKeyPair->certOrEncCert->value.certificate = X509_dup(cert)) == NULL || !sk_OSSL_CMP_CERTRESPONSE_push(crepmsg->response, cresp)) goto err; cresp = NULL; read_cresp = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, 99); if (!TEST_ptr(read_cresp)) goto err; if (!TEST_ptr_null(ossl_cmp_certrepmessage_get0_certresponse(crepmsg, 88))) goto err; privkey = OSSL_CMP_CTX_get0_newPkey(fixture->cmp_ctx, 1); /* may be NULL */ certfromresp = ossl_cmp_certresponse_get1_certificate(privkey, read_cresp); if (certfromresp == NULL || !TEST_int_eq(X509_cmp(cert, certfromresp), 0)) goto err; res = 1; err: X509_free(certfromresp); OSSL_CMP_CERTRESPONSE_free(cresp); OSSL_CMP_CERTREPMESSAGE_free(crepmsg); return res; } static int test_cmp_create_certrep(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); EXECUTE_TEST(execute_certrep_create, tear_down); return result; } static int execute_rp_create(CMP_MSG_TEST_FIXTURE *fixture) { OSSL_CMP_PKISI *si = ossl_cmp_statusinfo_new(33, 44, "a text"); X509_NAME *issuer = X509_NAME_new(); ASN1_INTEGER *serial = ASN1_INTEGER_new(); OSSL_CRMF_CERTID *cid = NULL; OSSL_CMP_MSG *rpmsg = NULL; int res = 0; if (si == NULL || issuer == NULL || serial == NULL) goto err; if (!X509_NAME_add_entry_by_txt(issuer, "CN", MBSTRING_ASC, (unsigned char*)"The Issuer", -1, -1, 0) || !ASN1_INTEGER_set(serial, 99) || (cid = OSSL_CRMF_CERTID_gen(issuer, serial)) == NULL || (rpmsg = ossl_cmp_rp_new(fixture->cmp_ctx, si, cid, 1)) == NULL) goto err; if (!TEST_ptr(ossl_cmp_revrepcontent_get_CertId(rpmsg->body->value.rp, 0))) goto err; if (!TEST_ptr(ossl_cmp_revrepcontent_get_pkistatusinfo(rpmsg->body->value.rp, 0))) goto err; res = 1; err: ASN1_INTEGER_free(serial); X509_NAME_free(issuer); OSSL_CRMF_CERTID_free(cid); OSSL_CMP_PKISI_free(si); OSSL_CMP_MSG_free(rpmsg); return res; } static int test_cmp_create_rp(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); EXECUTE_TEST(execute_rp_create, tear_down); return result; } static int execute_pollrep_create(CMP_MSG_TEST_FIXTURE *fixture) { OSSL_CMP_MSG *pollrep; int res = 0; pollrep = ossl_cmp_pollRep_new(fixture->cmp_ctx, 77, 2000); if (!TEST_ptr(pollrep)) return 0; if (!TEST_ptr(ossl_cmp_pollrepcontent_get0_pollrep( pollrep->body->value.pollRep, 77))) goto err; if (!TEST_ptr_null(ossl_cmp_pollrepcontent_get0_pollrep( pollrep->body->value.pollRep, 88))) goto err; res = 1; err: OSSL_CMP_MSG_free(pollrep); return res; } static int test_cmp_create_pollrep(void) { SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); EXECUTE_TEST(execute_pollrep_create, tear_down); return result; } static int test_cmp_pkimessage_create(int bodytype) { X509_REQ *p10cr = NULL; SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up); switch (fixture->bodytype = bodytype) { case OSSL_CMP_PKIBODY_P10CR: fixture->expected = 1; if (!TEST_true(OSSL_CMP_CTX_set1_p10CSR(fixture->cmp_ctx, p10cr = load_csr(pkcs10_f)))) { tear_down(fixture); fixture = NULL; } X509_REQ_free(p10cr); break; case OSSL_CMP_PKIBODY_IR: case OSSL_CMP_PKIBODY_IP: case OSSL_CMP_PKIBODY_CR: case OSSL_CMP_PKIBODY_CP: case OSSL_CMP_PKIBODY_KUR: case OSSL_CMP_PKIBODY_KUP: case OSSL_CMP_PKIBODY_RR: case OSSL_CMP_PKIBODY_RP: case OSSL_CMP_PKIBODY_PKICONF: case OSSL_CMP_PKIBODY_GENM: case OSSL_CMP_PKIBODY_GENP: case OSSL_CMP_PKIBODY_ERROR: case OSSL_CMP_PKIBODY_CERTCONF: case OSSL_CMP_PKIBODY_POLLREQ: case OSSL_CMP_PKIBODY_POLLREP: fixture->expected = 1; break; default: fixture->expected = 0; break; } EXECUTE_TEST(execute_pkimessage_create_test, tear_down); return result; } void cleanup_tests(void) { EVP_PKEY_free(newkey); X509_free(cert); } int setup_tests(void) { if (!test_skip_common_options()) { TEST_error("Error parsing test options\n"); return 0; } if (!TEST_ptr(server_cert_f = test_get_argument(0)) || !TEST_ptr(pkcs10_f = test_get_argument(1))) { TEST_error("usage: cmp_msg_test server.crt pkcs10.der\n"); return 0; } if (!TEST_ptr(newkey = gen_rsa()) || !TEST_ptr(cert = load_pem_cert(server_cert_f)) || !TEST_int_eq(1, RAND_bytes(ref, sizeof(ref)))) { cleanup_tests(); return 0; } /* Message creation tests */ ADD_TEST(test_cmp_create_certreq_with_invalid_bodytype); ADD_TEST(test_cmp_create_ir_protection_fails); ADD_TEST(test_cmp_create_ir_protection_set); ADD_TEST(test_cmp_create_error_msg); ADD_TEST(test_cmp_create_certconf); ADD_TEST(test_cmp_create_certconf_badAlg); ADD_TEST(test_cmp_create_certconf_fail_info_max); ADD_TEST(test_cmp_create_kur); ADD_TEST(test_cmp_create_kur_without_oldcert); ADD_TEST(test_cmp_create_cr); ADD_TEST(test_cmp_create_cr_without_key); ADD_TEST(test_cmp_create_p10cr); ADD_TEST(test_cmp_create_p10cr_null); ADD_TEST(test_cmp_create_pollreq); ADD_TEST(test_cmp_create_rr); ADD_TEST(test_cmp_create_rp); ADD_TEST(test_cmp_create_genm); ADD_TEST(test_cmp_create_certrep); ADD_TEST(test_cmp_create_pollrep); ADD_ALL_TESTS_NOSUBTEST(test_cmp_pkimessage_create, OSSL_CMP_PKIBODY_POLLREP + 1); return 1; }
dotsimon/openssl
providers/implementations/serializers/serializer_dh_pub.c
<filename>providers/implementations/serializers/serializer_dh_pub.c /* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_numbers.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/dh.h> #include <openssl/types.h> #include <openssl/params.h> #include "prov/bio.h" #include "prov/implementations.h" #include "serializer_local.h" static OSSL_OP_serializer_newctx_fn dh_pub_newctx; static OSSL_OP_serializer_freectx_fn dh_pub_freectx; static OSSL_OP_serializer_serialize_data_fn dh_pub_der_data; static OSSL_OP_serializer_serialize_object_fn dh_pub_der; static OSSL_OP_serializer_serialize_data_fn dh_pub_pem_data; static OSSL_OP_serializer_serialize_object_fn dh_pub_pem; static OSSL_OP_serializer_serialize_data_fn dh_pub_print_data; static OSSL_OP_serializer_serialize_object_fn dh_pub_print; /* Public key : context */ /* * There's no specific implementation context, so we use the provider context */ static void *dh_pub_newctx(void *provctx) { return provctx; } static void dh_pub_freectx(void *ctx) { } /* Public key : DER */ static int dh_pub_der_data(void *ctx, const OSSL_PARAM params[], BIO *out, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { OSSL_OP_keymgmt_new_fn *dh_new = ossl_prov_get_keymgmt_dh_new(); OSSL_OP_keymgmt_free_fn *dh_free = ossl_prov_get_keymgmt_dh_free(); OSSL_OP_keymgmt_import_fn *dh_import = ossl_prov_get_keymgmt_dh_import(); int ok = 0; if (dh_import != NULL) { DH *dh; /* ctx == provctx */ if ((dh = dh_new(ctx)) != NULL && dh_import(dh, OSSL_KEYMGMT_SELECT_KEYPAIR, params) && dh_pub_der(ctx, dh, out, cb, cbarg)) ok = 1; dh_free(dh); } return ok; } static int dh_pub_der(void *ctx, void *dh, BIO *out, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return ossl_prov_write_pub_der_from_obj(out, dh, EVP_PKEY_DH, ossl_prov_prepare_dh_params, ossl_prov_dh_pub_to_der); } /* Public key : PEM */ static int dh_pub_pem_data(void *ctx, const OSSL_PARAM params[], BIO *out, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { OSSL_OP_keymgmt_new_fn *dh_new = ossl_prov_get_keymgmt_dh_new(); OSSL_OP_keymgmt_free_fn *dh_free = ossl_prov_get_keymgmt_dh_free(); OSSL_OP_keymgmt_import_fn *dh_import = ossl_prov_get_keymgmt_dh_import(); int ok = 0; if (dh_import != NULL) { DH *dh; /* ctx == provctx */ if ((dh = dh_new(ctx)) != NULL && dh_import(dh, OSSL_KEYMGMT_SELECT_KEYPAIR, params) && dh_pub_pem(ctx, dh, out, cb, cbarg)) ok = 1; dh_free(dh); } return ok; } static int dh_pub_pem(void *ctx, void *dh, BIO *out, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return ossl_prov_write_pub_pem_from_obj(out, dh, EVP_PKEY_DH, ossl_prov_prepare_dh_params, ossl_prov_dh_pub_to_der); } static int dh_pub_print_data(void *ctx, const OSSL_PARAM params[], BIO *out, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { OSSL_OP_keymgmt_new_fn *dh_new = ossl_prov_get_keymgmt_dh_new(); OSSL_OP_keymgmt_free_fn *dh_free = ossl_prov_get_keymgmt_dh_free(); OSSL_OP_keymgmt_import_fn *dh_import = ossl_prov_get_keymgmt_dh_import(); int ok = 0; if (dh_import != NULL) { DH *dh; /* ctx == provctx */ if ((dh = dh_new(ctx)) != NULL && dh_import(dh, OSSL_KEYMGMT_SELECT_KEYPAIR, params) && dh_pub_print(ctx, dh, out, cb, cbarg)) ok = 1; dh_free(dh); } return ok; } static int dh_pub_print(void *ctx, void *dh, BIO *out, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { return ossl_prov_print_dh(out, dh, 0); } const OSSL_DISPATCH dh_pub_der_serializer_functions[] = { { OSSL_FUNC_SERIALIZER_NEWCTX, (void (*)(void))dh_pub_newctx }, { OSSL_FUNC_SERIALIZER_FREECTX, (void (*)(void))dh_pub_freectx }, { OSSL_FUNC_SERIALIZER_SERIALIZE_DATA, (void (*)(void))dh_pub_der_data }, { OSSL_FUNC_SERIALIZER_SERIALIZE_OBJECT, (void (*)(void))dh_pub_der }, { 0, NULL } }; const OSSL_DISPATCH dh_pub_pem_serializer_functions[] = { { OSSL_FUNC_SERIALIZER_NEWCTX, (void (*)(void))dh_pub_newctx }, { OSSL_FUNC_SERIALIZER_FREECTX, (void (*)(void))dh_pub_freectx }, { OSSL_FUNC_SERIALIZER_SERIALIZE_DATA, (void (*)(void))dh_pub_pem_data }, { OSSL_FUNC_SERIALIZER_SERIALIZE_OBJECT, (void (*)(void))dh_pub_pem }, { 0, NULL } }; const OSSL_DISPATCH dh_pub_text_serializer_functions[] = { { OSSL_FUNC_SERIALIZER_NEWCTX, (void (*)(void))dh_pub_newctx }, { OSSL_FUNC_SERIALIZER_FREECTX, (void (*)(void))dh_pub_freectx }, { OSSL_FUNC_SERIALIZER_SERIALIZE_OBJECT, (void (*)(void))dh_pub_print }, { OSSL_FUNC_SERIALIZER_SERIALIZE_DATA, (void (*)(void))dh_pub_print_data }, { 0, NULL } };
dotsimon/openssl
providers/fips/self_test_event.c
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_names.h> #include <openssl/params.h> #include "self_test.h" static void self_test_event_setparams(OSSL_ST_EVENT *ev) { size_t n = 0; if (ev->cb != NULL) { ev->params[n++] = OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_PHASE, (char *)ev->phase, 0); ev->params[n++] = OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_TYPE, (char *)ev->type, 0); ev->params[n++] = OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_DESC, (char *)ev->desc, 0); } ev->params[n++] = OSSL_PARAM_construct_end(); } void SELF_TEST_EVENT_init(OSSL_ST_EVENT *ev, OSSL_CALLBACK *cb, void *cbarg) { if (ev == NULL) return; ev->cb = cb; ev->cb_arg = cbarg; ev->phase = ""; ev->type = ""; ev->desc = ""; self_test_event_setparams(ev); } /* Can be used during application testing to log that a test has started. */ void SELF_TEST_EVENT_onbegin(OSSL_ST_EVENT *ev, const char *type, const char *desc) { if (ev != NULL && ev->cb != NULL) { ev->phase = OSSL_SELF_TEST_PHASE_START; ev->type = type; ev->desc = desc; self_test_event_setparams(ev); (void)ev->cb(ev->params, ev->cb_arg); } } /* * Can be used during application testing to log that a test has either * passed or failed. */ void SELF_TEST_EVENT_onend(OSSL_ST_EVENT *ev, int ret) { if (ev != NULL && ev->cb != NULL) { ev->phase = (ret == 1 ? OSSL_SELF_TEST_PHASE_PASS : OSSL_SELF_TEST_PHASE_FAIL); self_test_event_setparams(ev); (void)ev->cb(ev->params, ev->cb_arg); ev->phase = OSSL_SELF_TEST_PHASE_NONE; ev->type = OSSL_SELF_TEST_TYPE_NONE; ev->desc = OSSL_SELF_TEST_DESC_NONE; } } /* * Used for failure testing. * * Call the applications SELF_TEST_cb() if it exists. * If the application callback decides to return 0 then the first byte of 'bytes' * is modified (corrupted). This is used to modify output signatures or * ciphertext before they are verified or decrypted. */ void SELF_TEST_EVENT_oncorrupt_byte(OSSL_ST_EVENT *ev, unsigned char *bytes) { if (ev != NULL && ev->cb != NULL) { ev->phase = OSSL_SELF_TEST_PHASE_CORRUPT; self_test_event_setparams(ev); if (!ev->cb(ev->params, ev->cb_arg)) bytes[0] ^= 1; } }
dotsimon/openssl
crypto/bio/b_sock.c
<reponame>dotsimon/openssl /* * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include "bio_local.h" #ifndef OPENSSL_NO_SOCK # define SOCKET_PROTOCOL IPPROTO_TCP # ifdef SO_MAXCONN # define MAX_LISTEN SO_MAXCONN # elif defined(SOMAXCONN) # define MAX_LISTEN SOMAXCONN # else # define MAX_LISTEN 32 # endif # if defined(OPENSSL_SYS_WINDOWS) static int wsa_init_done = 0; # endif # ifndef _WIN32 # include <unistd.h> # include <sys/select.h> # else # include <winsock.h> /* for type fd_set */ # endif # ifndef OPENSSL_NO_DEPRECATED_1_1_0 int BIO_get_host_ip(const char *str, unsigned char *ip) { BIO_ADDRINFO *res = NULL; int ret = 0; if (BIO_sock_init() != 1) return 0; /* don't generate another error code here */ if (BIO_lookup(str, NULL, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) { size_t l; if (BIO_ADDRINFO_family(res) != AF_INET) { BIOerr(BIO_F_BIO_GET_HOST_IP, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET); } else if (BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), NULL, &l)) { /* * Because only AF_INET addresses will reach this far, we can assert * that l should be 4 */ if (ossl_assert(l == 4)) ret = BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), ip, &l); } BIO_ADDRINFO_free(res); } else { ERR_add_error_data(2, "host=", str); } return ret; } int BIO_get_port(const char *str, unsigned short *port_ptr) { BIO_ADDRINFO *res = NULL; int ret = 0; if (str == NULL) { BIOerr(BIO_F_BIO_GET_PORT, BIO_R_NO_PORT_DEFINED); return 0; } if (BIO_sock_init() != 1) return 0; /* don't generate another error code here */ if (BIO_lookup(NULL, str, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) { if (BIO_ADDRINFO_family(res) != AF_INET) { BIOerr(BIO_F_BIO_GET_PORT, BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET); } else { *port_ptr = ntohs(BIO_ADDR_rawport(BIO_ADDRINFO_address(res))); ret = 1; } BIO_ADDRINFO_free(res); } else { ERR_add_error_data(2, "host=", str); } return ret; } # endif int BIO_sock_error(int sock) { int j = 0, i; socklen_t size = sizeof(j); /* * Note: under Windows the third parameter is of type (char *) whereas * under other systems it is (void *) if you don't have a cast it will * choke the compiler: if you do have a cast then you can either go for * (char *) or (void *). */ i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, &size); if (i < 0) return get_last_socket_error(); else return j; } # ifndef OPENSSL_NO_DEPRECATED_1_1_0 struct hostent *BIO_gethostbyname(const char *name) { /* * Caching gethostbyname() results forever is wrong, so we have to let * the true gethostbyname() worry about this */ return gethostbyname(name); } # endif int BIO_sock_init(void) { # ifdef OPENSSL_SYS_WINDOWS static struct WSAData wsa_state; if (!wsa_init_done) { wsa_init_done = 1; memset(&wsa_state, 0, sizeof(wsa_state)); /* * Not making wsa_state available to the rest of the code is formally * wrong. But the structures we use are [believed to be] invariable * among Winsock DLLs, while API availability is [expected to be] * probed at run-time with DSO_global_lookup. */ if (WSAStartup(0x0202, &wsa_state) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling wsastartup()"); BIOerr(BIO_F_BIO_SOCK_INIT, BIO_R_WSASTARTUP); return -1; } } # endif /* OPENSSL_SYS_WINDOWS */ # ifdef WATT32 extern int _watt_do_exit; _watt_do_exit = 0; /* don't make sock_init() call exit() */ if (sock_init()) return -1; # endif return 1; } void bio_sock_cleanup_int(void) { # ifdef OPENSSL_SYS_WINDOWS if (wsa_init_done) { wsa_init_done = 0; WSACleanup(); } # endif } int BIO_socket_ioctl(int fd, long type, void *arg) { int i; # ifdef __DJGPP__ i = ioctlsocket(fd, type, (char *)arg); # else # if defined(OPENSSL_SYS_VMS) /*- * 2011-02-18 SMS. * VMS ioctl() can't tolerate a 64-bit "void *arg", but we * observe that all the consumers pass in an "unsigned long *", * so we arrange a local copy with a short pointer, and use * that, instead. */ # if __INITIAL_POINTER_SIZE == 64 # define ARG arg_32p # pragma pointer_size save # pragma pointer_size 32 unsigned long arg_32; unsigned long *arg_32p; # pragma pointer_size restore arg_32p = &arg_32; arg_32 = *((unsigned long *)arg); # else /* __INITIAL_POINTER_SIZE == 64 */ # define ARG arg # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ # else /* defined(OPENSSL_SYS_VMS) */ # define ARG arg # endif /* defined(OPENSSL_SYS_VMS) [else] */ i = ioctlsocket(fd, type, ARG); # endif /* __DJGPP__ */ if (i < 0) ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling ioctlsocket()"); return i; } # ifndef OPENSSL_NO_DEPRECATED_1_1_0 int BIO_get_accept_socket(char *host, int bind_mode) { int s = INVALID_SOCKET; char *h = NULL, *p = NULL; BIO_ADDRINFO *res = NULL; if (!BIO_parse_hostserv(host, &h, &p, BIO_PARSE_PRIO_SERV)) return INVALID_SOCKET; if (BIO_sock_init() != 1) return INVALID_SOCKET; if (BIO_lookup(h, p, BIO_LOOKUP_SERVER, AF_UNSPEC, SOCK_STREAM, &res) != 0) goto err; if ((s = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res), BIO_ADDRINFO_protocol(res), 0)) == INVALID_SOCKET) { s = INVALID_SOCKET; goto err; } if (!BIO_listen(s, BIO_ADDRINFO_address(res), bind_mode ? BIO_SOCK_REUSEADDR : 0)) { BIO_closesocket(s); s = INVALID_SOCKET; } err: BIO_ADDRINFO_free(res); OPENSSL_free(h); OPENSSL_free(p); return s; } int BIO_accept(int sock, char **ip_port) { BIO_ADDR res; int ret = -1; ret = BIO_accept_ex(sock, &res, 0); if (ret == (int)INVALID_SOCKET) { if (BIO_sock_should_retry(ret)) { ret = -2; goto end; } ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling accept()"); BIOerr(BIO_F_BIO_ACCEPT, BIO_R_ACCEPT_ERROR); goto end; } if (ip_port != NULL) { char *host = BIO_ADDR_hostname_string(&res, 1); char *port = BIO_ADDR_service_string(&res, 1); if (host != NULL && port != NULL) *ip_port = OPENSSL_zalloc(strlen(host) + strlen(port) + 2); else *ip_port = NULL; if (*ip_port == NULL) { BIOerr(BIO_F_BIO_ACCEPT, ERR_R_MALLOC_FAILURE); BIO_closesocket(ret); ret = (int)INVALID_SOCKET; } else { strcpy(*ip_port, host); strcat(*ip_port, ":"); strcat(*ip_port, port); } OPENSSL_free(host); OPENSSL_free(port); } end: return ret; } # endif int BIO_set_tcp_ndelay(int s, int on) { int ret = 0; # if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP)) int opt; # ifdef SOL_TCP opt = SOL_TCP; # else # ifdef IPPROTO_TCP opt = IPPROTO_TCP; # endif # endif ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on)); # endif return (ret == 0); } int BIO_socket_nbio(int s, int mode) { int ret = -1; int l; l = mode; # ifdef FIONBIO l = mode; ret = BIO_socket_ioctl(s, FIONBIO, &l); # elif defined(F_GETFL) && defined(F_SETFL) && (defined(O_NONBLOCK) || defined(FNDELAY)) /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */ l = fcntl(s, F_GETFL, 0); if (l == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fcntl()"); ret = -1; } else { # if defined(O_NONBLOCK) l &= ~O_NONBLOCK; # else l &= ~FNDELAY; /* BSD4.x */ # endif if (mode) { # if defined(O_NONBLOCK) l |= O_NONBLOCK; # else l |= FNDELAY; /* BSD4.x */ # endif } ret = fcntl(s, F_SETFL, l); if (ret < 0) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fcntl()"); } } # else /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */ BIOerr(BIO_F_BIO_SOCKET_NBIO, ERR_R_PASSED_INVALID_ARGUMENT); # endif return (ret == 0); } int BIO_sock_info(int sock, enum BIO_sock_info_type type, union BIO_sock_info_u *info) { switch (type) { case BIO_SOCK_INFO_ADDRESS: { socklen_t addr_len; int ret = 0; addr_len = sizeof(*info->addr); ret = getsockname(sock, BIO_ADDR_sockaddr_noconst(info->addr), &addr_len); if (ret == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling getsockname()"); BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_GETSOCKNAME_ERROR); return 0; } if ((size_t)addr_len > sizeof(*info->addr)) { BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS); return 0; } } break; default: BIOerr(BIO_F_BIO_SOCK_INFO, BIO_R_UNKNOWN_INFO_TYPE); return 0; } return 1; } /* TODO simplify by BIO_socket_wait() further other uses of select() in apps/ */ /* * Wait on fd at most until max_time; succeed immediately if max_time == 0. * If for_read == 0 then assume to wait for writing, else wait for reading. * Returns -1 on error, 0 on timeout, and 1 on success. */ int BIO_socket_wait(int fd, int for_read, time_t max_time) { fd_set confds; struct timeval tv; time_t now; if (max_time == 0) return 1; now = time(NULL); if (max_time <= now) return 0; FD_ZERO(&confds); openssl_fdset(fd, &confds); tv.tv_usec = 0; tv.tv_sec = (long)(max_time - now); /* this might overflow */ return select(fd + 1, for_read ? &confds : NULL, for_read ? NULL : &confds, NULL, &tv); } /* * Wait on BIO at most until max_time; succeed immediately if max_time == 0. * Returns -1 on error, 0 on timeout, and 1 on success. */ static int bio_wait(BIO *bio, time_t max_time) { int fd; if (BIO_get_fd(bio, &fd) <= 0) return -1; return BIO_socket_wait(fd, BIO_should_read(bio), max_time); } /* * Wait on BIO at most until max_time; succeed immediately if max_time == 0. * Call BIOerr(...) unless success. * Returns -1 on error, 0 on timeout, and 1 on success. */ int BIO_wait(BIO *bio, time_t max_time) { int rv = bio_wait(bio, max_time); if (rv <= 0) BIOerr(0, rv == 0 ? BIO_R_TRANSFER_TIMEOUT : BIO_R_TRANSFER_ERROR); return rv; } /* * Connect via the given BIO using BIO_do_connect() until success/timeout/error. * Parameter timeout == 0 means infinite, < 0 leads to immediate timeout error. * Returns -1 on error, 0 on timeout, and 1 on success. */ int BIO_connect_retry(BIO *bio, int timeout) { int blocking = timeout == 0; time_t max_time = timeout > 0 ? time(NULL) + timeout : 0; int rv; if (bio == NULL) { BIOerr(0, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (timeout < 0) { BIOerr(0, BIO_R_CONNECT_TIMEOUT); return 0; } if (!blocking) BIO_set_nbio(bio, 1); retry: /* it does not help here to set SSL_MODE_AUTO_RETRY */ rv = BIO_do_connect(bio); /* This indirectly calls ERR_clear_error(); */ if (rv <= 0) { if (get_last_sys_error() == ETIMEDOUT) { /* * if blocking, despite blocking BIO, BIO_do_connect() timed out * when non-blocking, BIO_do_connect() timed out early * with rv == -1 and get_last_sys_error() == 0 */ ERR_clear_error(); (void)BIO_reset(bio); /* * unless using BIO_reset(), blocking next connect() may crash and * non-blocking next BIO_do_connect() will fail */ goto retry; } else if (BIO_should_retry(bio)) { /* will not actually wait if timeout == 0 (i.e., blocking BIO) */ rv = bio_wait(bio, max_time); if (rv > 0) goto retry; BIOerr(0, rv == 0 ? BIO_R_CONNECT_TIMEOUT : BIO_R_CONNECT_ERROR); } else { rv = -1; if (ERR_peek_error() == 0) /* missing error queue entry */ BIOerr(0, BIO_R_CONNECT_ERROR); /* workaround: general error */ } } return rv; } #endif /* !defined(OPENSSL_NO_SOCK) */
dotsimon/openssl
crypto/ec/curve448/curve448_local.h
/* * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_EC_CURVE448_LOCAL_H # define OSSL_CRYPTO_EC_CURVE448_LOCAL_H # include "curve448utils.h" int ED448_sign(OPENSSL_CTX *ctx, uint8_t *out_sig, const uint8_t *message, size_t message_len, const uint8_t public_key[57], const uint8_t private_key[57], const uint8_t *context, size_t context_len); int ED448_verify(OPENSSL_CTX *ctx, const uint8_t *message, size_t message_len, const uint8_t signature[114], const uint8_t public_key[57], const uint8_t *context, size_t context_len); int ED448ph_sign(OPENSSL_CTX *ctx, uint8_t *out_sig, const uint8_t hash[64], const uint8_t public_key[57], const uint8_t private_key[57], const uint8_t *context, size_t context_len); int ED448ph_verify(OPENSSL_CTX *ctx, const uint8_t hash[64], const uint8_t signature[114], const uint8_t public_key[57], const uint8_t *context, size_t context_len); int ED448_public_from_private(OPENSSL_CTX *ctx, uint8_t out_public_key[57], const uint8_t private_key[57]); #endif /* OSSL_CRYPTO_EC_CURVE448_LOCAL_H */
dotsimon/openssl
crypto/self_test_core.c
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/self_test.h> #include "internal/cryptlib.h" typedef struct self_test_cb_st { OSSL_CALLBACK *cb; void *cbarg; } SELF_TEST_CB; static void *self_test_set_callback_new(OPENSSL_CTX *ctx) { SELF_TEST_CB *stcb; stcb = OPENSSL_zalloc(sizeof(*stcb)); return stcb; } static void self_test_set_callback_free(void *stcb) { OPENSSL_free(stcb); } static const OPENSSL_CTX_METHOD self_test_set_callback_method = { self_test_set_callback_new, self_test_set_callback_free, }; static SELF_TEST_CB *get_self_test_callback(OPENSSL_CTX *libctx) { return openssl_ctx_get_data(libctx, OPENSSL_CTX_SELF_TEST_CB_INDEX, &self_test_set_callback_method); } void OSSL_SELF_TEST_set_callback(OPENSSL_CTX *libctx, OSSL_CALLBACK *cb, void *cbarg) { SELF_TEST_CB *stcb = get_self_test_callback(libctx); if (stcb != NULL) { stcb->cb = cb; stcb->cbarg = cbarg; } } void OSSL_SELF_TEST_get_callback(OPENSSL_CTX *libctx, OSSL_CALLBACK **cb, void **cbarg) { SELF_TEST_CB *stcb = get_self_test_callback(libctx); if (cb != NULL) *cb = (stcb != NULL ? stcb->cb : NULL); if (cbarg != NULL) *cbarg = (stcb != NULL ? stcb->cbarg : NULL); }
dotsimon/openssl
providers/fips/self_test.h
/* * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/core_numbers.h> #include <openssl/types.h> #include <openssl/self_test.h> typedef struct self_test_post_params_st { /* FIPS module integrity check parameters */ const char *module_filename; /* Module file to perform MAC on */ const char *module_checksum_data; /* Expected module MAC integrity */ /* Used for KAT install indicator integrity check */ const char *indicator_version; /* version - for future proofing */ const char *indicator_data; /* data to perform MAC on */ const char *indicator_checksum_data; /* Expected MAC integrity value */ /* BIO callbacks supplied to the FIPS provider */ OSSL_BIO_new_file_fn *bio_new_file_cb; OSSL_BIO_new_membuf_fn *bio_new_buffer_cb; OSSL_BIO_read_ex_fn *bio_read_ex_cb; OSSL_BIO_free_fn *bio_free_cb; OSSL_CALLBACK *event_cb; void *event_cb_arg; OPENSSL_CTX *libctx; } SELF_TEST_POST_PARAMS; typedef struct st_event_st { /* local state variables */ const char *phase; const char *type; const char *desc; OSSL_CALLBACK *cb; /* callback related variables used to pass the state back to the user */ OSSL_PARAM params[4]; void *cb_arg; } OSSL_ST_EVENT; int SELF_TEST_post(SELF_TEST_POST_PARAMS *st, int on_demand_test); int SELF_TEST_kats(OSSL_ST_EVENT *event, OPENSSL_CTX *libctx); void SELF_TEST_EVENT_init(OSSL_ST_EVENT *ev, OSSL_CALLBACK *cb, void *cbarg); void SELF_TEST_EVENT_onbegin(OSSL_ST_EVENT *ev, const char *type, const char *desc); void SELF_TEST_EVENT_onend(OSSL_ST_EVENT *ev, int ret); void SELF_TEST_EVENT_oncorrupt_byte(OSSL_ST_EVENT *ev, unsigned char *bytes);
hervey-su/home
notebook/demo/src/funs.c
<filename>notebook/demo/src/funs.c #include "funs.h" // x[0]*x[1]*...*x[n-1] double dprod(double *x, int n) { double y = 1.0; for (int i = 0; i < n; i++) { y *= x[i]; } return y; } // The factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n. // For example,5!=5*4*3*2*1=120 // The value of 0! is 1 int factorial(int n) { if (n ==0 ) { return 1; } else { return n * factorial(n - 1); } }
hervey-su/home
notebook/demo/src/SumArray.h
#ifndef SUMARRAY_H #define SUMARRAY_H int sum(int array[], int size); #endif
hervey-su/home
notebook/demo/src/hello.c
<filename>notebook/demo/src/hello.c<gh_stars>1-10 /* gcc -o hello hello.c */ #include <stdio.h> int main() { printf("Hello, world!\n"); return 0; }
southmountain/CrossScalePatchMatch
CSPM/ca_filter/GuidedFilter.h
#pragma once #include "..\CommFunc.h" // to use fast inverse method #define FAST_INV // cum sum like cumsum in matlab Mat CumSum( const Mat& src, const int d ); // % BOXFILTER O(1) time box filtering using cumulative sum // % // % - Definition imDst(x, y)=sum(sum(imSrc(x-r:x+r,y-r:y+r))); // % - Running time independent of r; // % - Equivalent to the function: colfilt(imSrc, [2*r+1, 2*r+1], 'sliding', @sum); // % - But much faster. Mat BoxFilter( const Mat& imSrc, const int r = 9 ); // % GUIDEDFILTER O(1) time implementation of guided filter. // % // % - guidance image: I (should be a gray-scale/single channel image) // % - filtering input image: p (should be a gray-scale/single channel image) // % - local window radius: r // % - regularization parameter: eps Mat GuidedFilter( const Mat& I, const Mat& p, const int r = 9, const float eps = 0.0001 );
southmountain/CrossScalePatchMatch
CSPM/get_method.h
<reponame>southmountain/CrossScalePatchMatch<filename>CSPM/get_method.h /////////////////////////////////////////////////////// // File: GetMethod // Desc: Get all the method interface by name // // Author: <NAME> // Date: 2013/09/06 /////////////////////////////////////////////////////// #pragma once #include "CC/GrdCC.h" #include "CC/CenCC.h" #include "CC/CGCC.h" #include "CAFilter/GFCA.h" #include "CAFilter/BFCA.h" #include "CAFilter/BoxCA.h" #include "CANLC/NLCCA.h" #include "CAST/STCA.h" #include "PPWM/WMPP.h" #include "PPSG/SGPP.h" // get cost compuation method name CCMethod* getCCType(const string name) { if (name == "GRD") { return new GrdCC(); } else if (name == "CEN") { return new CenCC(); } else if (name == "BSM") { return NULL; } else if (name == "CG") { return new CGCC(); } } // get cost aggregation method name CAMethod* getCAType(const string name) { if (name == "GF") { return new GFCA(); } else if (name == "BF") { return new BFCA(); } else if (name == "BOX") { return new BoxCA(); } else if (name == "NL") { return new NLCCA(); } else if (name == "ST") { return new STCA(); } } // get cost compuation method name PPMethod* getPPType(const string name) { if (name == "SG") { return new SGPP(); } else if (name == "WM") { return new WMPP(); } else if (name == "NP") { return NULL; } }
southmountain/CrossScalePatchMatch
CSPM/plane_cost/pre_cs_pc.h
/////////////////////////////////////////////////////// // File: pre_cs_pc.h // Desc: precompute cost volume // for cross-scale plane cost // // Author: rookiepig // Date: 2014/05/19 // /////////////////////////////////////////////////////// #pragma once #include"../commfunc.h" #include"i_plane_cost.h" #include"../cc_method.h" // 10 * 3 = 30 means divide color by 3 #define WGT_GAMMA 10.0 // #define REG_LAMBDA 1 class PreCSPC : public IPlaneCost { public: PreCSPC(const Mat& l_img, const Mat& r_img, const int& max_disp, const int& wnd_size, const int& scale_num, CCMethod* cc_method, const double& reg_lambda); //const double& alpha, //const double& tau_clr, const double& tau_grd, //const double& gamma); ~PreCSPC(void); virtual double GetPlaneCost( const int& ref_x, const int& ref_y, const Plane& plane, const RefView& view ) const; private: double GetCostWeight(const int& ref_x, const int& ref_y, const int& q_x, const int& q_y, const RefView& view, const int& scale) const; double GetPixelCost(const int& ref_x, const int& ref_y, const double& other_x, const int& other_y, const RefView& view, const int& scale) const; // multi-scale related int scale_num_; double* scale_wgt_; // color image Mat* img_[kViewNum]; // cost volume Mat** cost_vol_[kViewNum]; double* max_cost_[kViewNum]; // image property int* wid_; int* hei_; // look up table for fast-exp double* lookup_exp_; // method paramter int* max_disp_; int wnd_size_; int half_wnd_; //double alpha_; // balance color and gradient cost //double tau_clr_; // threshold for color cost //double tau_grd_; // threshold for gradient cost //double gamma_; // cost weight parameter };
southmountain/CrossScalePatchMatch
CSPM/plane_cost/grd_pc.h
<filename>CSPM/plane_cost/grd_pc.h /////////////////////////////////////////////////////// // File: grd_pc.h // Desc: gradient + color plane cost // // Author: rookiepig // Date: 2014/04/03 // /////////////////////////////////////////////////////// #pragma once #include"../commfunc.h" #include"i_plane_cost.h" #define COST_ALPHA 0.1 #define TAU_CLR 10.0 #define TAU_GRD 2.0 // 10 * 3 = 30 means divide color by 3 #define WGT_GAMMA 10.0 // #define USE_BORDER //#define USE_INTER #ifdef USE_INTER #define INTER_SIZE 10.0 #endif // #define INV_DISP_COST_SCALE 10000 // #define USE_LAB_WGT class GrdPC : public IPlaneCost { public: GrdPC(const Mat& l_img, const Mat& r_img, const int& max_disp, const int& wnd_size); //const double& alpha, //const double& tau_clr, const double& tau_grd, //const double& gamma); ~GrdPC(void); virtual double GetPlaneCost( const int& ref_x, const int& ref_y, const Plane& plane, const RefView& view ) const; private: double GetCostWeight(const int& ref_x, const int& ref_y, const int& q_x, const int& q_y, const RefView& view) const; double GetPixelCost(const int& ref_x, const int& ref_y, const double& other_x, const int& other_y, const RefView& view) const; // color image Mat img_[kViewNum]; Mat lab_[kViewNum]; // gradient along x axis Mat grd_x_[kViewNum]; #ifdef USE_INTER Mat inter_img_[kViewNum]; // interpolated image Mat inter_grd_x_[kViewNum]; // interpolated gradient int inter_wid_; #endif // image property int wid_; int hei_; // look up table for fast-exp double* lookup_exp_; // method paramter int max_disp_; int wnd_size_; int half_wnd_; //double alpha_; // balance color and gradient cost //double tau_clr_; // threshold for color cost //double tau_grd_; // threshold for gradient cost //double gamma_; // cost weight parameter };
southmountain/CrossScalePatchMatch
CSPM/cc_method.h
/////////////////////////////////////////////////////// // File: cc_method.h // Desc: Interface for Cost Computation // // Author: rookiepig // Date: 2014/05/16 // /////////////////////////////////////////////////////// #pragma once #include "commfunc.h" // // Interface for Cost Computation // class CCMethod { public: CCMethod(void) {} virtual ~CCMethod(void) {} public: /////////////////////////////////////////////////////// // Func: buildCV // Desc: build cost volume // In: // const Mat& lImg - left color image // const Mat& rImg - right color image // const int maxDis - maxDis // Out: // Mat* costVol - out put cost volume /////////////////////////////////////////////////////// virtual void buildCV( const Mat& lImg, const Mat& rImg, const int maxDis, Mat* costVol ) = 0; virtual void buildRightCV( const Mat& lImg, const Mat& rImg, const int maxDis, Mat* rCostVol ) = 0; };
southmountain/CrossScalePatchMatch
CSPM/plane_cost/pre_ss_pc.h
/////////////////////////////////////////////////////// // File: pre_ss_pc.h // Desc: precompute cost volume // for single-scale plane cost // // Author: rookiepig // Date: 2014/05/19 // /////////////////////////////////////////////////////// #pragma once #include"../commfunc.h" #include"i_plane_cost.h" #include"../cc_method.h" // 10 * 3 = 30 means divide color by 3 #define WGT_GAMMA 10.0 class PreSSPC : public IPlaneCost { public: PreSSPC(const Mat& l_img, const Mat& r_img, const int& max_disp, const int& wnd_size, CCMethod* cc_method); //const double& alpha, //const double& tau_clr, const double& tau_grd, //const double& gamma); ~PreSSPC(void); virtual double GetPlaneCost( const int& ref_x, const int& ref_y, const Plane& plane, const RefView& view ) const; private: // color image Mat img_[kViewNum]; // cost volume Mat* cost_vol_[kViewNum]; double max_cost_[kViewNum]; // image property int wid_; int hei_; // look up table for fast-exp double* lookup_exp_; // method paramter int max_disp_; int wnd_size_; int half_wnd_; //double alpha_; // balance color and gradient cost //double tau_clr_; // threshold for color cost //double tau_grd_; // threshold for gradient cost //double gamma_; // cost weight parameter };
southmountain/CrossScalePatchMatch
CSPM/commfunc.h
<filename>CSPM/commfunc.h /////////////////////////////////////////////////////// // File: commfunc.h // Desc: global functions, constants and headers // // Author: <NAME> // Date: 2013/09/06 /////////////////////////////////////////////////////// #pragma once #include<opencv2/opencv.hpp> #include<string> #include<iostream> #include<iomanip> #include<algorithm> #include<limits> #include<cstdlib> #include<gflags/gflags.h> #include<omp.h> #include<bitset> // C Header #include"ctmf.h" using namespace std; using namespace cv; const int kViewNum = 2; // not use too small eps to avoid overflow const double kDoubleEps = 0.00000001; const double kDoubleMax = numeric_limits<double>::max(); enum RefView{ kLeft = 0, kRight = 1 }; #pragma comment(lib, "ShLwapi.lib") // // gflags lib // #ifdef _DEBUG #pragma comment(lib, "gflags_debug.lib") #else #pragma comment(lib, "gflags.lib") #endif // // Opencv Lib 2.4.6 // #ifdef _DEBUG #pragma comment( lib, "opencv_calib3d248d.lib" ) #pragma comment( lib, "opencv_contrib248d.lib" ) #pragma comment( lib, "opencv_core248d.lib" ) #pragma comment( lib, "opencv_features2d248d.lib" ) #pragma comment( lib, "opencv_flann248d.lib" ) #pragma comment( lib, "opencv_gpu248d.lib" ) #pragma comment( lib, "opencv_highgui248d.lib" ) #pragma comment( lib, "opencv_imgproc248d.lib" ) #pragma comment( lib, "opencv_legacy248d.lib" ) #pragma comment( lib, "opencv_ml248d.lib" ) #pragma comment( lib, "opencv_nonfree248d.lib" ) #pragma comment( lib, "opencv_objdetect248d.lib" ) #pragma comment( lib, "opencv_photo248d.lib" ) #pragma comment( lib, "opencv_stitching248d.lib" ) #pragma comment( lib, "opencv_superres248d.lib" ) #pragma comment( lib, "opencv_ts248d.lib" ) #pragma comment( lib, "opencv_video248d.lib" ) #pragma comment( lib, "opencv_videostab248d.lib" ) #else #pragma comment( lib, "opencv_calib3d248.lib" ) #pragma comment( lib, "opencv_contrib248.lib" ) #pragma comment( lib, "opencv_core248.lib" ) #pragma comment( lib, "opencv_features2d248.lib" ) #pragma comment( lib, "opencv_flann248.lib" ) #pragma comment( lib, "opencv_gpu248.lib" ) #pragma comment( lib, "opencv_highgui248.lib" ) #pragma comment( lib, "opencv_imgproc248.lib" ) #pragma comment( lib, "opencv_legacy248.lib" ) #pragma comment( lib, "opencv_ml248.lib" ) #pragma comment( lib, "opencv_nonfree248.lib" ) #pragma comment( lib, "opencv_objdetect248.lib" ) #pragma comment( lib, "opencv_photo248.lib" ) #pragma comment( lib, "opencv_stitching248.lib" ) #pragma comment( lib, "opencv_superres248.lib" ) #pragma comment( lib, "opencv_ts248.lib" ) #pragma comment( lib, "opencv_video248.lib" ) #pragma comment( lib, "opencv_videostab248.lib" ) #endif // // Global Functions // // output matrix template<class T> void PrintMat(const Mat& mat) { int rows = mat.rows; int cols = mat.cols; printf("\n%d x %d Matrix\n", rows, cols); for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { cout << mat.at<T>(r, c) << "\t"; } printf("\n"); } printf("\n"); } // fast float floor to int inline int Floor2Int(double d) { // minus -0.5 to floor const double dme = .5f - 1.5e-8; d -= dme; // magic number d = d + 6755399441055744.0; return ((int*)&d)[0]; // 0 for little endian, 1 for big endian } // fast float rount to int inline int Round2Int(double d) { // magic number d = d + 6755399441055744.0; return ((int*)&d)[0]; // 0 for little endian, 1 for big endian } inline double FastFabs(double x) { int tmp = (int&)x & 0x7FFFFFFFFFFFFFFF; return (double&)tmp; } // handle image border inline int HandleBorder(const int& loc, const int& size) { //if (loc < 0 || loc >= size) { // // mod too slow !!! // return ( loc + size ) % size; //} if (loc < 0) { // CV_Assert(loc + size >= 0); return loc + size; // return 0; } if (loc >= size) { // CV_Assert(loc - size < size); return loc - size; // return size - 1; } return loc; } // handle image border macro //#define HANDLE_BORDER(loc, size) \ // ((loc) < 0 ? (loc)+(size) : \ // ((loc) >= (size) ? (loc)-(size) : (loc))) // // constant time median filter //inline void MedianFilter(cv::InputArray iImage_, cv::OutputArray oImage_, int r) { // cv::Mat iImage = iImage_.getMat(); // cv::Size imageSize = iImage.size(); // CV_Assert(iImage.depth() == CV_8U); // // cv::Mat tmp(imageSize, iImage.type()); // ctmf(iImage.data, tmp.data, imageSize.width, imageSize.height, // iImage.step1(), tmp.step1(), r, // iImage.channels(), imageSize.area() * iImage.channels()); // // if (oImage_.getMat().size() != imageSize || oImage_.getMat().depth() != CV_8U || oImage_.getMat().type() != CV_8UC1) { // oImage_.create(imageSize, iImage.type()); // } // tmp.copyTo(oImage_.getMat()); //} // #define MY_DEBUG #define USE_OMP
southmountain/CrossScalePatchMatch
CSPM/plane.h
<filename>CSPM/plane.h<gh_stars>10-100 /////////////////////////////////////////////////////// // File: Plane.h // Desc: Simple plane class to record plane param for // for each pixel // // Author: rookiepig // Date: 2014/04/01 /////////////////////////////////////////////////////// #pragma once #include"commfunc.h" class Plane { public: Plane() : norm_(0, 0, 0), point_(0, 0, 0), param_(0, 0, 0 ) {} Plane(const Vec3d& norm, const Point3d& point) : norm_(norm), point_(point) { update_param(); } void set_point(const Point3d& point) { point_ = point; } void set_norm(const Point3d& norm) { norm_ = norm; } inline void update_param() { // avoid deivde 0 double denom = max(fabs(norm_[2]), kDoubleEps); if (norm_[2] < 0.0) { denom = -denom; } param_[0] = -norm_[0] / denom; param_[1] = -norm_[1] / denom; param_[2] = norm_.dot(point_) / denom; } Vec3d norm() const { return norm_; } Point3d point() const { return point_; } Vec3d param() const { return param_; } private: Vec3d norm_; Point3d point_; Vec3d param_; };
southmountain/CrossScalePatchMatch
CSPM/plane_cost/i_plane_cost.h
/////////////////////////////////////////////////////// // File: i_plane_cost.h // Desc: interface for calculating plane cost // // Author: rookiepig // Date: 2014/04/02 // /////////////////////////////////////////////////////// #pragma once #include"../commfunc.h" #include"../plane.h" class IPlaneCost { public: IPlaneCost(void) {} virtual ~IPlaneCost(void) {} /////////////////////////////////////////////////////// // Func: GetPlaneCost // Desc: get aggregated cost with plane pramater // In: // const int& ref_x - reference pixel location // const int& ref_y - reference pixel location // const Plane& plane - plane paramter // const RefView& view - enum to decide current view // Out: // double - aggregated cost /////////////////////////////////////////////////////// virtual double GetPlaneCost( const int& ref_x, const int& ref_y, const Plane& plane, const RefView& view ) const = 0; };
southmountain/CrossScalePatchMatch
CSPM/ca_method.h
<reponame>southmountain/CrossScalePatchMatch #pragma once #include "commfunc.h" // // Interface for Cost Aggregtation // class CAMethod { public: CAMethod(void) {} virtual ~CAMethod(void) {} public: /////////////////////////////////////////////////////// // Func: aggreCV // Desc: aggregate cost volume // In: // const Mat& lImg - left color image // const Mat& rImg - right color image // const int maxDis - maxDis // Out: // Mat* costVol - out put cost volume /////////////////////////////////////////////////////// virtual void aggreCV( const Mat& lImg, const Mat& rImg, const int maxDis, Mat* costVol ) = 0; };
southmountain/CrossScalePatchMatch
CSPM/plane_cost/cspc.h
<gh_stars>10-100 /////////////////////////////////////////////////////// // File: cspc.h // Desc: corss scale cost aggregation // // Author: rookiepig // Date: 2014/04/03 // /////////////////////////////////////////////////////// #pragma once #include"../commfunc.h" #include"i_plane_cost.h" #define COST_ALPHA 0.1 #define TAU_CLR 10.0 #define TAU_GRD 2.0 // 10 * 3 = 30 means divide color by 3 #define WGT_GAMMA 10.0 //#define REG_LAMBDA 1 class CSPC : public IPlaneCost { public: CSPC(const Mat& l_img, const Mat& r_img, const int& max_disp, const int& wnd_size, const int& scale_num, const double& reg_lambda); //const double& alpha, //const double& tau_clr, const double& tau_grd, //const double& gamma); ~CSPC(void); virtual double GetPlaneCost( const int& ref_x, const int& ref_y, const Plane& plane, const RefView& view ) const; private: double GetCostWeight(const int& ref_x, const int& ref_y, const int& q_x, const int& q_y, const RefView& view, const int& scale) const; double GetPixelCost(const int& ref_x, const int& ref_y, const double& other_x, const int& other_y, const RefView& view, const int& scale) const; // multi-scale related int scale_num_; double* scale_wgt_; // color image Mat* img_[kViewNum]; Mat* lab_[kViewNum]; // gradient along x axis Mat* grd_x_[kViewNum]; // image property int* wid_; int* hei_; // look up table for fast-exp double* lookup_exp_; // method paramter int* max_disp_; int wnd_size_; int half_wnd_; //double alpha_; // balance color and gradient cost //double tau_clr_; // threshold for color cost //double tau_grd_; // threshold for gradient cost //double gamma_; // cost weight parameter };
voohoo2000/chadwm
chadwm/config.def.h
/* See LICENSE file for copyright and license details. */ #define XF86XK_MonBrightnessDown 0x1008ff03 #define XF86XK_MonBrightnessUp 0x1008ff02 #define XF86XK_AudioLowerVolume 0x1008FF11 #define XF86XK_AudioMute 0x1008FF12 #define XF86XK_AudioRaiseVolume 0x1008FF13 #define XF86XK_AudioMicMute 0x1008FFB2 /* appearance */ static const unsigned int borderpx = 0; /* border pixel of windows */ static const unsigned int default_border = 0; // to switch back to default border after dynamic border resizing via keybinds static const unsigned int snap = 32; /* snap pixel */ static const unsigned int gappih = 10; /* horiz inner gap between windows */ static const unsigned int gappiv = 10; /* vert inner gap between windows */ static const unsigned int gappoh = 10; /* horiz outer gap between windows and screen edge */ static const unsigned int gappov = 10; /* vert outer gap between windows and screen edge */ static int smartgaps = 0; /* 1 means no outer gap when there is only one window */ static const unsigned int systraypinning = 0; /* 0: sloppy systray follows selected monitor, >0: pin systray to monitor X */ static const unsigned int systrayspacing = 2; /* systray spacing */ static const int systraypinningfailfirst = 1; /* 1: if pinning fails,display systray on the 1st monitor,False: display systray on last monitor*/ static const int showsystray = 1; /* 0 means no systray */ static const int showbar = 1; /* 0 means no bar */ enum showtab_modes { showtab_never, showtab_auto, showtab_nmodes, showtab_always }; static const int showtab = showtab_auto; static const int toptab = True; static const int topbar = 1; /* 0 means bottom bar */ static const int horizpadbar = 5; static const int vertpadbar = 11; static const int vertpadtab = 33; static const int horizpadtabi = 15; static const int horizpadtabo = 15; static const int scalepreview = 4; static int tag_preview = 0; /* 1 means enable, 0 is off */ static const char *fonts[] = { "JetBrainsMono Nerd Font:style:medium:size=10", "Material Design Icons-Regular:size=10", }; static const int colorfultag = 1; /* 0 means use SchemeSel for selected non vacant tag */ // theme #include "themes/onedark.h" static const char *colors[][3] = { /* fg bg border */ [SchemeNorm] = { gray3, black, gray2 }, [SchemeSel] = { gray4, blue, blue }, [TabSel] = { blue, gray2, black }, [TabNorm] = { gray3, black, black }, [SchemeTag] = { gray3, black, black }, [SchemeTag1] = { blue, black, black }, [SchemeTag2] = { red, black, black }, [SchemeTag3] = { orange, black,black }, [SchemeTag4] = { green, black, black }, [SchemeTag5] = { pink, black, black }, [SchemeLayout] = { green, black, black }, [SchemeBtnPrev] = { green, black, black }, [SchemeBtnNext] = { yellow, black, black }, [SchemeBtnClose] = { red, black, black }, }; /* tagging */ static char *tags[] = {"", "", "", "", ""}; static const char* eww[] = { "eww", "open" , "eww", NULL }; static const Launcher launchers[] = { /* command name to display */ { eww, "" }, }; static const int tagschemes[] = { SchemeTag1, SchemeTag2, SchemeTag3, SchemeTag4, SchemeTag5 }; static const unsigned int ulinepad = 5; /* horizontal padding between the underline and tag */ static const unsigned int ulinestroke = 2; /* thickness / height of the underline */ static const unsigned int ulinevoffset = 0; /* how far above the bottom of the bar the line should appear */ static const int ulineall = 0; /* 1 to show underline on all tags, 0 for just the active ones */ static const Rule rules[] = { /* xprop(1): * WM_CLASS(STRING) = instance, class * WM_NAME(STRING) = title */ /* class instance title tags mask iscentered isfloating monitor */ { "eww", NULL, NULL, 0, 0, 1, -1 }, { "wemeetapp",NULL, NULL, 0, 1, 1, -1 }, }; /* layout(s) */ static const float mfact = 0.50; /* factor of master area size [0.05..0.95] */ static const int nmaster = 1; /* number of clients in master area */ static const int resizehints = 0; /* 1 means respect size hints in tiled resizals */ static const int lockfullscreen = 1; /* 1 will force focus on the fullscreen window */ #define FORCE_VSPLIT 1 /* nrowgrid layout: force two clients to always split vertically */ #include "functions.h" static const Layout layouts[] = { /* symbol arrange function */ { "[]=", tile }, /* first entry is default */ { "[M]", monocle }, { "[@]", spiral }, { "[\\]", dwindle }, { "H[]", deck }, { "TTT", bstack }, { "===", bstackhoriz }, { "HHH", grid }, { "###", nrowgrid }, { "---", horizgrid }, { ":::", gaplessgrid }, { "|M|", centeredmaster }, { ">M>", centeredfloatingmaster }, { "><>", NULL }, /* no layout function means floating behavior */ }; /* key definitions */ #define MODKEY Mod4Mask #define TAGKEYS(KEY,TAG) \ { MODKEY, KEY, view, {.ui = 1 << TAG} }, \ { MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \ { MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \ { MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} }, /* helper for spawning shell commands in the pre dwm-5.0 fashion */ #define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } } /* commands */ static const char *term[] = {"alacritty", NULL }; static const char *rofi[] = {"rofi", "-show", "drun", NULL }; static const char *xi[] = {"xbacklight", "-inc", "7", NULL}; static const char *xd[] = {"xbacklight", "-dec", "7", NULL}; static const char *mutevol[] = { "pactl", "set-sink-mute", "0", "toggle", NULL }; static const char *upvol[] = { "pactl", "set-sink-volume", "0", "+5%", NULL }; static const char *downvol[] = { "pactl", "set-sink-volume", "0", "-5%", NULL }; static const char *micmute[] = { "pactl", "set-source-mute", "1", "toggle", NULL }; static const char *suspend[] = {"systemctl", "suspend", NULL, NULL }; static const char *hibernate[] = {"systemctl", "hibernate", NULL, NULL }; static const char *shutdown[] = {"shutdown", "now", NULL, NULL }; static Key keys[] = { /* modifier key function argument */ { MODKEY, XK_c, spawn, {.v = rofi } }, { MODKEY, XK_Return, spawn, {.v = term }}, // { MODKEY, XK_Return, spawn, SHCMD("st_pad && st")}, {MODKEY | ControlMask, XK_u, spawn, SHCMD("maim | xclip -selection clipboard -t image/png")}, {MODKEY, XK_u, spawn, SHCMD("maim --select | xclip -selection clipboard -t image/png")}, {0, XF86XK_MonBrightnessDown, spawn, {.v = xd}}, {0, XF86XK_MonBrightnessUp, spawn, {.v = xi}}, {0, XF86XK_AudioMute, spawn, {.v = mutevol}}, {0, XF86XK_AudioLowerVolume, spawn, {.v = downvol}}, {0, XF86XK_AudioRaiseVolume, spawn, {.v = upvol}}, {0, XF86XK_AudioMicMute, spawn, {.v = micmute}}, { MODKEY|ControlMask|ShiftMask, XK_s, spawn, {.v = suspend } }, { MODKEY|ControlMask|ShiftMask, XK_h, spawn, {.v = hibernate } }, { MODKEY|ControlMask|ShiftMask, XK_d, spawn, {.v = shutdown } }, { MODKEY, XK_b, togglebar, {0} }, { MODKEY|ControlMask, XK_w, tabmode, { -1 } }, { MODKEY, XK_j, focusstack, {.i = +1 } }, { MODKEY, XK_k, focusstack, {.i = -1 } }, { MODKEY, XK_i, incnmaster, {.i = +1 } }, { MODKEY, XK_d, incnmaster, {.i = -1 } }, { MODKEY, XK_h, setmfact, {.f = -0.05} }, { MODKEY, XK_l, setmfact, {.f = +0.05} }, { MODKEY|ShiftMask, XK_h, setcfact, {.f = +0.25} }, { MODKEY|ShiftMask, XK_l, setcfact, {.f = -0.25} }, { MODKEY|ShiftMask, XK_o, setcfact, {.f = 0.00} }, { MODKEY|ShiftMask, XK_j, movestack, {.i = +1 } }, { MODKEY|ShiftMask, XK_k, movestack, {.i = -1 } }, { MODKEY, XK_Return, zoom, {0} }, { MODKEY, XK_Tab, view, {0} }, // overall gaps { MODKEY|ControlMask, XK_i, incrgaps, {.i = +1 } }, { MODKEY|ControlMask, XK_d, incrgaps, {.i = -1 } }, // inner gaps { MODKEY|ShiftMask, XK_i, incrigaps, {.i = +1 } }, { MODKEY|ControlMask|ShiftMask, XK_i, incrigaps, {.i = -1 } }, // outer gaps { MODKEY|ControlMask, XK_o, incrogaps, {.i = +1 } }, { MODKEY|ControlMask|ShiftMask, XK_o, incrogaps, {.i = -1 } }, { MODKEY|ControlMask, XK_6, incrihgaps, {.i = +1 } }, { MODKEY|ControlMask|ShiftMask, XK_6, incrihgaps, {.i = -1 } }, { MODKEY|ControlMask, XK_7, incrivgaps, {.i = +1 } }, { MODKEY|ControlMask|ShiftMask, XK_7, incrivgaps, {.i = -1 } }, { MODKEY|ControlMask, XK_8, incrohgaps, {.i = +1 } }, { MODKEY|ControlMask|ShiftMask, XK_8, incrohgaps, {.i = -1 } }, { MODKEY|ControlMask, XK_9, incrovgaps, {.i = +1 } }, { MODKEY|ControlMask|ShiftMask, XK_9, incrovgaps, {.i = -1 } }, { MODKEY|ControlMask, XK_t, togglegaps, {0} }, { MODKEY|ControlMask|ShiftMask, XK_d, defaultgaps, {0} }, { MODKEY, XK_q, killclient, {0} }, { MODKEY, XK_t, setlayout, {.v = &layouts[0]} }, { MODKEY|ShiftMask, XK_f, setlayout, {.v = &layouts[1]} }, { MODKEY, XK_m, setlayout, {.v = &layouts[2]} }, { MODKEY|ControlMask, XK_g, setlayout, {.v = &layouts[10]} }, { MODKEY|ControlMask|ShiftMask, XK_t, setlayout, {.v = &layouts[13]} }, { MODKEY, XK_space, setlayout, {0} }, { MODKEY|ControlMask, XK_comma, cyclelayout, {.i = -1 } }, { MODKEY|ControlMask, XK_period, cyclelayout, {.i = +1 } }, { MODKEY|ShiftMask, XK_space, togglefloating, {0} }, { MODKEY, XK_f, togglefullscr, {0} }, { MODKEY, XK_0, view, {.ui = ~0 } }, { MODKEY|ShiftMask, XK_0, tag, {.ui = ~0 } }, { MODKEY, XK_comma, focusmon, {.i = -1 } }, { MODKEY, XK_period, focusmon, {.i = +1 } }, { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } }, { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } }, { MODKEY|ShiftMask, XK_minus, setborderpx, {.i = -1 } }, { MODKEY|ShiftMask, XK_p, setborderpx, {.i = +1 } }, { MODKEY|ShiftMask, XK_w, setborderpx, {.i = default_border } }, TAGKEYS( XK_1, 0) TAGKEYS( XK_2, 1) TAGKEYS( XK_3, 2) TAGKEYS( XK_4, 3) TAGKEYS( XK_5, 4) TAGKEYS( XK_6, 5) TAGKEYS( XK_7, 6) TAGKEYS( XK_8, 7) TAGKEYS( XK_9, 8) { MODKEY|ControlMask, XK_q, quit, {0} }, { MODKEY|ShiftMask, XK_r, quit, {1} }, { MODKEY, XK_e, hidewin, {0} }, { MODKEY|ShiftMask, XK_e, restorewin, {0} }, }; /* button definitions */ /* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */ static Button buttons[] = { /* click event mask button function argument */ { ClkLtSymbol, 0, Button1, setlayout, {0} }, { ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]} }, { ClkWinTitle, 0, Button2, zoom, {0} }, { ClkStatusText, 0, Button2, spawn, {.v = term } }, /* Keep movemouse? */ /* { ClkClientWin, MODKEY, Button1, movemouse, {0} }, */ /* placemouse options, choose which feels more natural: * 0 - tiled position is relative to mouse cursor * 1 - tiled postiion is relative to window center * 2 - mouse pointer warps to window center * * The moveorplace uses movemouse or placemouse depending on the floating state * of the selected client. Set up individual keybindings for the two if you want * to control these separately (i.e. to retain the feature to move a tiled window * into a floating position). */ { ClkClientWin, MODKEY, Button1, moveorplace, {.i = 0} }, { ClkClientWin, MODKEY, Button2, togglefloating, {0} }, { ClkClientWin, MODKEY, Button3, resizemouse, {0} }, { ClkClientWin, ControlMask, Button1, dragmfact, {0} }, { ClkClientWin, ControlMask, Button3, dragcfact, {0} }, { ClkTagBar, 0, Button1, view, {0} }, { ClkTagBar, 0, Button3, toggleview, {0} }, { ClkTagBar, MODKEY, Button1, tag, {0} }, { ClkTagBar, MODKEY, Button3, toggletag, {0} }, { ClkTabBar, 0, Button1, focuswin, {0} }, { ClkTabBar, 0, Button1, focuswin, {0} }, { ClkTabPrev, 0, Button1, movestack, { .i = -1 } }, { ClkTabNext, 0, Button1, movestack, { .i = +1 } }, { ClkTabClose, 0, Button1, killclient, {0} }, };
IT1050-2022-Feb/tutorial-01-IT21289484
Tute04.c
<filename>Tute04.c /*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int max(int no1,int no2); int min(int no1,int no2); int mul(int no1,int no2); int main() { int no1, no2, maximum, minimum, multiple; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); maximum = max(no1,no2); minimum = min(no1,no2); multiple =mul(no1,no2); printf("%d ", min(no1, no2)); printf("%d ", max(no1, no2)); printf("%d ", mul(no1, no2)); return 0; } int max(int no1,int no2) { if(no1 > no2) return no1; else return no2; } int min(int no1,int no2) { if(no1 < no2) return no1; else return no2; } int mul(int no1,int no2) { return no1 * no2; }
jtk33/Vulkan
include/gf3d_texture.h
<filename>include/gf3d_texture.h<gh_stars>0 #ifndef __GF3D_TEXTURE_H__ #define __GF3D_TEXTURE_H__ #include <vulkan/vulkan.h> #include "gfc_types.h" #include "gfc_text.h" typedef struct { Uint8 _inuse; Uint32 _refcount; Uint32 width, height; TextLine filename; VkImage textureImage; VkDeviceMemory textureImageMemory; VkImageView textureImageView; VkSampler textureSampler; }Texture; void gf3d_texture_init(Uint32 max_textures); Texture *gf3d_texture_load(char *filename); void gf3d_texture_free(Texture *tex); #endif
jtk33/Vulkan
src/gf3d_enemy.c
#include "simple_logger.h" #include "gf3d_enemy.h" #include "gf3d_player.h" #include "SDL_keycode.h" #include "SDL_events.h" typedef struct { float speed; /**It's a mystery what this one does*/ float jumpheight; /**Self explanatory, again, have fun*/ float gravity; /**Enemy gravity.*/ enum state hostile; /**Is the enemy hostile?*/ float vel; }Enemy; Enemy enemy; const Uint8 * keys; Entity *ent[10] = { 0 }; Vector2D shoot; void gf3d_enemy_init() { keys = SDL_GetKeyboardState(NULL); enemy.gravity = 0.00001; enemy.hostile = no; ent[0] = gf3d_entity_new(); ent[0]->model = gf3d_model_load("detectorr"); gfc_matrix_make_translation( ent[0]->modelMatrix, vector3d(-500, -500, 0)); } void gf3d_enemy_think(Entity *self) { if (!self)return; if (self->type == 2 && self->live == yes) { gf3d_entity_set_colliders(self, (float)0.5, (float)0.3, (float)3.2, (float)0.72, (float)0.5, (float)0); if (enemy.hostile == yes) { gfc_matrix_rotate( self->modelMatrix, self->modelMatrix, 0.01, vector3d(0, 1, 0)); if (location().x > self->modelMatrix[3][0]) { gfc_matrix_translate( self->modelMatrix, vector3d(0.002, 0, 0)); } if (location().x < self->modelMatrix[3][0]) { gfc_matrix_translate( self->modelMatrix, vector3d(-0.002, 0, 0)); } if (location().y > self->modelMatrix[3][1]) { gfc_matrix_translate( self->modelMatrix, vector3d(0, 0.002, 0)); } if (location().y < self->modelMatrix[3][1]) { gfc_matrix_translate( self->modelMatrix, vector3d(0, -0.002, 0)); } if (location().x - self->modelMatrix[3][0] <= 1 && location().y - self->modelMatrix[3][1] <= 1 && location().z - self->modelMatrix[3][2] <= 1 && location().x - self->modelMatrix[3][0] >= -1 && location().y - self->modelMatrix[3][1] >= -1 && location().z - self->modelMatrix[3][2] >= -1) { respawn(); } } } if (self->type >= 3 && self->live == yes) { gf3d_entity_set_colliders(self, (float)0.5, (float)0.3, (float)3.2, (float)0.72, (float)0.5, (float)0); if (enemy.hostile == yes) { self->cooldown -= 0.001; if (self->cooldown <= 0) { gfc_matrix_make_translation( ent[0]->modelMatrix, vector3d(self->modelMatrix[3][0], self->modelMatrix[3][1], self->modelMatrix[3][2])); self->cooldown = 5; if (location().x > self->modelMatrix[3][0]) { shoot.x = 0.02; } if (location().x < self->modelMatrix[3][0]) { shoot.x = -0.02; } if (location().y > self->modelMatrix[3][1]) { shoot.y = 0.02; } if (location().y < self->modelMatrix[3][1]) { shoot.y = -0.02; } } if (location().x - ent[0]->modelMatrix[3][0] <= 1 && location().y - ent[0]->modelMatrix[3][1] <= 1 && location().z - ent[0]->modelMatrix[3][2] <= 1 && location().x - ent[0]->modelMatrix[3][0] >= -1 && location().y - ent[0]->modelMatrix[3][1] >= -1 && location().z - ent[0]->modelMatrix[3][2] >= -1 && enemy.hostile == yes) { respawn(); } } gfc_matrix_translate( ent[0]->modelMatrix, vector3d(shoot.x, shoot.y, 0)); } if (keys[SDL_SCANCODE_E] && location().x - self->modelMatrix[3][0] <= 1 && location().y - self->modelMatrix[3][1] <= 1 && location().z - self->modelMatrix[3][2] <= 1 && location().x - self->modelMatrix[3][0] >= -1 && location().y - self->modelMatrix[3][1] >= -1 && location().z - self->modelMatrix[3][2] >= -1) { self->live = no; gfc_matrix_rotate( self->modelMatrix, self->modelMatrix, -(float)1.5708, vector3d(1, 0, 0)); } if (self->ground == yes) { enemy.vel = 0; } if (self->ground == no) { gfc_matrix_translate( self->modelMatrix, vector3d(0, 0, enemy.vel)); if (enemy.vel < 0.1) { enemy.vel -= enemy.gravity; } } if (self->modelMatrix[3][2] <= -100 || self->modelMatrix[3][1] <= -100 || self->modelMatrix[3][0] <= -100 || self->modelMatrix[3][2] >= 100 || self->modelMatrix[3][1] >= 100 || self->modelMatrix[3][0] >= 100) { self->modelMatrix[3][0] = 0; self->modelMatrix[3][1] = 0; self->modelMatrix[3][2] = 5; enemy.vel = 0; } } void gf3d_detect() { enemy.hostile = yes; } void gf3d_lose() { enemy.hostile = no; }
jtk33/Vulkan
src/gf3d_gltf_load.c
#include <string.h> #include "simple_logger.h" #include "simple_json.h" #include "simple_json_list.h" #include "simple_json_parse.h" #include "gf3d_gltf_load.h" GLB_File *simple_glb_new() { GLB_File *glbFile = NULL; glbFile = (GLB_File*)malloc(sizeof(GLB_File)); if (!glbFile) { slog("failed to allocate space for GLP FILE"); return NULL; } memset(glbFile, 0, sizeof(GLB_File)); return glbFile; } uint32_t simple_glb_get_chunk_length(GLB_Chunk *chunk) { uint32_t size = 0; if (!chunk) { slog("no chunk provided"); return 0; } size = (sizeof(uint32_t)* 2) + chunk->chunkLength; slog("chunk is size %i", size); return size; } GLB_Chunk *simple_glb_get_chunk_by_type(GLB_File *glbFile, GLB_ChunkType type) { int i; if (!glbFile)return NULL; for (i = 0; i < glbFile->chunkCount; i++) { if (glbFile->chunkList[i].chunkType == type) { return &glbFile->chunkList[i]; } } return NULL; } SJson *simple_glb_get_json(GLB_File *glbFile) { SJson *json = NULL; GLB_Chunk *chunk = NULL; if (!glbFile) { slog("no glbFile provided"); return NULL; } chunk = simple_glb_get_chunk_by_type(glbFile, GLB_CT_JSON); if (!chunk) { slog("no JSON chunk in GLB, bad file"); return NULL; } slog("attempting to parse json data from chunk. length %i", chunk->chunkLength); // slog("json text loaded:%s\n",chunk->chunkData); json = sj_parse_buffer(chunk->chunkData, chunk->chunkLength); if (!json) { slog("json data from glb file failed to parse"); return NULL; } return json; } void simple_glb_parse(GLB_File *glb) { GLB_Chunk *chunk = NULL; uint32_t index = 0; uint32_t chunkCount = 0; uint32_t chunkIndex = 0; if (!glb)return; while (index < glb->header.length) { chunk = (GLB_Chunk *)&glb->buffer[index]; index += simple_glb_get_chunk_length(chunk); chunkCount++; } slog("chunkCount: %i", chunkCount); glb->chunkList = (GLB_Chunk*)malloc(sizeof(GLB_Chunk)*chunkCount); if (!glb->chunkList) { slog("failed to allocate chunk list"); return; } memset(glb->chunkList, 0, sizeof(GLB_Chunk)*chunkCount); index = 0; chunkIndex = 0; while ((index < glb->header.length) && (chunkIndex < chunkCount)) { chunk = (GLB_Chunk *)&glb->buffer[index]; glb->chunkList[chunkIndex].chunkLength = chunk->chunkLength - 4; glb->chunkList[chunkIndex].chunkType = chunk->chunkType; glb->chunkList[chunkIndex].chunkData = (char *)&chunk->chunkData; switch (chunk->chunkType) { case GLB_CT_JSON: slog("chunk %i is JSON", chunkIndex); break; case GLB_CT_BIN: slog("chunk %i is BINary", chunkIndex); break; default: slog("chunk %i is unknown: 0x%x", chunkIndex, chunk->chunkType); } chunkIndex++; index += simple_glb_get_chunk_length(chunk); } glb->chunkCount = chunkCount; slog("parsed %i chunks out of glb file", chunkCount); } GLB_File *simple_glb_load(char * filepath) { GLB_File *glbFile = NULL; FILE *file; int32_t fileLength = 0; file = fopen(filepath, "rb"); if (!file) { slog("failed to open file %s", filepath); return NULL; } glbFile = simple_glb_new(); if (!glbFile) { fclose(file); return NULL; } fread(&glbFile->header, sizeof(GLB_Header), 1, file); slog("glb file header:\n-magic: %X\n-version: %i\n-length:%i", glbFile->header.magic, glbFile->header.version, glbFile->header.length); fileLength = glbFile->header.length - sizeof(GLB_Header); if ((fileLength <= 0) || ((glbFile->buffer = malloc(fileLength)) == NULL)) { slog("bad glb file length: %i", fileLength); fclose(file); simple_glb_free(glbFile); return NULL; } memset(glbFile->buffer, 0, fileLength); slog("read %i bytes from glb file", fread(glbFile->buffer, fileLength, 1, file)*fileLength); fclose(file); simple_glb_parse(glbFile); return glbFile; } void gf3d_glb_get_counts_from_file(GLBData *glb, FILE* file) { char buf[256]; int numvertices = 0; int numtexels = 0; int numnormals = 0; int numfaces = 0; if ((file == NULL) || (glb == NULL)) { return; } while (fscanf(file, "%s", buf) != EOF) { switch (buf[0]) { case 'v': switch (buf[1]) { case '\0': fgets(buf, sizeof(buf), file); numvertices++; break; case 'n': fgets(buf, sizeof(buf), file); numnormals++; break; case 't': fgets(buf, sizeof(buf), file); numtexels++; break; default: break; } break; case 'f': fgets(buf, sizeof(buf), file); numfaces++; break; default: fgets(buf, sizeof(buf), file); break; } } glb->vertex_count = numvertices; glb->texel_count = numtexels; glb->normal_count = numnormals; glb->face_count = numfaces; } void gf3d_glb_load_reorg(GLBData *glb) { int i, f; int vert = 0; int vertexIndex, normalIndex, texelIndex; if (!glb)return; glb->face_vert_count = glb->face_count * 3; glb->faceVertices = (Vertex *)gfc_allocate_array(sizeof(Vertex), glb->face_vert_count); glb->outFace = (Face *)gfc_allocate_array(sizeof(Face), glb->face_count); for (i = 0; i < glb->face_count; i++) { for (f = 0; f < 3; f++, vert++) { vertexIndex = glb->faceVerts[i].verts[f]; normalIndex = glb->faceNormals[i].verts[f]; texelIndex = glb->faceTexels[i].verts[f]; vector3d_copy(glb->faceVertices[vert].vertex, glb->vertices[vertexIndex]); vector3d_copy(glb->faceVertices[vert].normal, glb->normals[normalIndex]); vector2d_copy(glb->faceVertices[vert].texel, glb->texels[texelIndex]); glb->outFace[i].verts[f] = vert; } } } void gf3d_glb_load_get_data_from_file(GLBData *glb, FILE* file) { int numvertices = 0; int numnormals = 0; int numtexcoords = 0; int numfaces = 0; char buf[128]; float x, y, z; int f[3][3]; if (file == NULL) return; rewind(file); while (fscanf(file, "%s", buf) != EOF) { switch (buf[0]) { case 'v': switch (buf[1]) { case '\0': fscanf( file, "%f %f %f", &x, &y, &z ); glb->vertices[numvertices].x = x; glb->vertices[numvertices].y = y; glb->vertices[numvertices].z = z; numvertices++; break; case 'n': fscanf( file, "%f %f %f", &x, &y, &z ); glb->normals[numnormals].x = x; glb->normals[numnormals].y = y; glb->normals[numnormals].z = z; numnormals++; break; case 't': fscanf( file, "%f %f", &x, &y ); glb->texels[numtexcoords].x = x; glb->texels[numtexcoords].y = 1 - y; numtexcoords++; break; default: break; } break; case 'f': fscanf( file, "%d/%d/%d %d/%d/%d %d/%d/%d", &f[0][0], &f[0][1], &f[0][2], &f[1][0], &f[1][1], &f[1][2], &f[2][0], &f[2][1], &f[2][2]); glb->faceVerts[numfaces].verts[0] = f[0][0] - 1; glb->faceTexels[numfaces].verts[0] = f[0][1] - 1; glb->faceNormals[numfaces].verts[0] = f[0][2] - 1; glb->faceVerts[numfaces].verts[1] = f[1][0] - 1; glb->faceTexels[numfaces].verts[1] = f[1][1] - 1; glb->faceNormals[numfaces].verts[1] = f[1][2] - 1; glb->faceVerts[numfaces].verts[2] = f[2][0] - 1; glb->faceTexels[numfaces].verts[2] = f[2][1] - 1; glb->faceNormals[numfaces].verts[2] = f[2][2] - 1; numfaces++; break; default: fgets(buf, sizeof(buf), file); break; } } } void simple_glb_free(GLB_File *glbFile) { if (!glbFile) { slog("no glbFile handle provided"); return; } if (glbFile->chunkList) { free(glbFile->chunkList); glbFile->chunkList = NULL; } if (glbFile->buffer) { free(glbFile->buffer); glbFile->buffer = NULL; } free(glbFile); } void simple_glb_free2(GLBData *glb) { if (!glb)return; if (glb->vertices != NULL) { free(glb->vertices); } if (glb->normals != NULL) { free(glb->normals); } if (glb->texels != NULL) { free(glb->texels); } if (glb->faceVerts != NULL) { free(glb->faceVerts); } if (glb->faceNormals != NULL) { free(glb->faceNormals); } if (glb->faceTexels != NULL) { free(glb->faceTexels); } if (glb->faceVertices != NULL) { free(glb->faceVertices); } if (glb->outFace != NULL) { free(glb->outFace); } free(glb); } GLBData *gf3d_glb_load_from_file(char *filename) { FILE *file; GLBData *glb; file = fopen(filename, "r"); if (!file) { slog("failed to open glb file %s", filename); return NULL; } glb = (GLBData*)gfc_allocate_array(sizeof(GLBData), 1); if (!glb)return NULL; gf3d_glb_get_counts_from_file(glb, file); glb->vertices = (Vector3D *)gfc_allocate_array(sizeof(Vector3D), glb->vertex_count); glb->normals = (Vector3D *)gfc_allocate_array(sizeof(Vector3D), glb->normal_count); glb->texels = (Vector2D *)gfc_allocate_array(sizeof(Vector2D), glb->texel_count); glb->faceVerts = (Face *)gfc_allocate_array(sizeof(Face), glb->face_count); glb->faceNormals = (Face *)gfc_allocate_array(sizeof(Face), glb->face_count); glb->faceTexels = (Face *)gfc_allocate_array(sizeof(Face), glb->face_count); gf3d_glb_load_get_data_from_file(glb, file); fclose(file); gf3d_glb_load_reorg(glb); return glb; } /*eol@eof*/
jtk33/Vulkan
include/gf3d_player.h
<filename>include/gf3d_player.h #ifndef __GF3D_PLAYER_H__ #define __GF3D_PLAYER_H__ #include "gfc_types.h" #include "gfc_matrix.h" #include "gf3d_model.h" #include "gf3d_entity.h" #include "gf3d_vgraphics.h" #include "SDL_keycode.h" #include "SDL_events.h" /** * @purpose this is the file to access the the player */ void gf3d_player_init(); void gf3d_player_think(Entity *self); void gf3d_player_grounded(); void gf3d_player_air(); float gf3d_detection(); Vector3D location(); void jumpoff(); #endif
jtk33/Vulkan
include/gf3d_sprite.h
#ifndef __GF3D_SPRITE_H__ #define __GF3D_SPRITE_H__ /** * gf3d_sprite * @license The MIT License (MIT) @copyright Copyright (c) 2019 EngineerOfLies Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "gfc_types.h" #include "gfc_vector.h" #include "gfc_matrix.h" #include "gfc_text.h" #include "gf3d_texture.h" typedef struct { Uint8 _inuse; TextLine filename; /**<the name of the file used to create the sprite*/ Uint32 frameCount; /**<how many frames are loaded for this model*/ Texture *texture; /**<texture memory pointer*/ Uint8 framesPerLine; /**<how many frames are per line in the sprite sheet*/ Uint32 frameWidth, frameHeight; /*<the size, in pixels, of the individual sprite frames*/ VkBuffer buffer; /**<vertex buffer for the sprite (always 4 vertices)*/ VkDeviceMemory bufferMemory; /**<memory handle for the vertex buffer*/ VkDescriptorSet *descriptorSet; /**<descriptor sets used for this sprite to render*/ VkBuffer *uniformBuffers; /**<handles for the UBO*/ VkDeviceMemory *uniformBuffersMemory; /**<memory handle for the UBO memory*/ Uint32 uniformBufferCount; /**<how many UBOs for the sprite*/ }Sprite; /** * @brief initialize the internal management system for sprites, auto-cleaned up on program exit * @param max_sprites how many concurrent sprites to support * @param chain_length how many images are available in the swap chain * @param device the logical vulkan device to be rendering to */ void gf3d_sprite_manager_init(Uint32 max_sprites, Uint32 chain_length, VkDevice device); /** * @brief loads a sprite sheet into memory * @param frame_width how wide an individual frame is on the sprite sheet * @param frame_height how high an individual frame is on the sprite sheet * @param frames_per_line how many frames across are on the sprite sheet * @return NULL on error (check logs) or a pointer to a sprite that can be draw to the 2d overlay */ Sprite * gf3d_sprite_load(char * filename, int frame_width, int frame_height, Uint32 frames_per_line); /** * @brief free a previously loaded sprite * @param sprite a pointer to the sprite to be freed */ void gf3d_sprite_free(Sprite *sprite); /** * @brief draw a sprite frame to the current buffer frame * @param sprite the sprite to draw * @param position where on the screen to draw the sprite * @param scale amount to scale the sprite by. (1,1) is no scale * @param frame the frame of the sprite to draw * @param buffer_frame the current rendering context * @param commandBuffer the command to use to execute the draw call */ void gf3d_sprite_draw(Sprite *sprite, Vector2D position, Vector2D scale, Uint32 frame, Uint32 buffer_frame, VkCommandBuffer commandBuffer); /** * @brief get the binding description for a sprite */ VkVertexInputBindingDescription * gf3d_sprite_get_bind_description(); VkVertexInputAttributeDescription * gf3d_sprite_get_attribute_descriptions(Uint32 *count); #endif
jtk33/Vulkan
include/gf3d_enemy.h
<filename>include/gf3d_enemy.h #ifndef __GF3D_ENEMY_H__ #define __GF3D_ENEMY_H__ #include "gfc_types.h" #include "gfc_matrix.h" #include "gf3d_model.h" #include "gf3d_entity.h" #include "gf3d_vgraphics.h" #include "SDL_keycode.h" #include "SDL_events.h" /** * @purpose this is the file to access the the enemy */ void gf3d_enemy_init(); void gf3d_enemy_think(Entity *self); void gf3d_enemy_grounded(); void gf3d_enemy_air(); void gf3d_detect(); #endif
jtk33/Vulkan
src/game.c
<reponame>jtk33/Vulkan #include <SDL.h> #include "simple_logger.h" #include "gfc_vector.h" #include "gfc_matrix.h" #include "gf3d_vgraphics.h" #include "gf3d_pipeline.h" #include "gf3d_swapchain.h" #include "gf3d_model.h" #include "gf3d_camera.h" #include "gf3d_texture.h" #include "gf3d_entity.h" #include "gf3d_player.h" #include "gf3d_enemy.h" #include "gf3d_boss.h" #include "gf3d_gltf_load.h" #include "SDL_keycode.h" #include "SDL_events.h" int main(int argc,char *argv[]) { int done = 0; int a, i; Uint8 validate = 0; const Uint8 * keys; Uint32 bufferFrame = 0; VkCommandBuffer commandBuffer; Entity *ent[10] = { 0 }; Matrix4 *view; for (a = 1; a < argc;a++) { if (strcmp(argv[a],"-disable_validate") == 0) { validate = 0; } } init_logger("gf3d.log"); slog("gf3d begin"); gf3d_vgraphics_init( "gf3d", //program name 1600, //screen width 900, //screen height vector4d(1,1,1,1), //background color 0, //fullscreen validate //validation ); slog_sync(); gf3d_entity_init(256); // main game loop slog("gf3d main loop begin"); slog_sync(); ent[0] = gf3d_entity_new(); ent[0]->model = gf3d_model_load("robo"); ent[0]->think = gf3d_player_think; gf3d_entity_set_colliders(ent[0], (float)0.5, (float)0.3, (float)3.2, (float)0.72, (float)0.5, (float)0); ent[0]->modelMatrix[3][2] = 5; ent[0]->modelMatrix[3][0] = 0; ent[0]->modelMatrix[3][0] = 0; ent[1] = gf3d_entity_new(); ent[1]->model = gf3d_model_load("skybox"); ent[2] = gf3d_entity_new(); ent[2]->model = gf3d_model_load("base"); gf3d_entity_set_colliders(ent[2], (float)25, (float)25, (float)0.5, (float)25, (float)25, (float)0.5); ent[3] = gf3d_entity_new(); ent[3]->model = gf3d_model_load("platform1"); gfc_matrix_make_translation( ent[3]->modelMatrix, vector3d(20, -50, 0)); gf3d_entity_set_colliders(ent[3], (float)2, (float)2, (float)0.5, (float)2, (float)2, (float)0.5); ent[4] = gf3d_entity_new(); ent[4]->model = gf3d_model_load("platform1"); gfc_matrix_make_translation( ent[4]->modelMatrix, vector3d(-20, -50, 0)); gf3d_entity_set_colliders(ent[4], (float)2, (float)2, (float)0.5, (float)2, (float)2, (float)0.5); ent[5] = gf3d_entity_new(); ent[5]->model = gf3d_model_load("detectorg"); gfc_matrix_make_translation( ent[5]->modelMatrix, vector3d(-30, -20, 5)); gf3d_entity_set_colliders(ent[5], (float)50, (float)15, (float)15, (float)15, (float)15, (float)15); ent[6] = gf3d_entity_new(); ent[6]->model = gf3d_model_load("melee"); ent[6]->think = gf3d_enemy_think; gf3d_entity_set_colliders(ent[6], (float)0.5, (float)0.3, (float)3.2, (float)0.72, (float)0.5, (float)0); gfc_matrix_make_translation( ent[6]->modelMatrix, vector3d(-20, -20, 5)); ent[7] = gf3d_entity_new(); ent[7]->model = gf3d_model_load("shooter"); ent[7]->think = gf3d_enemy_think; gf3d_entity_set_colliders(ent[7], (float)0.5, (float)0.3, (float)3.2, (float)0.72, (float)0.5, (float)0); gfc_matrix_make_translation( ent[7]->modelMatrix, vector3d(20, -20, 5)); ent[8] = gf3d_entity_new(); ent[8]->model = gf3d_model_load("boss"); ent[8]->think = gf3d_boss_think; gf3d_entity_set_colliders(ent[8], (float)0.5, (float)0.3, (float)3.2, (float)0.72, (float)0.5, (float)0); gfc_matrix_make_translation( ent[8]->modelMatrix, vector3d(100, -75, 5)); /*ent[6] = gf3d_entity_new(); ent[6]->model = gf3d_model2_load("cube"); gfc_matrix_make_translation( ent[6]->modelMatrix, vector3d(0, 0, 0)); gf3d_entity_set_colliders(ent[6], (float)2, (float)2, (float)2, (float)2, (float)2, (float)2);*/ gf3d_player_init(); gfc_matrix_rotate( ent[0]->modelMatrix, ent[0]->modelMatrix, (float)1.5708, vector3d(1, 0, 0)); ent[0]->type = 1; gfc_matrix_rotate( ent[2]->modelMatrix, ent[2]->modelMatrix, (float)1.5708, vector3d(1, 0, 0)); gfc_matrix_rotate( ent[3]->modelMatrix, ent[3]->modelMatrix, (float)1.5708, vector3d(1, 0, 0)); gfc_matrix_rotate( ent[4]->modelMatrix, ent[4]->modelMatrix, (float)1.5708, vector3d(1, 0, 0)); gf3d_enemy_init(); gfc_matrix_rotate( ent[6]->modelMatrix, ent[6]->modelMatrix, (float)1.5708, vector3d(1, 0, 0)); ent[6]->type = 2; ent[6]->ground = no; ent[6]->live = yes; gfc_matrix_rotate( ent[7]->modelMatrix, ent[7]->modelMatrix, (float)1.5708, vector3d(1, 0, 0)); ent[7]->type = 3; ent[7]->ground = no; ent[7]->live = yes; gfc_matrix_rotate( ent[8]->modelMatrix, ent[8]->modelMatrix, (float)1.5708, vector3d(1, 0, 0)); //view = gf3d_vgraphics_get_view(); SDL_ShowCursor(0); SDL_SetRelativeMouseMode(SDL_TRUE); while(!done) { SDL_PumpEvents(); // update SDL's internal event structures keys = SDL_GetKeyboardState(NULL); // get the keyboard state for this frame //update game things here gf3d_entity_think_all(); gf3d_camera_think(ent[0]); gf3d_collision_think(ent[2], ent[0]); gf3d_collision_think(ent[3], ent[0]); gf3d_collision_think(ent[4], ent[0]); gf3d_collision_think(ent[2], ent[6]); gf3d_collision_think(ent[3], ent[6]); gf3d_collision_think(ent[4], ent[6]); gf3d_detector_think(ent[5], ent[0]); /*gfc_matrix_view( view, vector3d(*view[3][0], ent[0]->modelMatrix[3][1] + 9, ent[0]->modelMatrix[3][2] + 5), vector3d(ent[0]->modelMatrix[3][0], ent[0]->modelMatrix[3][1], ent[0]->modelMatrix[3][2] + 3.6), vector3d(0, 0, 1));*/ //gfc_matrix_copy(gf3d_vgraphics_get_view, view); //gfc_matrix_slog(ent[0]->modelMatrix); // configure render command for graphics command pool // for each mesh, get a command and configure it from the pool bufferFrame = gf3d_vgraphics_render_begin(); gf3d_pipeline_reset_frame(gf3d_vgraphics_get_graphics_pipeline(),bufferFrame); commandBuffer = gf3d_command_rendering_begin(bufferFrame); gf3d_entity_draw_all(bufferFrame, commandBuffer); gf3d_command_rendering_end(commandBuffer); gf3d_vgraphics_render_end(bufferFrame); if (keys[SDL_SCANCODE_ESCAPE])done = 1; // exit condition } vkDeviceWaitIdle(gf3d_vgraphics_get_default_logical_device()); //cleanup slog("gf3d program end"); slog_sync(); return 0; } /*eol@eof*/
jtk33/Vulkan
include/gf3d_gltf_load.h
#ifndef __GF3D_GLTF_LOAD_H__ #define __GF3D_GLTF_LOAD_H__ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "simple_json.h" #include "gf3d_mesh.h" typedef struct { uint32_t magic; /**<equals 0x46546C67. It is ASCII string glTF*/ uint32_t version; /**<indicates the version of the Binary glTF container format.*/ uint32_t length; /**<is the total length of the Binary glTF, including Header and all Chunks, in bytes.*/ }GLB_Header; typedef enum { GLB_CT_JSON = 0x4E4F534A, GLB_CT_BIN = 0x004E4942 }GLB_ChunkType; typedef struct { uint32_t chunkLength; /**<is the length of chunkData, in bytes.*/ uint32_t chunkType; /**<indicates the type of chunk. one of GLB_ChunkType*/ char *chunkData; /**<is a binary payload of chunk*/ }GLB_Chunk; typedef struct { GLB_Header header; /**<file header for GLB file*/ char * buffer; /**<data blob for the GLB file*/ GLB_Chunk *chunkList; /**<list of chunks in the buffer*/ uint32_t chunkCount; /**<how many chunks are in the list*/ }GLB_File; typedef struct { Vector3D *vertices; Uint32 vertex_count; Vector3D *normals; Uint32 normal_count; Vector2D *texels; Uint32 texel_count; Face *faceVerts; Face *faceNormals; Face *faceTexels; Uint32 face_count; Face *outFace; Vertex *faceVertices; Uint32 face_vert_count; }GLBData; /** * @brief given a glbFile, parse the json out of it * @param glbFile the file to parse * @return NULL on error, or a SJson object * @note: returned object must be freed with sj_free() */ SJson *simple_glb_get_json(GLB_File *glbFile); /** * @brief load a GLB file from disk * @note file must be freed with simple_glb_free * @param filepath the file to load * @return NULL on error (see logs) or a pointer to a loaded GLB file otherwise */ GLB_File *simple_glb_load(char * filepath); /** * @brief free the data from a glbFile * @param glbFFile the glb data to free */ void simple_glb_free(GLB_File *glbFile); GLBData *gf3d_glb_load_from_file(char *filename); #endif
jtk33/Vulkan
src/gf3d_entity.c
#include "simple_logger.h" #include "gf3d_entity.h" #include "gf3d_player.h" #include "gf3d_enemy.h" typedef struct { Entity *entity_list; /**<My big ole list of entities*/ Uint32 entity_count; /**<upper limit for concurrent active entities*/ }EntityManager; static EntityManager gf3d_entity = {0}; void gf3d_entity_free(Entity *entity); float collidercount = 3; float relook = 1; float hostile = 0; void gf3d_entity_close( void ) { int i; if (gf3d_entity.entity_list != NULL) { for (i = 0; i < (int)gf3d_entity.entity_count; i++) { gf3d_entity_free(&gf3d_entity.entity_list[i]); } free(gf3d_entity.entity_list); } memset(&gf3d_entity, 0, sizeof(EntityManager)); slog("Entity System Closed, pog, I suppose."); } void gf3d_entity_init(Uint32 maxEntities) { if (gf3d_entity.entity_list != NULL) { slog("WARNING: entity system already initialized"); return; } gf3d_entity.entity_list = gfc_allocate_array(sizeof(Entity),maxEntities); if (!gf3d_entity.entity_list) { slog("failed to allocate big ole entity list"); } gf3d_entity.entity_count = maxEntities; atexit(gf3d_entity_close); slog("Entity System Initialized, POG!"); } void gf3d_entity_free(Entity *entity) { if (!entity)return; gf3d_model_free(entity->model); memset(entity,0,sizeof(Entity)); } Entity *gf3d_entity_new() { int i; for (i = 0; i < (int) gf3d_entity.entity_count; i++) { if (!gf3d_entity.entity_list[i]._inuse) { gf3d_entity.entity_list[i]._inuse = 1; gfc_matrix_identity(gf3d_entity.entity_list[i].modelMatrix); gf3d_entity.entity_list[i].x = 0; gf3d_entity.entity_list[i].y = 0; gf3d_entity.entity_list[i].z = 0; gf3d_entity.entity_list[i].nx = 0; gf3d_entity.entity_list[i].ny = 0; gf3d_entity.entity_list[i].nz = 0; gf3d_entity.entity_list[i].canx = yes; gf3d_entity.entity_list[i].cany = yes; gf3d_entity.entity_list[i].cannx = yes; gf3d_entity.entity_list[i].canny = yes; return &gf3d_entity.entity_list[i]; } } slog("Failed to provide new entity, no unused slots"); return NULL; } void gf3d_entity_think(Entity *self) { if (!self)return; if (!self->think)return;//no think function to call self->think(self); } void gf3d_entity_think_all() { int i; for (i = 0; i < (int)gf3d_entity.entity_count; i++) { if (!gf3d_entity.entity_list[i]._inuse)continue; gf3d_entity_think(&gf3d_entity.entity_list[i]); } } void gf3d_entity_set_colliders(Entity *self, float cx, float cy, float cz, float cnx, float cny, float cnz) { self->x = self->modelMatrix[3][0] + cx; self->y = self->modelMatrix[3][1] + cy; self->z = self->modelMatrix[3][2] + cz; self->nx = self->modelMatrix[3][0] - cnx; self->ny = self->modelMatrix[3][1] - cny; self->nz = self->modelMatrix[3][2] - cnz; } void gf3d_collision_think(Entity *self, Entity *other) { if (!self)return; if (self->nx < other->x && self->x > other->nx && self->ny < other->y && self->y > other->ny && self->nz < other->z && self->z > other->nz) { collidercount = 3; if (other->type == 1) gf3d_player_grounded(); else if (other->type == 2) other->ground = yes; } else { collidercount -= 1; if (collidercount <= 0) { if (other->type == 1) gf3d_player_air(); else if (other->type >= 2) other->ground = no; other->canx = yes; other->cany = yes; other->cannx = yes; other->canny = yes; } } if (self->nx < other->x && self->x > other->nx && self->ny < other->y && self->y > other->ny && self->nz < other->z && self->z > other->nz && self->z > other->nz + 0.1) { collision_detect(self, other); } } void collision_detect(Entity *self, Entity *other) { if (self->nx < other->x + 0.1) { other->canx = no; } if (self->x > other->nx - 0.1) { other->cannx = no; } if (self->ny < other->y + 0.1) { other->cany = no; } if (self->y > other->ny - 0.1) { other->canny = no; } } void gf3d_detector_think(Entity *self, Entity *other) { if (!self)return; relook -= 0.0005; if (self->nx < other->x && self->x > other->nx && self->ny < other->y && self->y > other->ny && self->nz < other->z && self->z > other->nz) { if ((gfc_crandom() + 1) * 100 < gf3d_detection() && relook <= 0) { relook = 1; if (hostile == 0) { //gf3d_model_delete(self->model); self->model = gf3d_model_load("detectorr"); hostile = 1; gf3d_detect(); } } } else if (hostile == 1 && relook <= 0) { self->model = gf3d_model_load("detectorg"); hostile = 0; } if (relook <= 0) { relook = 1; } } void gf3d_entity_draw(Entity *self, Uint32 bufferFrame, VkCommandBuffer commandBuffer) { if (!self)return; gf3d_model_draw(self->model, bufferFrame, commandBuffer, self->modelMatrix); } void gf3d_entity_draw_all(Uint32 bufferFrame, VkCommandBuffer commandBuffer) { int i; for (i = 0; i < (int)gf3d_entity.entity_count; i++) { if (!gf3d_entity.entity_list[i]._inuse)continue; gf3d_entity_draw(&gf3d_entity.entity_list[i], bufferFrame, commandBuffer); } } /*eol@oef*/
jtk33/Vulkan
include/gf3d_boss.h
#ifndef __GF3D_BOSS_H__ #define __GF3D_BOSS_H__ #include "gfc_types.h" #include "gfc_matrix.h" #include "gf3d_model.h" #include "gf3d_entity.h" #include "gf3d_vgraphics.h" #include "SDL_keycode.h" #include "SDL_events.h" /** * @purpose this is the file to access the the enemy */ void gf3d_boss_init(); void gf3d_boss_think(Entity *self); #endif
jtk33/Vulkan
src/gf3d_player.c
#include "simple_logger.h" #include "simple_json.h" #include "gf3d_player.h" #include "SDL_keycode.h" #include "SDL_events.h" enum form{ stealth = 0, platformer = 1 }; typedef struct { enum form form; /**Stealth or Platformer?*/ float speed; /**It's a mystery what this one does*/ float jumpheight; /**Self explanatory, again, have fun*/ enum state crouch; /**Is the player crouching?*/ enum state prone; /**Is the player prone?*/ enum state sprint; /**Is the player sprinting?*/ enum state cloaking; /**Is the player using cloaking technology?*/ enum state boxxed; /**Is the player using the most cutting-edge of stealth technology?*/ float sprintspeed; /**Sprint speed, AKA the speed when you sprint.*/ float gravity; /**Player gravity.*/ enum state grounded; /**Is the player on the ground?*/ float tpdistance; /**Teleportation distance*/ float detection; /**% Chance of being detected at every frame*/ }Player; Player player; const Uint8 * keys; float airvelocity; float djwait; //Double Jump Wait, the time until a double jump is activated, to avoid the player instantly wasting it. float formwait; enum state cantp; float cloakwait; float boxwait; float tpwait; float originspeed; Vector2D angle; float theta; Vector2D direction; int x, y; Vector3D loc; int anim; int rev; void gf3d_player_init() { if (player.form != NULL) { slog("Uh oh, the player already exists in the world."); return; } keys = SDL_GetKeyboardState(NULL); player.form = platformer; player.speed = 0.005; player.jumpheight = 0.01; player.crouch = no; player.prone = no; player.sprint = no; player.cloaking = no; player.boxxed = no; player.sprintspeed = 0.01; player.gravity = 0.00001; player.grounded = no; player.tpdistance = 10; airvelocity = 0; djwait = 1; formwait = 1; cloakwait = 1; boxwait = 1; tpwait = 1; cantp = yes; originspeed = player.speed; loc.z = 5; anim = 0; rev = 0; } void respawn() { loc.x = 0; loc.y = 0; loc.z = 5; airvelocity = 0; gf3d_lose(); } void runnin(Entity *self) { if (anim <= 500) { rev = 0; } if (anim >= 1450) { rev = 1; } if (rev == 0) { anim++; } if (rev == 1) { anim--; } if (anim < 100) { self->model = gf3d_pmodel_load(self->model, "run/r1"); } else if (anim < 200) { self->model = gf3d_pmodel_load(self->model, "run/r2"); } else if (anim < 300) { self->model = gf3d_pmodel_load(self->model, "run/r3"); } else if (anim < 400) { self->model = gf3d_pmodel_load(self->model, "run/r4"); } else if (anim < 500) { self->model = gf3d_pmodel_load(self->model, "run/r5"); } else if (anim < 600) { self->model = gf3d_pmodel_load(self->model, "run/r6"); } else if (anim < 700) { self->model = gf3d_pmodel_load(self->model, "run/r7"); } else if (anim < 800) { self->model = gf3d_pmodel_load(self->model, "run/r8"); } else if (anim < 900) { self->model = gf3d_pmodel_load(self->model, "run/r9"); } else if (anim < 1000) { self->model = gf3d_pmodel_load(self->model, "run/r10"); } else if (anim < 1100) { self->model = gf3d_pmodel_load(self->model, "run/r11"); } else if (anim < 1200) { self->model = gf3d_pmodel_load(self->model, "run/r12"); } else if (anim < 1300) { self->model = gf3d_pmodel_load(self->model, "run/r13"); } else if (anim < 1400) { self->model = gf3d_pmodel_load(self->model, "run/r14"); } else if (anim < 1500) { self->model = gf3d_pmodel_load(self->model, "run/r15"); } } void gf3d_player_think(Entity *self) { if (!self)return; gf3d_entity_set_colliders(self, (float)0.5, (float)0.3, (float)3.2, (float)0.72, (float)0.5, (float)0); angle.x = rotatex(); angle.y = rotatey(); theta = atan2(angle.y, angle.x); direction.x = cos(theta) * 2; direction.y = sin(theta) * 2; gfc_matrix_rotate( self->modelMatrix, self->modelMatrix, -mousex() * GFC_DEGTORAD * 0.1, vector3d(0, 1, 0)); self->modelMatrix[3][0] = loc.x; self->modelMatrix[3][1] = loc.y; self->modelMatrix[3][2] = loc.z; if (player.form == platformer) { player.detection = 100; } if (player.form == stealth) { player.detection = 50; } if (player.crouch == yes) { player.detection = 20; } if (player.prone == yes) { player.detection = 5; } if (player.boxxed == yes) { player.detection = 1; } if (player.cloaking == yes) { player.detection = 0; } /*if (self->modelMatrix[3][2] <= 0) { player.grounded = yes; } else { player.grounded = no; }*/ if (formwait > 0) { formwait -= 0.001; } if (cloakwait > 0) { cloakwait -= 0.001; } if (boxwait > 0) { boxwait -= 0.001; } if (tpwait > 0) { tpwait -= 0.001; } if (keys[SDL_SCANCODE_TAB]) { if (formwait <= 0) { formwait = 1; if (player.form == platformer) { player.form = stealth; self->modelMatrix[1][2] = 0.9; //self->model = gf3d_model_load("cloaked"); player.speed = originspeed * 0.5; } else if (player.form == stealth) { player.form = platformer; self->modelMatrix[1][2] = 1; //->model = gf3d_model_load("robo"); player.speed = originspeed; player.crouch = no; player.prone = no; player.cloaking = no; player.boxxed = no; } } } if (keys[SDL_SCANCODE_LSHIFT]) { if (player.form == platformer) { player.sprint = yes; } else if (player.form == stealth) { player.crouch = yes; self->modelMatrix[1][2] = 0.5; player.speed = originspeed * 0.3; } } else { if (player.form == platformer) { player.sprint = no; } else if (player.form == stealth) { if (player.crouch == yes) { player.crouch = no; self->modelMatrix[1][2] = 0.9; player.speed = originspeed * 0.5; } } } if (keys[SDL_SCANCODE_LCTRL]) { if (player.form == stealth) { if (player.crouch == yes) { player.crouch = no; } player.prone = yes; self->modelMatrix[1][2] = 0.2; player.speed = originspeed * 0.1; } } else { if (player.form == stealth) { if (player.prone == yes) { player.prone = no; self->modelMatrix[1][2] = 0.9; player.speed = originspeed * 0.5; } } } if (keys[SDL_SCANCODE_A] && player.boxxed == no) { if (self->canny == yes && self->canx == yes) { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(direction.y * player.sprintspeed, -direction.x * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(direction.y * player.speed, -direction.x * player.speed, 0)); } } else { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.y * player.sprintspeed, direction.x * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.y * player.speed, direction.x * player.speed, 0)); } } runnin(self); } if (keys[SDL_SCANCODE_D] && player.boxxed == no) { if (self->canny == yes && self->canx == yes) { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.y * player.sprintspeed, direction.x * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.y * player.speed, direction.x * player.speed, 0)); } } else { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(direction.y * player.sprintspeed, -direction.x * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(direction.y * player.speed, -direction.x * player.speed, 0)); } } runnin(self); } if (keys[SDL_SCANCODE_S] && player.boxxed == no) { if (self->cany == yes && self->canx == yes) { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(direction.x * player.sprintspeed, direction.y * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(direction.x * player.speed, direction.y * player.speed, 0)); } } else { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.x * player.sprintspeed, -direction.y * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.x * player.speed, -direction.y * player.speed, 0)); } } runnin(self); } if (keys[SDL_SCANCODE_W] && player.boxxed == no) { if (self->canny == yes && self->canx == yes) { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.x * player.sprintspeed, -direction.y * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(-direction.x * player.speed, -direction.y * player.speed, 0)); } } else { if (player.sprint == yes) { gfc_matrix_translate( self->modelMatrix, vector3d(direction.x * player.sprintspeed, direction.y * player.sprintspeed, 0)); } else { gfc_matrix_translate( self->modelMatrix, vector3d(direction.x * player.speed, direction.y * player.speed, 0)); } } runnin(self); } if (keys[SDL_SCANCODE_X]) { if (player.form == platformer) { airvelocity += player.gravity + 0.000005; } if (player.form == stealth) { if (cloakwait <= 0) { cloakwait = 1; if (player.cloaking == no) { player.cloaking = yes; self->model = gf3d_model_load("cloaked"); } else if (player.cloaking == yes) { player.cloaking = no; self->model = gf3d_model_load("robo"); } } } } if (keys[SDL_SCANCODE_LALT]) { if (player.form == platformer) { if (keys[SDL_SCANCODE_A]) { if (tpwait <= 0) { tpwait = 1; gfc_matrix_translate( self->modelMatrix, vector3d(direction.y * player.tpdistance, -direction.x * player.tpdistance, 0)); cantp = no; } } if (keys[SDL_SCANCODE_D]) { if (tpwait <= 0) { tpwait = 1; gfc_matrix_translate( self->modelMatrix, vector3d(-direction.y * player.tpdistance, direction.x * player.tpdistance, 0)); cantp = no; } } if (keys[SDL_SCANCODE_S]) { if (tpwait <= 0) { tpwait = 1; gfc_matrix_translate( self->modelMatrix, vector3d(direction.x * player.tpdistance, direction.y * player.tpdistance, 0)); cantp = no; } } if (keys[SDL_SCANCODE_W]) { if (tpwait <= 0) { tpwait = 1; gfc_matrix_translate( self->modelMatrix, vector3d(-direction.x * player.tpdistance, -direction.y * player.tpdistance, 0)); cantp = no; } } } if (player.form == stealth) { if (boxwait <= 0) { boxwait = 1; if (player.boxxed == no) { player.boxxed = yes; player.cloaking = no; self->model = gf3d_model_load("box"); player.speed = 0; } else if (player.boxxed == yes) { player.boxxed = no; self->model = gf3d_model_load("robo"); player.speed = originspeed * 0.5; } } } } if (player.grounded == yes) { airvelocity = 0; djwait = 1; cantp = yes; } if (player.grounded == yes && keys[SDL_SCANCODE_SPACE]) { if (player.crouch == no && player.prone == no) { player.grounded = no; airvelocity = player.jumpheight; } } if (player.grounded == no) { gfc_matrix_translate( self->modelMatrix, vector3d(0, 0, airvelocity)); if (airvelocity < 0.1) { airvelocity -= player.gravity; } if (djwait != 10) { djwait -= 0.001; } } if (player.grounded == no && keys[SDL_SCANCODE_SPACE] && djwait <= 0 && player.form == platformer) { airvelocity = player.jumpheight; djwait = 10; } loc.x = self->modelMatrix[3][0]; loc.y = self->modelMatrix[3][1]; loc.z = self->modelMatrix[3][2]; if (self->modelMatrix[3][2] <= -100 || self->modelMatrix[3][1] <= -100 || self->modelMatrix[3][0] <= -100 || self->modelMatrix[3][2] >= 100 || self->modelMatrix[3][1] >= 100 || self->modelMatrix[3][0] >= 100) { respawn(); } if (!keys[SDL_SCANCODE_W] && !keys[SDL_SCANCODE_A] && !keys[SDL_SCANCODE_S] && !keys[SDL_SCANCODE_D] && player.boxxed == no) { anim = 0; rev = 0; self->model = gf3d_pmodel_load(self->model, "robo"); } } void gf3d_player_grounded() { player.grounded = yes; } void gf3d_player_air() { player.grounded = no; } float gf3d_detection() { return player.detection; } Vector3D location() { return loc; } void jumpoff() { airvelocity = player.jumpheight * 3; djwait = 10; }
jtk33/Vulkan
include/gf3d_entity.h
#ifndef __GF3D_ENTITY_H__ #define __GF3D_ENTITY_H__ #include "gfc_types.h" #include "gfc_matrix.h" #include "gf3d_model.h" /** * @purpose this is the file to access the entity management system */ enum state{ yes = 0, no = 1 }; typedef struct Entity_S { Uint8 _inuse; /**<flag to make sure entities are not re-assigned while active*/ Model *model; Matrix4 modelMatrix; float x; /**Used for collision, x centered on the modelMatrix*/ float y; /**Used for collision, y centered on the modelMatrix*/ float z; /**Used for collision, z centered on the modelMatrix*/ float nx; /**Used for collision, negative x centered on the modelMatrix*/ float ny; /**Used for collision, negative y centered on the modelMatrix*/ float nz; /**Used for collision, negative z centered on the modelMatrix*/ enum state canx; /**Can move on x?*/ enum state cany; /**Can it move on y?*/ enum state cannx; /**Can it move on negative x?*/ enum state canny; /**Can it move on negative y?*/ void (*think)(struct Entity_S *self); int type; enum state ground; float cooldown; enum state live; }Entity; void gf3d_entity_init(Uint32 maxEntities); Entity *gf3d_entity_new(); void gf3d_entity_draw(Entity *self, Uint32 bufferFrame, VkCommandBuffer commandBuffer); void gf3d_entity_draw_all(Uint32 bufferFrame, VkCommandBuffer commandBuffer); void gf3d_entity_think_all(); void gf3d_entity_set_colliders(Entity *self, float cx, float cy, float cz, float cnx, float cny, float cnz); void gf3d_collision_think(Entity *self, Entity *other); void collision_detect(Entity *self, Entity *other); void gf3d_entity_free(Entity *entity); #endif
jtk33/Vulkan
src/gf3d_boss.c
#include "simple_logger.h" #include "gf3d_enemy.h" #include "gf3d_player.h" #include "SDL_keycode.h" #include "SDL_events.h" void gf3d_boss_init() { } void gf3d_boss_think(Entity *self) { if (!self)return; gfc_matrix_translate( self->modelMatrix, vector3d(-0.1, 0, 0)); gfc_matrix_rotate( self->modelMatrix, self->modelMatrix, 0.01, vector3d(0, 1, 0)); if (self->modelMatrix[3][0] <= -100) { gfc_matrix_translate( self->modelMatrix, vector3d(200, 0, 0)); } if (location().x - self->modelMatrix[3][0] <= 4 && location().y - self->modelMatrix[3][1] <= 4 && location().z - self->modelMatrix[3][2] <= 4 && location().x - self->modelMatrix[3][0] >= -4 && location().y - self->modelMatrix[3][1] >= -4 && location().z - self->modelMatrix[3][2] >= -4) { gf3d_entity_free(self); jumpoff(); } }
Akshat69/SFML-RPG
SFML-RPG/GUI.h
#pragma once #include "stdafx.h" namespace GUI { enum Button_State { IDLE = 0, HOVER, PRESSED }; class Button { private: short unsigned buttonState; sf::RectangleShape shape; sf::Font* font; sf::Text text; sf::Color idleColorButton, hoverColorButton, activeColorButton; sf::Color idleColorText, hoverColorText, activeColorText; public: Button(float posX, float posY, float width, float height, sf::Font* font, std::string text, sf::Color idleColor, sf::Color hoverColor, sf::Color activeColor, sf::Color idleColorText, sf::Color hoverColorText, sf::Color activeColorText); ~Button(); const bool isPressed(); //Functions void Update(const sf::Vector2f mousePos); void Render(sf::RenderTarget* target); }; class SlideBox { private: sf::RectangleShape activeShape; Button* lButton = nullptr; Button* rButton = nullptr; sf::Font font; sf::Text text; int currentIndex = 0; std::vector<std::string> contentList; //Initializer Functions void initSlideBox(); void initButtons(); public: SlideBox(sf::Vector2f Position, sf::Vector2f Dimensions, sf::Font* font, sf::Color SliderColor, std::vector<std::string> contentList); ~SlideBox(); //Functions void Update(const sf::Vector2f mousePos); void UpdateButtons(const sf::Vector2f mousePos); void UpdateSlider(); void Render(sf::RenderTarget* target); std::string getCurrentContent() { return this->contentList[this->currentIndex]; } }; }
Akshat69/SFML-RPG
SFML-RPG/Tile.h
<gh_stars>0 #pragma once class Tile { private: protected: sf::RectangleShape shape; public: Tile(); Tile(float x, float y, float gridSizeF); ~Tile(); void Update(const float& DeltaTime); void Render(sf::RenderTarget* target); };
Akshat69/SFML-RPG
SFML-RPG/GameState.h
#pragma once #include "PauseMenuState.h" #include "TileMap.h" class GameState : public State { private: Character* player; TileMap* map; public: GameState(sf::RenderWindow* window, std::map<std::string, int>* supportedKeys, std::stack<State*>* states); //Functions void initTileMap(); void initKeybinds(); void initTextures(); void initCharacters(); void Update(const float DeltaTime); void Render(sf::RenderTarget* target = nullptr); void UpdateInput(const float& DeltaTime); };
Akshat69/SFML-RPG
SFML-RPG/AnimationComponent.h
#pragma once #include "AudioComponent.h" class AnimationComponent { private: class Animation { public: bool done; float animationTimer; float timer; int width; int height; sf::Sprite& sprite; sf::Texture& textureSheet; sf::IntRect startRect, endRect, currentRect; const bool& Play(const float& DeltaTime, bool priority = false) { //UpdateTimer this->done = false; this->timer += 100.0f * DeltaTime; if (this->timer >= animationTimer) { //Reset Timer this->timer = 0.0f; //Animate if (this->currentRect != this->endRect) { this->currentRect.left += this->width; } else //Reset { this->currentRect.left = this->startRect.left; done = true; } this->sprite.setTextureRect(this->currentRect); } return done; } const bool& Play(const float& DeltaTime, float speed_percent, bool priority = false) { //UpdateTimer this->done = false; if (speed_percent < 0.5f) speed_percent = 0.5f; this->timer += speed_percent * 100.0f * DeltaTime; if (this->timer >= animationTimer) { //Reset Timer this->timer = 0.0f; //Animate if (this->currentRect != this->endRect) { this->currentRect.left += this->width; } else //Reset { this->currentRect.left = this->startRect.left; done = true; } this->sprite.setTextureRect(this->currentRect); } return done; } void Reset() { this->timer = 0.0f; this->currentRect = this->startRect; } const bool& isDone() { return this->done; } Animation( sf::Sprite& sprite, sf::Texture& textureSheet, float animationTimer, sf::Vector2i startFrameIndex, sf::Vector2i endFrameIndex, sf::Vector2i Dimensions, bool priority = false) : sprite(sprite), textureSheet(textureSheet), animationTimer(animationTimer) { //this->animationTimer = 0.0f; this->timer = 0.0f; this->done = false; this->width = Dimensions.x; this->height = Dimensions.y; this->startRect = sf::IntRect(startFrameIndex.x * this->width, startFrameIndex.y * this->height, this->width, this->height); this->endRect = sf::IntRect(endFrameIndex.x * this->width, endFrameIndex.y * this->height, this->width, this->height); this->currentRect = this->startRect; this->sprite.setTexture(this->textureSheet, true); this->sprite.setTextureRect(this->startRect); } ~Animation() { } }; sf::Sprite& sprite; sf::Texture& texture_sheet; std::map<std::string, Animation*> animations; Animation* lastAnimated; Animation* priorityAnimation; public: AnimationComponent(sf::Sprite& sprite, sf::Texture& texture_sheet); ~AnimationComponent(); const bool& isDone(const std::string key) { return this->animations[key]->isDone(); } void Play(const std::string key, const float& DeltaTime, const bool priority = false); void Play(const std::string key, const float& DeltaTime, float modifier, float modifier_max, const bool priority = false); void addAnimation(const std::string key, float animationTimer, sf::Vector2i startFrameIndex, sf::Vector2i endFrameIndex, sf::Vector2i Dimensions); };
Akshat69/SFML-RPG
SFML-RPG/EditorState.h
#include "SettingState.h" #include "Tile.h" #include "GUI.h" class EditorState : public State { private: sf::Font font; std::map<std::string, GUI::Button*> buttons; std::map<std::string, std::vector<Tile*>> tiles; void initFonts(); void initKeybinds(); void initButtons(); //void initComponents(); public: EditorState(sf::RenderWindow* window, std::map<std::string, int>* supportedKeys, std::stack<State*>* states); virtual ~EditorState(); //Functions void Update(const float DeltaTime); void UpdateButtons(); void Render(sf::RenderTarget* target = nullptr); void UpdateInput(const float& DeltaTime); void EndState(); };
Akshat69/SFML-RPG
SFML-RPG/SettingState.h
#pragma once #include "GameState.h" #include "GUI.h" class SettingState : public State { private: sf::RectangleShape background; sf::Texture backgroundTexture; sf::Font font; std::map<std::string, sf::Text*> settings; std::map<std::string, GUI::Button*> buttons; std::map<std::string, GUI::SlideBox*> sliderBoxes; //Functions void initFonts(); void initKeybinds(); void initGUI(); void initBackground(); void initComponents(); public: SettingState(sf::RenderWindow* window, std::map<std::string, int>* supportedKeys, std::stack<State*>* states); virtual ~SettingState(); //Functions void LoadTexture(std::string ImageLocation); void Update(const float DeltaTime); void UpdateButtons(); void Render(sf::RenderTarget* target = nullptr); void UpdateInput(const float& DeltaTime); };
Akshat69/SFML-RPG
SFML-RPG/HitboxComponent.h
#pragma once #include "stdafx.h" class HitboxComponent { private: sf::Sprite& sprite; sf::RectangleShape hitbox; sf::Vector2f offset; public: bool render = false; HitboxComponent(sf::Sprite& sprite, sf::Vector2f offset, sf::Vector2f size); ~HitboxComponent(); //Functions void Update(const float& DeltaTime); void Render(sf::RenderTarget* target); bool checkCollision(HitboxComponent* hitbox); friend sf::RectangleShape getHitbox(HitboxComponent* hitboxComponent) { return hitboxComponent->hitbox; } };
Akshat69/SFML-RPG
SFML-RPG/Game.h
#pragma once #include "MainMenuState.h" class Game { private: class GraphicsSettings { public: GraphicsSettings() { this->resolution = sf::VideoMode::getDesktopMode(); this->fullScreen = false; this->verticalSync = false; this->FrameRateLimit = 120.0; this->contextSettings.antialiasingLevel = 0; this->videoMode = sf::VideoMode::getFullscreenModes(); } //Variables sf::VideoMode resolution; bool fullScreen; bool verticalSync; unsigned FrameRateLimit; sf::ContextSettings contextSettings; std::vector<sf::VideoMode> videoMode; void saveToFile(const std::string path) { } void loadFromFile(const std::string path) { this->videoMode = sf::VideoMode::getFullscreenModes(); std::ifstream ifs(path); std::string title = "None"; sf::VideoMode window_bounds = sf::VideoMode::getDesktopMode(); unsigned frameRateLimit = 120; bool vertical_sync_enabled = false; unsigned antialiasing_level = 0; if (ifs.is_open()) //Open file if exists { std::getline(ifs, title); ifs >> window_bounds.width >> window_bounds.height; ifs >> this->fullScreen; ifs >> frameRateLimit; ifs >> vertical_sync_enabled; ifs >> antialiasing_level; } else std::cout << "File Does not exist"; ifs.close(); //close the file this->contextSettings.antialiasingLevel = antialiasing_level; } }; void UpdateDeltaTime(); sf::RenderWindow* window; int WindowWidth, WindowHeight; sf::Clock DeltaTimeClock; std::stack<State*> states; std::map<std::string, int> supportedKeys; GraphicsSettings gfxSettings; public: Game(); virtual ~Game(); //Functions virtual void Update(); virtual void Render(); virtual void Run(); virtual void UpdateSFMLEvents(); //Initializers void initVariables(); void initGraphicsSettings(); void initWindow(); void initStates(); void initKeys(const std::string KeysFile); //Updates virtual void UpdateStates(); //Variables float DeltaTime; };
Akshat69/SFML-RPG
SFML-RPG/State.h
#include "Character.h" class State { protected: sf::RenderWindow* window; std::map<std::string, sf::Texture> textures; std::map<std::string, int>* supportedKeys; std::map<std::string, int> keyBinds; std::stack<State*>* states; AudioComponent* audioComponent = nullptr; bool quit = false; float keytime; float keytimeMax; sf::Vector2i mousePosScreen; sf::Vector2i mousePosWindow; sf::Vector2f mousePosView; virtual void initKeybinds() = 0; public: State(sf::RenderWindow* window, std::map<std::string, int>* supportedKeys, std::stack<State*>* states); virtual ~State(); //Functions virtual void UpdateInput(const float& DeltaTime) = 0; virtual void Update(const float DeltaTime) = 0; virtual void UpdateKeytime(const float DeltaTime); virtual void UpdateMousePositions(const float DeltaTime); virtual void Render(sf::RenderTarget* target = nullptr) = 0; virtual void EndState(); const bool& getQuit() { return this->quit; } const bool getKeytime(); };
Akshat69/SFML-RPG
SFML-RPG/Character.h
#pragma once #include "Entity.h" class Character : public Entity { private: //Variables bool isAttacking; //Initializers void initVariables(); public: Character(float posX, float posY, sf::Texture* texture_sheet, sf::RenderWindow* window); ~Character(); //Functions void Update(const float& DeltaTime); void UpdateInput(std::map<std::string, int> keyBinds, const float& DeltaTime); void UpdateAnimation(const float& DeltaTime); void AttackAnimation(const float& DeltaTime); void MovementAnimation(const float& DeltaTime); };