repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
openssl
openssl-master/test/helpers/handshake_srp.c
/* * Copyright 2016-2022 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 */ /* * SRP is deprecated and there is no replacent. When SRP is removed, the code in * this file can be removed too. Until then we have to use the deprecated APIs. */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/srp.h> #include <openssl/ssl.h> #include "handshake.h" #include "../testutil.h" static char *client_srp_cb(SSL *s, void *arg) { CTX_DATA *ctx_data = (CTX_DATA*)(arg); return OPENSSL_strdup(ctx_data->srp_password); } static int server_srp_cb(SSL *s, int *ad, void *arg) { CTX_DATA *ctx_data = (CTX_DATA*)(arg); if (strcmp(ctx_data->srp_user, SSL_get_srp_username(s)) != 0) return SSL3_AL_FATAL; if (SSL_set_srp_server_param_pw(s, ctx_data->srp_user, ctx_data->srp_password, "2048" /* known group */) < 0) { *ad = SSL_AD_INTERNAL_ERROR; return SSL3_AL_FATAL; } return SSL_ERROR_NONE; } int configure_handshake_ctx_for_srp(SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx, const SSL_TEST_EXTRA_CONF *extra, CTX_DATA *server_ctx_data, CTX_DATA *server2_ctx_data, CTX_DATA *client_ctx_data) { if (extra->server.srp_user != NULL) { SSL_CTX_set_srp_username_callback(server_ctx, server_srp_cb); server_ctx_data->srp_user = OPENSSL_strdup(extra->server.srp_user); server_ctx_data->srp_password = OPENSSL_strdup(extra->server.srp_password); if (server_ctx_data->srp_user == NULL || server_ctx_data->srp_password == NULL) { OPENSSL_free(server_ctx_data->srp_user); OPENSSL_free(server_ctx_data->srp_password); server_ctx_data->srp_user = NULL; server_ctx_data->srp_password = NULL; return 0; } SSL_CTX_set_srp_cb_arg(server_ctx, server_ctx_data); } if (extra->server2.srp_user != NULL) { if (!TEST_ptr(server2_ctx)) return 0; SSL_CTX_set_srp_username_callback(server2_ctx, server_srp_cb); server2_ctx_data->srp_user = OPENSSL_strdup(extra->server2.srp_user); server2_ctx_data->srp_password = OPENSSL_strdup(extra->server2.srp_password); if (server2_ctx_data->srp_user == NULL || server2_ctx_data->srp_password == NULL) { OPENSSL_free(server2_ctx_data->srp_user); OPENSSL_free(server2_ctx_data->srp_password); server2_ctx_data->srp_user = NULL; server2_ctx_data->srp_password = NULL; return 0; } SSL_CTX_set_srp_cb_arg(server2_ctx, server2_ctx_data); } if (extra->client.srp_user != NULL) { if (!TEST_true(SSL_CTX_set_srp_username(client_ctx, extra->client.srp_user))) return 0; SSL_CTX_set_srp_client_pwd_callback(client_ctx, client_srp_cb); client_ctx_data->srp_password = OPENSSL_strdup(extra->client.srp_password); if (client_ctx_data->srp_password == NULL) return 0; SSL_CTX_set_srp_cb_arg(client_ctx, client_ctx_data); } return 1; }
3,585
39.75
91
c
openssl
openssl-master/test/helpers/pkcs12.c
/* * Copyright 2020-2021 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 <string.h> #include <stdlib.h> #include "internal/nelem.h" #include <openssl/pkcs12.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include "../testutil.h" #include "pkcs12.h" /* from the same directory */ /* Set this to > 0 write test data to file */ static int write_files = 0; static int legacy = 0; static OSSL_LIB_CTX *test_ctx = NULL; static const char *test_propq = NULL; /* ------------------------------------------------------------------------- * Local function declarations */ static int add_attributes(PKCS12_SAFEBAG *bag, const PKCS12_ATTR *attrs); static void generate_p12(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); static int write_p12(PKCS12 *p12, const char *outfile); static PKCS12 *from_bio_p12(BIO *bio, const PKCS12_ENC *mac); static PKCS12 *read_p12(const char *infile, const PKCS12_ENC *mac); static int check_p12_mac(PKCS12 *p12, const PKCS12_ENC *mac); static int check_asn1_string(const ASN1_TYPE *av, const char *txt); static int check_attrs(const STACK_OF(X509_ATTRIBUTE) *bag_attrs, const PKCS12_ATTR *attrs); /* -------------------------------------------------------------------------- * Global settings */ void PKCS12_helper_set_write_files(int enable) { write_files = enable; } void PKCS12_helper_set_legacy(int enable) { legacy = enable; } void PKCS12_helper_set_libctx(OSSL_LIB_CTX *libctx) { test_ctx = libctx; } void PKCS12_helper_set_propq(const char *propq) { test_propq = propq; } /* -------------------------------------------------------------------------- * Test data load functions */ static X509 *load_cert_asn1(const unsigned char *bytes, int len) { X509 *cert = NULL; cert = d2i_X509(NULL, &bytes, len); if (!TEST_ptr(cert)) goto err; err: return cert; } static EVP_PKEY *load_pkey_asn1(const unsigned char *bytes, int len) { EVP_PKEY *pkey = NULL; pkey = d2i_AutoPrivateKey(NULL, &bytes, len); if (!TEST_ptr(pkey)) goto err; err: return pkey; } /* ------------------------------------------------------------------------- * PKCS12 builder */ PKCS12_BUILDER *new_pkcs12_builder(const char *filename) { PKCS12_BUILDER *pb = OPENSSL_malloc(sizeof(PKCS12_BUILDER)); if (!TEST_ptr(pb)) return NULL; pb->filename = filename; pb->success = 1; return pb; } int end_pkcs12_builder(PKCS12_BUILDER *pb) { int result = pb->success; OPENSSL_free(pb); return result; } void start_pkcs12(PKCS12_BUILDER *pb) { pb->safes = NULL; } void end_pkcs12(PKCS12_BUILDER *pb) { if (!pb->success) return; generate_p12(pb, NULL); } void end_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { if (!pb->success) return; generate_p12(pb, mac); } /* Generate the PKCS12 encoding and write to memory bio */ static void generate_p12(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { PKCS12 *p12; EVP_MD *md = NULL; if (!pb->success) return; pb->p12bio = BIO_new(BIO_s_mem()); if (!TEST_ptr(pb->p12bio)) { pb->success = 0; return; } if (legacy) p12 = PKCS12_add_safes(pb->safes, 0); else p12 = PKCS12_add_safes_ex(pb->safes, 0, test_ctx, test_propq); if (!TEST_ptr(p12)) { pb->success = 0; goto err; } sk_PKCS7_pop_free(pb->safes, PKCS7_free); if (mac != NULL) { if (legacy) md = (EVP_MD *)EVP_get_digestbynid(mac->nid); else md = EVP_MD_fetch(test_ctx, OBJ_nid2sn(mac->nid), test_propq); if (!TEST_true(PKCS12_set_mac(p12, mac->pass, strlen(mac->pass), NULL, 0, mac->iter, md))) { pb->success = 0; goto err; } } i2d_PKCS12_bio(pb->p12bio, p12); /* Can write to file here for debug */ if (write_files) write_p12(p12, pb->filename); err: if (!legacy && md != NULL) EVP_MD_free(md); PKCS12_free(p12); } static int write_p12(PKCS12 *p12, const char *outfile) { int ret = 0; BIO *out = BIO_new_file(outfile, "w"); if (out == NULL) goto err; if (!TEST_int_eq(i2d_PKCS12_bio(out, p12), 1)) goto err; ret = 1; err: BIO_free(out); return ret; } static PKCS12 *from_bio_p12(BIO *bio, const PKCS12_ENC *mac) { PKCS12 *p12 = NULL; /* Supply a p12 with library context/propq to the d2i decoder*/ if (!legacy) { p12 = PKCS12_init_ex(NID_pkcs7_data, test_ctx, test_propq); if (!TEST_ptr(p12)) goto err; } p12 = d2i_PKCS12_bio(bio, &p12); BIO_free(bio); if (!TEST_ptr(p12)) goto err; if (mac == NULL) { if (!TEST_false(PKCS12_mac_present(p12))) goto err; } else { if (!check_p12_mac(p12, mac)) goto err; } return p12; err: PKCS12_free(p12); return NULL; } /* For use with existing files */ static PKCS12 *read_p12(const char *infile, const PKCS12_ENC *mac) { PKCS12 *p12 = NULL; BIO *in = BIO_new_file(infile, "r"); if (in == NULL) goto err; p12 = d2i_PKCS12_bio(in, NULL); BIO_free(in); if (!TEST_ptr(p12)) goto err; if (mac == NULL) { if (!TEST_false(PKCS12_mac_present(p12))) goto err; } else { if (!check_p12_mac(p12, mac)) goto err; } return p12; err: PKCS12_free(p12); return NULL; } static int check_p12_mac(PKCS12 *p12, const PKCS12_ENC *mac) { return TEST_true(PKCS12_mac_present(p12)) && TEST_true(PKCS12_verify_mac(p12, mac->pass, strlen(mac->pass))); } /* ------------------------------------------------------------------------- * PKCS7 content info builder */ void start_contentinfo(PKCS12_BUILDER *pb) { pb->bags = NULL; } void end_contentinfo(PKCS12_BUILDER *pb) { if (pb->success && pb->bags != NULL) { if (!TEST_true(PKCS12_add_safe(&pb->safes, pb->bags, -1, 0, NULL))) pb->success = 0; } sk_PKCS12_SAFEBAG_pop_free(pb->bags, PKCS12_SAFEBAG_free); pb->bags = NULL; } void end_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc) { if (pb->success && pb->bags != NULL) { if (legacy) { if (!TEST_true(PKCS12_add_safe(&pb->safes, pb->bags, enc->nid, enc->iter, enc->pass))) pb->success = 0; } else { if (!TEST_true(PKCS12_add_safe_ex(&pb->safes, pb->bags, enc->nid, enc->iter, enc->pass, test_ctx, test_propq))) pb->success = 0; } } sk_PKCS12_SAFEBAG_pop_free(pb->bags, PKCS12_SAFEBAG_free); pb->bags = NULL; } static STACK_OF(PKCS12_SAFEBAG) *decode_contentinfo(STACK_OF(PKCS7) *safes, int idx, const PKCS12_ENC *enc) { STACK_OF(PKCS12_SAFEBAG) *bags = NULL; int bagnid; PKCS7 *p7 = sk_PKCS7_value(safes, idx); if (!TEST_ptr(p7)) goto err; bagnid = OBJ_obj2nid(p7->type); if (enc) { if (!TEST_int_eq(bagnid, NID_pkcs7_encrypted)) goto err; bags = PKCS12_unpack_p7encdata(p7, enc->pass, strlen(enc->pass)); } else { if (!TEST_int_eq(bagnid, NID_pkcs7_data)) goto err; bags = PKCS12_unpack_p7data(p7); } if (!TEST_ptr(bags)) goto err; return bags; err: return NULL; } /* ------------------------------------------------------------------------- * PKCS12 safeBag/attribute builder */ static int add_attributes(PKCS12_SAFEBAG *bag, const PKCS12_ATTR *attr) { int ret = 0; int attr_nid; const PKCS12_ATTR *p_attr = attr; STACK_OF(X509_ATTRIBUTE)* attrs = NULL; X509_ATTRIBUTE *x509_attr = NULL; if (attr == NULL) return 1; while (p_attr->oid != NULL) { TEST_info("Adding attribute %s = %s", p_attr->oid, p_attr->value); attr_nid = OBJ_txt2nid(p_attr->oid); if (attr_nid == NID_friendlyName) { if (!TEST_true(PKCS12_add_friendlyname(bag, p_attr->value, -1))) goto err; } else if (attr_nid == NID_localKeyID) { if (!TEST_true(PKCS12_add_localkeyid(bag, (unsigned char *)p_attr->value, strlen(p_attr->value)))) goto err; } else if (attr_nid == NID_oracle_jdk_trustedkeyusage) { attrs = (STACK_OF(X509_ATTRIBUTE)*)PKCS12_SAFEBAG_get0_attrs(bag); x509_attr = X509_ATTRIBUTE_create(attr_nid, V_ASN1_OBJECT, OBJ_txt2obj(p_attr->value, 0)); X509at_add1_attr(&attrs, x509_attr); PKCS12_SAFEBAG_set0_attrs(bag, attrs); X509_ATTRIBUTE_free(x509_attr); } else { /* Custom attribute values limited to ASCII in these tests */ if (!TEST_true(PKCS12_add1_attr_by_txt(bag, p_attr->oid, MBSTRING_ASC, (unsigned char *)p_attr->value, strlen(p_attr->value)))) goto err; } p_attr++; } ret = 1; err: return ret; } void add_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs) { PKCS12_SAFEBAG *bag = NULL; X509 *cert = NULL; char *name; if (!pb->success) return; cert = load_cert_asn1(bytes, len); if (!TEST_ptr(cert)) { pb->success = 0; return; } name = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); TEST_info("Adding certificate <%s>", name); OPENSSL_free(name); bag = PKCS12_add_cert(&pb->bags, cert); if (!TEST_ptr(bag)) { pb->success = 0; goto err; } if (!TEST_true(add_attributes(bag, attrs))) { pb->success = 0; goto err; } err: X509_free(cert); } void add_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc) { PKCS12_SAFEBAG *bag = NULL; EVP_PKEY *pkey = NULL; if (!pb->success) return; TEST_info("Adding key"); pkey = load_pkey_asn1(bytes, len); if (!TEST_ptr(pkey)) { pb->success = 0; return; } if (legacy) bag = PKCS12_add_key(&pb->bags, pkey, 0 /*keytype*/, enc->iter, enc->nid, enc->pass); else bag = PKCS12_add_key_ex(&pb->bags, pkey, 0 /*keytype*/, enc->iter, enc->nid, enc->pass, test_ctx, test_propq); if (!TEST_ptr(bag)) { pb->success = 0; goto err; } if (!add_attributes(bag, attrs)) pb->success = 0; err: EVP_PKEY_free(pkey); } void add_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs) { PKCS12_SAFEBAG *bag = NULL; if (!pb->success) return; TEST_info("Adding secret <%s>", secret); bag = PKCS12_add_secret(&pb->bags, secret_nid, (const unsigned char *)secret, strlen(secret)); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!add_attributes(bag, attrs)) pb->success = 0; } /* ------------------------------------------------------------------------- * PKCS12 structure checking */ static int check_asn1_string(const ASN1_TYPE *av, const char *txt) { int ret = 0; char *value = NULL; if (!TEST_ptr(av)) goto err; switch (av->type) { case V_ASN1_BMPSTRING: value = OPENSSL_uni2asc(av->value.bmpstring->data, av->value.bmpstring->length); if (!TEST_str_eq(txt, (char *)value)) goto err; break; case V_ASN1_UTF8STRING: if (!TEST_mem_eq(txt, strlen(txt), (char *)av->value.utf8string->data, av->value.utf8string->length)) goto err; break; case V_ASN1_OCTET_STRING: if (!TEST_mem_eq(txt, strlen(txt), (char *)av->value.octet_string->data, av->value.octet_string->length)) goto err; break; default: /* Tests do not support other attribute types currently */ goto err; } ret = 1; err: OPENSSL_free(value); return ret; } static int check_attrs(const STACK_OF(X509_ATTRIBUTE) *bag_attrs, const PKCS12_ATTR *attrs) { int ret = 0; X509_ATTRIBUTE *attr; ASN1_TYPE *av; int i, j; char attr_txt[100]; for (i = 0; i < sk_X509_ATTRIBUTE_num(bag_attrs); i++) { const PKCS12_ATTR *p_attr = attrs; ASN1_OBJECT *attr_obj; attr = sk_X509_ATTRIBUTE_value(bag_attrs, i); attr_obj = X509_ATTRIBUTE_get0_object(attr); OBJ_obj2txt(attr_txt, 100, attr_obj, 0); while (p_attr->oid != NULL) { /* Find a matching attribute type */ if (strcmp(p_attr->oid, attr_txt) == 0) { if (!TEST_int_eq(X509_ATTRIBUTE_count(attr), 1)) goto err; for (j = 0; j < X509_ATTRIBUTE_count(attr); j++) { av = X509_ATTRIBUTE_get0_type(attr, j); if (!TEST_true(check_asn1_string(av, p_attr->value))) goto err; } break; } p_attr++; } } ret = 1; err: return ret; } void check_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs) { X509 *x509 = NULL; X509 *ref_x509 = NULL; const PKCS12_SAFEBAG *bag; if (!pb->success) return; bag = sk_PKCS12_SAFEBAG_value(pb->bags, pb->bag_idx++); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!check_attrs(PKCS12_SAFEBAG_get0_attrs(bag), attrs) || !TEST_int_eq(PKCS12_SAFEBAG_get_nid(bag), NID_certBag) || !TEST_int_eq(PKCS12_SAFEBAG_get_bag_nid(bag), NID_x509Certificate)) { pb->success = 0; return; } x509 = PKCS12_SAFEBAG_get1_cert(bag); if (!TEST_ptr(x509)) { pb->success = 0; goto err; } ref_x509 = load_cert_asn1(bytes, len); if (!TEST_false(X509_cmp(x509, ref_x509))) pb->success = 0; err: X509_free(x509); X509_free(ref_x509); } void check_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc) { EVP_PKEY *pkey = NULL; EVP_PKEY *ref_pkey = NULL; PKCS8_PRIV_KEY_INFO *p8; const PKCS8_PRIV_KEY_INFO *p8c; const PKCS12_SAFEBAG *bag; if (!pb->success) return; bag = sk_PKCS12_SAFEBAG_value(pb->bags, pb->bag_idx++); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!check_attrs(PKCS12_SAFEBAG_get0_attrs(bag), attrs)) { pb->success = 0; return; } switch (PKCS12_SAFEBAG_get_nid(bag)) { case NID_keyBag: p8c = PKCS12_SAFEBAG_get0_p8inf(bag); if (!TEST_ptr(pkey = EVP_PKCS82PKEY(p8c))) { pb->success = 0; goto err; } break; case NID_pkcs8ShroudedKeyBag: if (legacy) p8 = PKCS12_decrypt_skey(bag, enc->pass, strlen(enc->pass)); else p8 = PKCS12_decrypt_skey_ex(bag, enc->pass, strlen(enc->pass), test_ctx, test_propq); if (!TEST_ptr(p8)) { pb->success = 0; goto err; } if (!TEST_ptr(pkey = EVP_PKCS82PKEY(p8))) { PKCS8_PRIV_KEY_INFO_free(p8); pb->success = 0; goto err; } PKCS8_PRIV_KEY_INFO_free(p8); break; default: pb->success = 0; goto err; } /* PKEY compare returns 1 for match */ ref_pkey = load_pkey_asn1(bytes, len); if (!TEST_true(EVP_PKEY_eq(pkey, ref_pkey))) pb->success = 0; err: EVP_PKEY_free(pkey); EVP_PKEY_free(ref_pkey); } void check_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs) { const PKCS12_SAFEBAG *bag; if (!pb->success) return; bag = sk_PKCS12_SAFEBAG_value(pb->bags, pb->bag_idx++); if (!TEST_ptr(bag)) { pb->success = 0; return; } if (!check_attrs(PKCS12_SAFEBAG_get0_attrs(bag), attrs) || !TEST_int_eq(PKCS12_SAFEBAG_get_nid(bag), NID_secretBag) || !TEST_int_eq(PKCS12_SAFEBAG_get_bag_nid(bag), secret_nid) || !TEST_true(check_asn1_string(PKCS12_SAFEBAG_get0_bag_obj(bag), secret))) pb->success = 0; } void start_check_pkcs12(PKCS12_BUILDER *pb) { PKCS12 *p12; if (!pb->success) return; p12 = from_bio_p12(pb->p12bio, NULL); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void start_check_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { PKCS12 *p12; if (!pb->success) return; p12 = from_bio_p12(pb->p12bio, mac); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void start_check_pkcs12_file(PKCS12_BUILDER *pb) { PKCS12 *p12; if (!pb->success) return; p12 = read_p12(pb->filename, NULL); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void start_check_pkcs12_file_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac) { PKCS12 *p12; if (!pb->success) return; p12 = read_p12(pb->filename, mac); if (!TEST_ptr(p12)) { pb->success = 0; return; } pb->safes = PKCS12_unpack_authsafes(p12); if (!TEST_ptr(pb->safes)) pb->success = 0; pb->safe_idx = 0; PKCS12_free(p12); } void end_check_pkcs12(PKCS12_BUILDER *pb) { if (!pb->success) return; sk_PKCS7_pop_free(pb->safes, PKCS7_free); } void start_check_contentinfo(PKCS12_BUILDER *pb) { if (!pb->success) return; pb->bag_idx = 0; pb->bags = decode_contentinfo(pb->safes, pb->safe_idx++, NULL); if (!TEST_ptr(pb->bags)) { pb->success = 0; return; } TEST_info("Decoding %d bags", sk_PKCS12_SAFEBAG_num(pb->bags)); } void start_check_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc) { if (!pb->success) return; pb->bag_idx = 0; pb->bags = decode_contentinfo(pb->safes, pb->safe_idx++, enc); if (!TEST_ptr(pb->bags)) { pb->success = 0; return; } TEST_info("Decoding %d bags", sk_PKCS12_SAFEBAG_num(pb->bags)); } void end_check_contentinfo(PKCS12_BUILDER *pb) { if (!pb->success) return; if (!TEST_int_eq(sk_PKCS12_SAFEBAG_num(pb->bags), pb->bag_idx)) pb->success = 0; sk_PKCS12_SAFEBAG_pop_free(pb->bags, PKCS12_SAFEBAG_free); pb->bags = NULL; }
19,679
23.661654
107
c
openssl
openssl-master/test/helpers/pkcs12.h
/* * Copyright 2020-2021 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 <string.h> #include <stdlib.h> #include "internal/nelem.h" #include <openssl/pkcs12.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include "../testutil.h" /* ------------------------------------------------------------------------- * PKCS#12 Test structures */ /* Holds a set of Attributes */ typedef struct pkcs12_attr { char *oid; char *value; } PKCS12_ATTR; /* Holds encryption parameters */ typedef struct pkcs12_enc { int nid; const char *pass; int iter; } PKCS12_ENC; /* Set of variables required for constructing the PKCS#12 structure */ typedef struct pkcs12_builder { const char *filename; int success; BIO *p12bio; STACK_OF(PKCS7) *safes; int safe_idx; STACK_OF(PKCS12_SAFEBAG) *bags; int bag_idx; } PKCS12_BUILDER; /* ------------------------------------------------------------------------- * PKCS#12 Test function declarations */ /* Global settings */ void PKCS12_helper_set_write_files(int enable); void PKCS12_helper_set_legacy(int enable); void PKCS12_helper_set_libctx(OSSL_LIB_CTX *libctx); void PKCS12_helper_set_propq(const char *propq); /* Allocate and initialise a PKCS#12 builder object */ PKCS12_BUILDER *new_pkcs12_builder(const char *filename); /* Finalise and free the PKCS#12 builder object, returning the success/fail flag */ int end_pkcs12_builder(PKCS12_BUILDER *pb); /* Encode/build functions */ void start_pkcs12(PKCS12_BUILDER *pb); void end_pkcs12(PKCS12_BUILDER *pb); void end_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); void start_contentinfo(PKCS12_BUILDER *pb); void end_contentinfo(PKCS12_BUILDER *pb); void end_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc); void add_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs); void add_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc); void add_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs); void add_extra_attr(PKCS12_BUILDER *pb); /* Decode/check functions */ void start_check_pkcs12(PKCS12_BUILDER *pb); void start_check_pkcs12_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); void start_check_pkcs12_file(PKCS12_BUILDER *pb); void start_check_pkcs12_file_with_mac(PKCS12_BUILDER *pb, const PKCS12_ENC *mac); void end_check_pkcs12(PKCS12_BUILDER *pb); void start_check_contentinfo(PKCS12_BUILDER *pb); void start_check_contentinfo_encrypted(PKCS12_BUILDER *pb, const PKCS12_ENC *enc); void end_check_contentinfo(PKCS12_BUILDER *pb); void check_certbag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs); void check_keybag(PKCS12_BUILDER *pb, const unsigned char *bytes, int len, const PKCS12_ATTR *attrs, const PKCS12_ENC *enc); void check_secretbag(PKCS12_BUILDER *pb, int secret_nid, const char *secret, const PKCS12_ATTR *attrs);
3,440
31.771429
83
h
openssl
openssl-master/test/helpers/predefined_dhparams.c
/* * Copyright 1995-2022 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/core_names.h> #include <openssl/param_build.h> #include "predefined_dhparams.h" #ifndef OPENSSL_NO_DH static EVP_PKEY *get_dh_from_pg_bn(OSSL_LIB_CTX *libctx, const char *type, BIGNUM *p, BIGNUM *g, BIGNUM *q) { EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(libctx, type, NULL); OSSL_PARAM_BLD *tmpl = NULL; OSSL_PARAM *params = NULL; EVP_PKEY *dhpkey = NULL; if (pctx == NULL || EVP_PKEY_fromdata_init(pctx) <= 0) goto err; if ((tmpl = OSSL_PARAM_BLD_new()) == NULL || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g) || (q != NULL && !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q, q))) goto err; params = OSSL_PARAM_BLD_to_param(tmpl); if (params == NULL || EVP_PKEY_fromdata(pctx, &dhpkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) goto err; err: EVP_PKEY_CTX_free(pctx); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(tmpl); return dhpkey; } static EVP_PKEY *get_dh_from_pg(OSSL_LIB_CTX *libctx, const char *type, unsigned char *pdata, size_t plen, unsigned char *gdata, size_t glen, unsigned char *qdata, size_t qlen) { EVP_PKEY *dhpkey = NULL; BIGNUM *p = NULL, *g = NULL, *q = NULL; p = BN_bin2bn(pdata, plen, NULL); g = BN_bin2bn(gdata, glen, NULL); if (p == NULL || g == NULL) goto err; if (qdata != NULL && (q = BN_bin2bn(qdata, qlen, NULL)) == NULL) goto err; dhpkey = get_dh_from_pg_bn(libctx, type, p, g, q); err: BN_free(p); BN_free(g); BN_free(q); return dhpkey; } EVP_PKEY *get_dh512(OSSL_LIB_CTX *libctx) { static unsigned char dh512_p[] = { 0xCB, 0xC8, 0xE1, 0x86, 0xD0, 0x1F, 0x94, 0x17, 0xA6, 0x99, 0xF0, 0xC6, 0x1F, 0x0D, 0xAC, 0xB6, 0x25, 0x3E, 0x06, 0x39, 0xCA, 0x72, 0x04, 0xB0, 0x6E, 0xDA, 0xC0, 0x61, 0xE6, 0x7A, 0x77, 0x25, 0xE8, 0x3B, 0xB9, 0x5F, 0x9A, 0xB6, 0xB5, 0xFE, 0x99, 0x0B, 0xA1, 0x93, 0x4E, 0x35, 0x33, 0xB8, 0xE1, 0xF1, 0x13, 0x4F, 0x59, 0x1A, 0xD2, 0x57, 0xC0, 0x26, 0x21, 0x33, 0x02, 0xC5, 0xAE, 0x23, }; static unsigned char dh512_g[] = { 0x02, }; return get_dh_from_pg(libctx, "DH", dh512_p, sizeof(dh512_p), dh512_g, sizeof(dh512_g), NULL, 0); } EVP_PKEY *get_dhx512(OSSL_LIB_CTX *libctx) { static unsigned char dhx512_p[] = { 0x00, 0xe8, 0x1a, 0xb7, 0x9a, 0x02, 0x65, 0x64, 0x94, 0x7b, 0xba, 0x09, 0x1c, 0x12, 0x27, 0x1e, 0xea, 0x89, 0x32, 0x64, 0x78, 0xf8, 0x1c, 0x78, 0x8e, 0x96, 0xc3, 0xc6, 0x9f, 0x41, 0x05, 0x41, 0x65, 0xae, 0xe3, 0x05, 0xea, 0x66, 0x21, 0xf7, 0x38, 0xb7, 0x2b, 0x32, 0x40, 0x5a, 0x14, 0x86, 0x51, 0x94, 0xb1, 0xcf, 0x01, 0xe3, 0x27, 0x28, 0xf6, 0x75, 0xa3, 0x15, 0xbb, 0x12, 0x4d, 0x99, 0xe7, }; static unsigned char dhx512_g[] = { 0x00, 0x91, 0xc1, 0x43, 0x6d, 0x0d, 0xb0, 0xa4, 0xde, 0x41, 0xb7, 0x93, 0xad, 0x51, 0x94, 0x1b, 0x43, 0xd8, 0x42, 0xf1, 0x5e, 0x46, 0x83, 0x5d, 0xf1, 0xd1, 0xf0, 0x41, 0x10, 0xd1, 0x1c, 0x5e, 0xad, 0x9b, 0x68, 0xb1, 0x6f, 0xf5, 0x8e, 0xaa, 0x6d, 0x71, 0x88, 0x37, 0xdf, 0x05, 0xf7, 0x6e, 0x7a, 0xb4, 0x25, 0x10, 0x6c, 0x7f, 0x38, 0xb4, 0xc8, 0xfc, 0xcc, 0x0c, 0x6a, 0x02, 0x08, 0x61, 0xf6, }; static unsigned char dhx512_q[] = { 0x00, 0xdd, 0xf6, 0x35, 0xad, 0xfa, 0x70, 0xc7, 0xe7, 0xa8, 0xf0, 0xe3, 0xda, 0x79, 0x34, 0x3f, 0x5b, 0xcf, 0x73, 0x82, 0x91, }; return get_dh_from_pg(libctx, "X9.42 DH", dhx512_p, sizeof(dhx512_p), dhx512_g, sizeof(dhx512_g), dhx512_q, sizeof(dhx512_q)); } EVP_PKEY *get_dh1024dsa(OSSL_LIB_CTX *libctx) { static unsigned char dh1024_p[] = { 0xC8, 0x00, 0xF7, 0x08, 0x07, 0x89, 0x4D, 0x90, 0x53, 0xF3, 0xD5, 0x00, 0x21, 0x1B, 0xF7, 0x31, 0xA6, 0xA2, 0xDA, 0x23, 0x9A, 0xC7, 0x87, 0x19, 0x3B, 0x47, 0xB6, 0x8C, 0x04, 0x6F, 0xFF, 0xC6, 0x9B, 0xB8, 0x65, 0xD2, 0xC2, 0x5F, 0x31, 0x83, 0x4A, 0xA7, 0x5F, 0x2F, 0x88, 0x38, 0xB6, 0x55, 0xCF, 0xD9, 0x87, 0x6D, 0x6F, 0x9F, 0xDA, 0xAC, 0xA6, 0x48, 0xAF, 0xFC, 0x33, 0x84, 0x37, 0x5B, 0x82, 0x4A, 0x31, 0x5D, 0xE7, 0xBD, 0x52, 0x97, 0xA1, 0x77, 0xBF, 0x10, 0x9E, 0x37, 0xEA, 0x64, 0xFA, 0xCA, 0x28, 0x8D, 0x9D, 0x3B, 0xD2, 0x6E, 0x09, 0x5C, 0x68, 0xC7, 0x45, 0x90, 0xFD, 0xBB, 0x70, 0xC9, 0x3A, 0xBB, 0xDF, 0xD4, 0x21, 0x0F, 0xC4, 0x6A, 0x3C, 0xF6, 0x61, 0xCF, 0x3F, 0xD6, 0x13, 0xF1, 0x5F, 0xBC, 0xCF, 0xBC, 0x26, 0x9E, 0xBC, 0x0B, 0xBD, 0xAB, 0x5D, 0xC9, 0x54, 0x39, }; static unsigned char dh1024_g[] = { 0x3B, 0x40, 0x86, 0xE7, 0xF3, 0x6C, 0xDE, 0x67, 0x1C, 0xCC, 0x80, 0x05, 0x5A, 0xDF, 0xFE, 0xBD, 0x20, 0x27, 0x74, 0x6C, 0x24, 0xC9, 0x03, 0xF3, 0xE1, 0x8D, 0xC3, 0x7D, 0x98, 0x27, 0x40, 0x08, 0xB8, 0x8C, 0x6A, 0xE9, 0xBB, 0x1A, 0x3A, 0xD6, 0x86, 0x83, 0x5E, 0x72, 0x41, 0xCE, 0x85, 0x3C, 0xD2, 0xB3, 0xFC, 0x13, 0xCE, 0x37, 0x81, 0x9E, 0x4C, 0x1C, 0x7B, 0x65, 0xD3, 0xE6, 0xA6, 0x00, 0xF5, 0x5A, 0x95, 0x43, 0x5E, 0x81, 0xCF, 0x60, 0xA2, 0x23, 0xFC, 0x36, 0xA7, 0x5D, 0x7A, 0x4C, 0x06, 0x91, 0x6E, 0xF6, 0x57, 0xEE, 0x36, 0xCB, 0x06, 0xEA, 0xF5, 0x3D, 0x95, 0x49, 0xCB, 0xA7, 0xDD, 0x81, 0xDF, 0x80, 0x09, 0x4A, 0x97, 0x4D, 0xA8, 0x22, 0x72, 0xA1, 0x7F, 0xC4, 0x70, 0x56, 0x70, 0xE8, 0x20, 0x10, 0x18, 0x8F, 0x2E, 0x60, 0x07, 0xE7, 0x68, 0x1A, 0x82, 0x5D, 0x32, 0xA2, }; return get_dh_from_pg(libctx, "DH", dh1024_p, sizeof(dh1024_p), dh1024_g, sizeof(dh1024_g), NULL, 0); } EVP_PKEY *get_dh2048(OSSL_LIB_CTX *libctx) { BIGNUM *p = NULL, *g = NULL; EVP_PKEY *dhpkey = NULL; g = BN_new(); if (g == NULL || !BN_set_word(g, 2)) goto err; p = BN_get_rfc3526_prime_2048(NULL); if (p == NULL) goto err; dhpkey = get_dh_from_pg_bn(libctx, "DH", p, g, NULL); err: BN_free(p); BN_free(g); return dhpkey; } EVP_PKEY *get_dh4096(OSSL_LIB_CTX *libctx) { BIGNUM *p = NULL, *g = NULL; EVP_PKEY *dhpkey = NULL; g = BN_new(); if (g == NULL || !BN_set_word(g, 2)) goto err; p = BN_get_rfc3526_prime_4096(NULL); if (p == NULL) goto err; dhpkey = get_dh_from_pg_bn(libctx, "DH", p, g, NULL); err: BN_free(p); BN_free(g); return dhpkey; } #endif
7,062
35.220513
82
c
openssl
openssl-master/test/helpers/predefined_dhparams.h
/* * Copyright 1995-2022 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> #ifndef OPENSSL_NO_DH EVP_PKEY *get_dh512(OSSL_LIB_CTX *libctx); EVP_PKEY *get_dhx512(OSSL_LIB_CTX *libctx); EVP_PKEY *get_dh1024dsa(OSSL_LIB_CTX *libct); EVP_PKEY *get_dh2048(OSSL_LIB_CTX *libctx); EVP_PKEY *get_dh4096(OSSL_LIB_CTX *libctx); #endif
613
31.315789
74
h
openssl
openssl-master/test/helpers/quictestlib.h
/* * Copyright 2022 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/ssl.h> #include <internal/quic_tserver.h> /* Type to represent the Fault Injector */ typedef struct qtest_fault QTEST_FAULT; /* * Structure representing a parsed EncryptedExtension message. Listeners can * make changes to the contents of structure objects as required and the fault * injector will reconstruct the message to be sent on */ typedef struct qtest_fault_encrypted_extensions { /* EncryptedExtension messages just have an extensions block */ unsigned char *extensions; size_t extensionslen; } QTEST_ENCRYPTED_EXTENSIONS; /* Flags for use with qtest_create_quic_objects() */ /* Indicates whether we are using blocking mode or not */ #define QTEST_FLAG_BLOCK 1 /* Use fake time rather than real time */ #define QTEST_FLAG_FAKE_TIME 2 /* * Given an SSL_CTX for the client and filenames for the server certificate and * keyfile, create a server and client instances as well as a fault injector * instance. |flags| is the logical or of flags defined above, or 0 if none. */ int qtest_create_quic_objects(OSSL_LIB_CTX *libctx, SSL_CTX *clientctx, char *certfile, char *keyfile, int flags, QUIC_TSERVER **qtserv, SSL **cssl, QTEST_FAULT **fault); /* Where QTEST_FLAG_FAKE_TIME is used, add millis to the current time */ void qtest_add_time(uint64_t millis); QTEST_FAULT *qtest_create_injector(QUIC_TSERVER *ts); BIO_METHOD *qtest_get_bio_method(void); /* * Free up a Fault Injector instance */ void qtest_fault_free(QTEST_FAULT *fault); /* Returns 1 if the quictestlib supports blocking tests */ int qtest_supports_blocking(void); /* * Run the TLS handshake to create a QUIC connection between the client and * server. */ int qtest_create_quic_connection(QUIC_TSERVER *qtserv, SSL *clientssl); /* * Shutdown the client SSL object gracefully */ int qtest_shutdown(QUIC_TSERVER *qtserv, SSL *clientssl); /* * Confirm that the server has received the given transport error code. */ int qtest_check_server_transport_err(QUIC_TSERVER *qtserv, uint64_t code); /* * Confirm the server has received a protocol error. Equivalent to calling * qtest_check_server_transport_err with a code of QUIC_ERR_PROTOCOL_VIOLATION */ int qtest_check_server_protocol_err(QUIC_TSERVER *qtserv); /* * Confirm the server has received a frame encoding error. Equivalent to calling * qtest_check_server_transport_err with a code of QUIC_ERR_FRAME_ENCODING_ERROR */ int qtest_check_server_frame_encoding_err(QUIC_TSERVER *qtserv); /* * Enable tests to listen for pre-encryption QUIC packets being sent */ typedef int (*qtest_fault_on_packet_plain_cb)(QTEST_FAULT *fault, QUIC_PKT_HDR *hdr, unsigned char *buf, size_t len, void *cbarg); int qtest_fault_set_packet_plain_listener(QTEST_FAULT *fault, qtest_fault_on_packet_plain_cb pplaincb, void *pplaincbarg); /* * Helper function to be called from a packet_plain_listener callback if it * wants to resize the packet (either to add new data to it, or to truncate it). * The buf provided to packet_plain_listener is over allocated, so this just * changes the logical size and never changes the actual address of the buf. * This will fail if a large resize is attempted that exceeds the over * allocation. */ int qtest_fault_resize_plain_packet(QTEST_FAULT *fault, size_t newlen); /* * Prepend frame data into a packet. To be called from a packet_plain_listener * callback */ int qtest_fault_prepend_frame(QTEST_FAULT *fault, const unsigned char *frame, size_t frame_len); /* * The general handshake message listener is sent the entire handshake message * data block, including the handshake header itself */ typedef int (*qtest_fault_on_handshake_cb)(QTEST_FAULT *fault, unsigned char *msg, size_t msglen, void *handshakecbarg); int qtest_fault_set_handshake_listener(QTEST_FAULT *fault, qtest_fault_on_handshake_cb handshakecb, void *handshakecbarg); /* * Helper function to be called from a handshake_listener callback if it wants * to resize the handshake message (either to add new data to it, or to truncate * it). newlen must include the length of the handshake message header. The * handshake message buffer is over allocated, so this just changes the logical * size and never changes the actual address of the buf. * This will fail if a large resize is attempted that exceeds the over * allocation. */ int qtest_fault_resize_handshake(QTEST_FAULT *fault, size_t newlen); /* * TODO(QUIC): Add listeners for specific types of frame here. E.g. we might * expect to see an "ACK" frame listener which will be passed pre-parsed ack * data that can be modified as required. */ /* * Handshake message specific listeners. Unlike the general handshake message * listener these messages are pre-parsed and supplied with message specific * data and exclude the handshake header */ typedef int (*qtest_fault_on_enc_ext_cb)(QTEST_FAULT *fault, QTEST_ENCRYPTED_EXTENSIONS *ee, size_t eelen, void *encextcbarg); int qtest_fault_set_hand_enc_ext_listener(QTEST_FAULT *fault, qtest_fault_on_enc_ext_cb encextcb, void *encextcbarg); /* TODO(QUIC): Add listeners for other types of handshake message here */ /* * Helper function to be called from message specific listener callbacks. newlen * is the new length of the specific message excluding the handshake message * header. The buffers provided to the message specific listeners are over * allocated, so this just changes the logical size and never changes the actual * address of the buffer. This will fail if a large resize is attempted that * exceeds the over allocation. */ int qtest_fault_resize_message(QTEST_FAULT *fault, size_t newlen); /* * Helper function to delete an extension from an extension block. |exttype| is * the type of the extension to be deleted. |ext| points to the extension block. * On entry |*extlen| contains the length of the extension block. It is updated * with the new length on exit. */ int qtest_fault_delete_extension(QTEST_FAULT *fault, unsigned int exttype, unsigned char *ext, size_t *extlen); /* * TODO(QUIC): Add additional helper functions for querying extensions here (e.g. * finding or adding them). We could also provide a "listener" API for listening * for specific extension types */ /* * Enable tests to listen for post-encryption QUIC packets being sent */ typedef int (*qtest_fault_on_packet_cipher_cb)(QTEST_FAULT *fault, /* The parsed packet header */ QUIC_PKT_HDR *hdr, /* The packet payload data */ unsigned char *buf, /* Length of the payload */ size_t len, void *cbarg); int qtest_fault_set_packet_cipher_listener(QTEST_FAULT *fault, qtest_fault_on_packet_cipher_cb pciphercb, void *picphercbarg); /* * Enable tests to listen for datagrams being sent */ typedef int (*qtest_fault_on_datagram_cb)(QTEST_FAULT *fault, BIO_MSG *m, size_t stride, void *cbarg); int qtest_fault_set_datagram_listener(QTEST_FAULT *fault, qtest_fault_on_datagram_cb datagramcb, void *datagramcbarg); /* * To be called from a datagram_listener callback. The datagram buffer is over * allocated, so this just changes the logical size and never changes the actual * address of the buffer. This will fail if a large resize is attempted that * exceeds the over allocation. */ int qtest_fault_resize_datagram(QTEST_FAULT *fault, size_t newlen);
9,107
39.300885
85
h
openssl
openssl-master/test/helpers/ssl_test_ctx.h
/* * Copyright 2016-2021 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_TEST_SSL_TEST_CTX_H #define OSSL_TEST_SSL_TEST_CTX_H #include <openssl/conf.h> #include <openssl/ssl.h> typedef enum { SSL_TEST_SUCCESS = 0, /* Default */ SSL_TEST_SERVER_FAIL, SSL_TEST_CLIENT_FAIL, SSL_TEST_INTERNAL_ERROR, /* Couldn't test resumption/renegotiation: original handshake failed. */ SSL_TEST_FIRST_HANDSHAKE_FAILED } ssl_test_result_t; typedef enum { SSL_TEST_VERIFY_NONE = 0, /* Default */ SSL_TEST_VERIFY_ACCEPT_ALL, SSL_TEST_VERIFY_RETRY_ONCE, SSL_TEST_VERIFY_REJECT_ALL } ssl_verify_callback_t; typedef enum { SSL_TEST_SERVERNAME_NONE = 0, /* Default */ SSL_TEST_SERVERNAME_SERVER1, SSL_TEST_SERVERNAME_SERVER2, SSL_TEST_SERVERNAME_INVALID } ssl_servername_t; typedef enum { SSL_TEST_SERVERNAME_CB_NONE = 0, /* Default */ SSL_TEST_SERVERNAME_IGNORE_MISMATCH, SSL_TEST_SERVERNAME_REJECT_MISMATCH, SSL_TEST_SERVERNAME_CLIENT_HELLO_IGNORE_MISMATCH, SSL_TEST_SERVERNAME_CLIENT_HELLO_REJECT_MISMATCH, SSL_TEST_SERVERNAME_CLIENT_HELLO_NO_V12 } ssl_servername_callback_t; typedef enum { SSL_TEST_SESSION_TICKET_IGNORE = 0, /* Default */ SSL_TEST_SESSION_TICKET_YES, SSL_TEST_SESSION_TICKET_NO, SSL_TEST_SESSION_TICKET_BROKEN /* Special test */ } ssl_session_ticket_t; typedef enum { SSL_TEST_COMPRESSION_NO = 0, /* Default */ SSL_TEST_COMPRESSION_YES } ssl_compression_t; typedef enum { SSL_TEST_SESSION_ID_IGNORE = 0, /* Default */ SSL_TEST_SESSION_ID_YES, SSL_TEST_SESSION_ID_NO } ssl_session_id_t; typedef enum { SSL_TEST_METHOD_TLS = 0, /* Default */ SSL_TEST_METHOD_DTLS, SSL_TEST_METHOD_QUIC } ssl_test_method_t; typedef enum { SSL_TEST_HANDSHAKE_SIMPLE = 0, /* Default */ SSL_TEST_HANDSHAKE_RESUME, SSL_TEST_HANDSHAKE_RENEG_SERVER, SSL_TEST_HANDSHAKE_RENEG_CLIENT, SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER, SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT, SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH } ssl_handshake_mode_t; typedef enum { SSL_TEST_CT_VALIDATION_NONE = 0, /* Default */ SSL_TEST_CT_VALIDATION_PERMISSIVE, SSL_TEST_CT_VALIDATION_STRICT } ssl_ct_validation_t; typedef enum { SSL_TEST_CERT_STATUS_NONE = 0, /* Default */ SSL_TEST_CERT_STATUS_GOOD_RESPONSE, SSL_TEST_CERT_STATUS_BAD_RESPONSE } ssl_cert_status_t; /* * Server/client settings that aren't supported by the SSL CONF library, * such as callbacks. */ typedef struct { /* One of a number of predefined custom callbacks. */ ssl_verify_callback_t verify_callback; /* One of a number of predefined server names use by the client */ ssl_servername_t servername; /* Maximum Fragment Length extension mode */ int max_fragment_len_mode; /* Supported NPN and ALPN protocols. A comma-separated list. */ char *npn_protocols; char *alpn_protocols; ssl_ct_validation_t ct_validation; /* Ciphersuites to set on a renegotiation */ char *reneg_ciphers; char *srp_user; char *srp_password; /* PHA enabled */ int enable_pha; /* Do not send extms on renegotiation */ int no_extms_on_reneg; } SSL_TEST_CLIENT_CONF; typedef struct { /* SNI callback (server-side). */ ssl_servername_callback_t servername_callback; /* Supported NPN and ALPN protocols. A comma-separated list. */ char *npn_protocols; char *alpn_protocols; /* Whether to set a broken session ticket callback. */ int broken_session_ticket; /* Should we send a CertStatus message? */ ssl_cert_status_t cert_status; /* An SRP user known to the server. */ char *srp_user; char *srp_password; /* Forced PHA */ int force_pha; char *session_ticket_app_data; } SSL_TEST_SERVER_CONF; typedef struct { SSL_TEST_CLIENT_CONF client; SSL_TEST_SERVER_CONF server; SSL_TEST_SERVER_CONF server2; } SSL_TEST_EXTRA_CONF; typedef struct { /* * Global test configuration. Does not change between handshakes. */ /* Whether the server/client CTX should use DTLS or TLS. */ ssl_test_method_t method; /* Whether to test a resumed/renegotiated handshake. */ ssl_handshake_mode_t handshake_mode; /* * How much application data to exchange (default is 256 bytes). * Both peers will send |app_data_size| bytes interleaved. */ int app_data_size; /* Maximum send fragment size. */ int max_fragment_size; /* KeyUpdate type */ int key_update_type; /* * Extra server/client configurations. Per-handshake. */ /* First handshake. */ SSL_TEST_EXTRA_CONF extra; /* Resumed handshake. */ SSL_TEST_EXTRA_CONF resume_extra; /* * Test expectations. These apply to the LAST handshake. */ /* Defaults to SUCCESS. */ ssl_test_result_t expected_result; /* Alerts. 0 if no expectation. */ /* See ssl.h for alert codes. */ /* Alert sent by the client / received by the server. */ int expected_client_alert; /* Alert sent by the server / received by the client. */ int expected_server_alert; /* Negotiated protocol version. 0 if no expectation. */ /* See ssl.h for protocol versions. */ int expected_protocol; /* * The expected SNI context to use. * We test server-side that the server switched to the expected context. * Set by the callback upon success, so if the callback wasn't called or * terminated with an alert, the servername will match with * SSL_TEST_SERVERNAME_NONE. * Note: in the event that the servername was accepted, the client should * also receive an empty SNI extension back but we have no way of probing * client-side via the API that this was the case. */ ssl_servername_t expected_servername; ssl_session_ticket_t session_ticket_expected; int compression_expected; /* The expected NPN/ALPN protocol to negotiate. */ char *expected_npn_protocol; char *expected_alpn_protocol; /* Whether the second handshake is resumed or a full handshake (boolean). */ int resumption_expected; /* Expected temporary key type */ int expected_tmp_key_type; /* Expected server certificate key type */ int expected_server_cert_type; /* Expected server signing hash */ int expected_server_sign_hash; /* Expected server signature type */ int expected_server_sign_type; /* Expected server CA names */ STACK_OF(X509_NAME) *expected_server_ca_names; /* Expected client certificate key type */ int expected_client_cert_type; /* Expected client signing hash */ int expected_client_sign_hash; /* Expected client signature type */ int expected_client_sign_type; /* Expected CA names for client auth */ STACK_OF(X509_NAME) *expected_client_ca_names; /* Whether to use SCTP for the transport */ int use_sctp; /* Whether to pre-compress server certificates */ int compress_certificates; /* Enable SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG on client side */ int enable_client_sctp_label_bug; /* Enable SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG on server side */ int enable_server_sctp_label_bug; /* Whether to expect a session id from the server */ ssl_session_id_t session_id_expected; char *expected_cipher; /* Expected Session Ticket Application Data */ char *expected_session_ticket_app_data; OSSL_LIB_CTX *libctx; /* FIPS version string to check for compatibility */ char *fips_version; } SSL_TEST_CTX; const char *ssl_test_result_name(ssl_test_result_t result); const char *ssl_alert_name(int alert); const char *ssl_protocol_name(int protocol); const char *ssl_verify_callback_name(ssl_verify_callback_t verify_callback); const char *ssl_servername_name(ssl_servername_t server); const char *ssl_servername_callback_name(ssl_servername_callback_t servername_callback); const char *ssl_session_ticket_name(ssl_session_ticket_t server); const char *ssl_session_id_name(ssl_session_id_t server); const char *ssl_test_method_name(ssl_test_method_t method); const char *ssl_handshake_mode_name(ssl_handshake_mode_t mode); const char *ssl_ct_validation_name(ssl_ct_validation_t mode); const char *ssl_certstatus_name(ssl_cert_status_t cert_status); const char *ssl_max_fragment_len_name(int MFL_mode); /* * Load the test case context from |conf|. * See test/README.ssltest.md for details on the conf file format. */ SSL_TEST_CTX *SSL_TEST_CTX_create(const CONF *conf, const char *test_section, OSSL_LIB_CTX *libctx); SSL_TEST_CTX *SSL_TEST_CTX_new(OSSL_LIB_CTX *libctx); void SSL_TEST_CTX_free(SSL_TEST_CTX *ctx); #endif /* OSSL_TEST_SSL_TEST_CTX_H */
9,053
33.037594
80
h
openssl
openssl-master/test/helpers/ssltestlib.h
/* * Copyright 2016-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 */ #ifndef OSSL_TEST_SSLTESTLIB_H # define OSSL_TEST_SSLTESTLIB_H # include <openssl/ssl.h> int create_ssl_ctx_pair(OSSL_LIB_CTX *libctx, const SSL_METHOD *sm, const SSL_METHOD *cm, int min_proto_version, int max_proto_version, SSL_CTX **sctx, SSL_CTX **cctx, char *certfile, char *privkeyfile); int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl, SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio); int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want, int read, int listen); int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl, SSL **cssl, int sfd, int cfd); int wait_until_sock_readable(int sock); int create_test_sockets(int *cfdp, int *sfdp, int socktype, BIO_ADDR *saddr); int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want); void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl); /* Note: Not thread safe! */ const BIO_METHOD *bio_f_tls_dump_filter(void); void bio_f_tls_dump_filter_free(void); const BIO_METHOD *bio_s_mempacket_test(void); void bio_s_mempacket_test_free(void); const BIO_METHOD *bio_s_always_retry(void); void bio_s_always_retry_free(void); void set_always_retry_err_val(int err); /* Packet types - value 0 is reserved */ #define INJECT_PACKET 1 #define INJECT_PACKET_IGNORE_REC_SEQ 2 /* * Mempacket BIO ctrls. We make them large enough to not clash with standard BIO * ctrl codes. */ #define MEMPACKET_CTRL_SET_DROP_EPOCH (1 << 15) #define MEMPACKET_CTRL_SET_DROP_REC (2 << 15) #define MEMPACKET_CTRL_GET_DROP_REC (3 << 15) #define MEMPACKET_CTRL_SET_DUPLICATE_REC (4 << 15) int mempacket_swap_epoch(BIO *bio); int mempacket_move_packet(BIO *bio, int d, int s); int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum, int type); typedef struct mempacket_st MEMPACKET; DEFINE_STACK_OF(MEMPACKET) #endif /* OSSL_TEST_SSLTESTLIB_H */
2,428
36.953125
80
h
openssl
openssl-master/test/testutil/apps_shims.c
/* * Copyright 2019-2021 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 "apps.h" #include "../testutil.h" /* shim that avoids sucking in too much from apps/apps.c */ void *app_malloc(size_t sz, const char *what) { void *vp; /* * This isn't ideal but it is what the app's app_malloc() does on failure. * Instead of exiting with a failure, abort() is called which makes sure * that there will be a good stack trace for debugging purposes. */ if (!TEST_ptr(vp = OPENSSL_malloc(sz))) { TEST_info("Could not allocate %zu bytes for %s\n", sz, what); abort(); } return vp; } /* shim to prevent sucking in too much from apps */ int opt_legacy_okay(void) { return 1; } /* * These three functions are defined here so that they don't need to come from * the apps source code and pull in a lot of additional things. */ int opt_provider_option_given(void) { return 0; } const char *app_get0_propq(void) { return NULL; } OSSL_LIB_CTX *app_get0_libctx(void) { return NULL; }
1,337
22.473684
78
c
openssl
openssl-master/test/testutil/driver.c
/* * Copyright 2016-2021 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 "../testutil.h" #include "output.h" #include "tu_local.h" #include <string.h> #include <assert.h> #include "internal/nelem.h" #include <openssl/bio.h> #include "platform.h" /* From libapps */ #if defined(_WIN32) && !defined(__BORLANDC__) # define strdup _strdup #endif /* * Declares the structures needed to register each test case function. */ typedef struct test_info { const char *test_case_name; int (*test_fn) (void); int (*param_test_fn)(int idx); int num; /* flags */ int subtest:1; } TEST_INFO; static TEST_INFO all_tests[1024]; static int num_tests = 0; static int show_list = 0; static int single_test = -1; static int single_iter = -1; static int level = 0; static int seed = 0; static int rand_order = 0; /* * A parameterised test runs a loop of test cases. * |num_test_cases| counts the total number of non-subtest test cases * across all tests. */ static int num_test_cases = 0; static int process_shared_options(void); void add_test(const char *test_case_name, int (*test_fn) (void)) { assert(num_tests != OSSL_NELEM(all_tests)); all_tests[num_tests].test_case_name = test_case_name; all_tests[num_tests].test_fn = test_fn; all_tests[num_tests].num = -1; ++num_tests; ++num_test_cases; } void add_all_tests(const char *test_case_name, int(*test_fn)(int idx), int num, int subtest) { assert(num_tests != OSSL_NELEM(all_tests)); all_tests[num_tests].test_case_name = test_case_name; all_tests[num_tests].param_test_fn = test_fn; all_tests[num_tests].num = num; all_tests[num_tests].subtest = subtest; ++num_tests; if (subtest) ++num_test_cases; else num_test_cases += num; } static int gcd(int a, int b) { while (b != 0) { int t = b; b = a % b; a = t; } return a; } static void set_seed(int s) { seed = s; if (seed <= 0) seed = (int)time(NULL); test_random_seed(seed); } int setup_test_framework(int argc, char *argv[]) { char *test_seed = getenv("OPENSSL_TEST_RAND_ORDER"); char *TAP_levels = getenv("HARNESS_OSSL_LEVEL"); if (TAP_levels != NULL) level = 4 * atoi(TAP_levels); test_adjust_streams_tap_level(level); if (test_seed != NULL) { rand_order = 1; set_seed(atoi(test_seed)); } else { set_seed(0); } #if defined(OPENSSL_SYS_VMS) && defined(__DECC) argv = copy_argv(&argc, argv); #elif defined(_WIN32) /* * Replace argv[] with UTF-8 encoded strings. */ win32_utf8argv(&argc, &argv); #endif if (!opt_init(argc, argv, test_get_options())) return 0; return 1; } /* * This can only be called after setup() has run, since num_tests and * all_tests[] are setup at this point */ static int check_single_test_params(char *name, char *testname, char *itname) { if (name != NULL) { int i; for (i = 0; i < num_tests; ++i) { if (strcmp(name, all_tests[i].test_case_name) == 0) { single_test = 1 + i; break; } } if (i >= num_tests) single_test = atoi(name); } /* if only iteration is specified, assume we want the first test */ if (single_test == -1 && single_iter != -1) single_test = 1; if (single_test != -1) { if (single_test < 1 || single_test > num_tests) { test_printf_stderr("Invalid -%s value " "(Value must be a valid test name OR a value between %d..%d)\n", testname, 1, num_tests); return 0; } } if (single_iter != -1) { if (all_tests[single_test - 1].num == -1) { test_printf_stderr("-%s option is not valid for test %d:%s\n", itname, single_test, all_tests[single_test - 1].test_case_name); return 0; } else if (single_iter < 1 || single_iter > all_tests[single_test - 1].num) { test_printf_stderr("Invalid -%s value for test %d:%s\t" "(Value must be in the range %d..%d)\n", itname, single_test, all_tests[single_test - 1].test_case_name, 1, all_tests[single_test - 1].num); return 0; } } return 1; } static int process_shared_options(void) { OPTION_CHOICE_DEFAULT o; int value; int ret = -1; char *flag_test = ""; char *flag_iter = ""; char *testname = NULL; opt_begin(); while ((o = opt_next()) != OPT_EOF) { switch (o) { /* Ignore any test options at this level */ default: break; case OPT_ERR: return ret; case OPT_TEST_HELP: opt_help(test_get_options()); return 0; case OPT_TEST_LIST: show_list = 1; break; case OPT_TEST_SINGLE: flag_test = opt_flag(); testname = opt_arg(); break; case OPT_TEST_ITERATION: flag_iter = opt_flag(); if (!opt_int(opt_arg(), &single_iter)) goto end; break; case OPT_TEST_INDENT: if (!opt_int(opt_arg(), &value)) goto end; level = 4 * value; test_adjust_streams_tap_level(level); break; case OPT_TEST_SEED: if (!opt_int(opt_arg(), &value)) goto end; set_seed(value); break; } } if (!check_single_test_params(testname, flag_test, flag_iter)) goto end; ret = 1; end: return ret; } int pulldown_test_framework(int ret) { set_test_title(NULL); return ret; } static void finalize(int success) { if (success) ERR_clear_error(); else ERR_print_errors_cb(openssl_error_cb, NULL); } static char *test_title = NULL; void set_test_title(const char *title) { free(test_title); test_title = title == NULL ? NULL : strdup(title); } PRINTF_FORMAT(2, 3) static void test_verdict(int verdict, const char *description, ...) { va_list ap; test_flush_stdout(); test_flush_stderr(); if (verdict == 0 && seed != 0) test_printf_tapout("# OPENSSL_TEST_RAND_ORDER=%d\n", seed); test_printf_tapout("%s ", verdict != 0 ? "ok" : "not ok"); va_start(ap, description); test_vprintf_tapout(description, ap); va_end(ap); if (verdict == TEST_SKIP_CODE) test_printf_tapout(" # skipped"); test_printf_tapout("\n"); test_flush_tapout(); } int run_tests(const char *test_prog_name) { int num_failed = 0; int verdict = 1; int ii, i, jj, j, jstep; int test_case_count = 0; int subtest_case_count = 0; int permute[OSSL_NELEM(all_tests)]; i = process_shared_options(); if (i == 0) return EXIT_SUCCESS; if (i == -1) return EXIT_FAILURE; if (num_tests < 1) { test_printf_tapout("1..0 # Skipped: %s\n", test_prog_name); } else if (show_list == 0 && single_test == -1) { if (level > 0) { test_printf_stdout("Subtest: %s\n", test_prog_name); test_flush_stdout(); } test_printf_tapout("1..%d\n", num_test_cases); } test_flush_tapout(); for (i = 0; i < num_tests; i++) permute[i] = i; if (rand_order != 0) for (i = num_tests - 1; i >= 1; i--) { j = test_random() % (1 + i); ii = permute[j]; permute[j] = permute[i]; permute[i] = ii; } for (ii = 0; ii != num_tests; ++ii) { i = permute[ii]; if (single_test != -1 && ((i+1) != single_test)) { continue; } else if (show_list) { if (all_tests[i].num != -1) { test_printf_tapout("%d - %s (%d..%d)\n", ii + 1, all_tests[i].test_case_name, 1, all_tests[i].num); } else { test_printf_tapout("%d - %s\n", ii + 1, all_tests[i].test_case_name); } test_flush_tapout(); } else if (all_tests[i].num == -1) { set_test_title(all_tests[i].test_case_name); ERR_clear_error(); verdict = all_tests[i].test_fn(); finalize(verdict != 0); test_verdict(verdict, "%d - %s", test_case_count + 1, test_title); if (verdict == 0) num_failed++; test_case_count++; } else { verdict = TEST_SKIP_CODE; set_test_title(all_tests[i].test_case_name); if (all_tests[i].subtest) { level += 4; test_adjust_streams_tap_level(level); if (single_iter == -1) { test_printf_stdout("Subtest: %s\n", test_title); test_printf_tapout("%d..%d\n", 1, all_tests[i].num); test_flush_stdout(); test_flush_tapout(); } } j = -1; if (rand_order == 0 || all_tests[i].num < 3) jstep = 1; else do jstep = test_random() % all_tests[i].num; while (jstep == 0 || gcd(all_tests[i].num, jstep) != 1); for (jj = 0; jj < all_tests[i].num; jj++) { int v; j = (j + jstep) % all_tests[i].num; if (single_iter != -1 && ((jj + 1) != single_iter)) continue; ERR_clear_error(); v = all_tests[i].param_test_fn(j); if (v == 0) { verdict = 0; } else if (v != TEST_SKIP_CODE && verdict != 0) { verdict = 1; } finalize(v != 0); if (all_tests[i].subtest) test_verdict(v, "%d - iteration %d", subtest_case_count + 1, j + 1); else test_verdict(v, "%d - %s - iteration %d", test_case_count + subtest_case_count + 1, test_title, j + 1); subtest_case_count++; } if (all_tests[i].subtest) { level -= 4; test_adjust_streams_tap_level(level); } if (verdict == 0) ++num_failed; if (all_tests[i].num == -1 || all_tests[i].subtest) test_verdict(verdict, "%d - %s", test_case_count + 1, all_tests[i].test_case_name); test_case_count++; } } if (num_failed != 0) return EXIT_FAILURE; return EXIT_SUCCESS; } /* * Glue an array of strings together and return it as an allocated string. * Optionally return the whole length of this string in |out_len| */ char *glue_strings(const char *list[], size_t *out_len) { size_t len = 0; char *p, *ret; int i; for (i = 0; list[i] != NULL; i++) len += strlen(list[i]); if (out_len != NULL) *out_len = len; if (!TEST_ptr(ret = p = OPENSSL_malloc(len + 1))) return NULL; for (i = 0; list[i] != NULL; i++) p += strlen(strcpy(p, list[i])); return ret; } char *test_mk_file_path(const char *dir, const char *file) { # ifndef OPENSSL_SYS_VMS const char *sep = "/"; # else const char *sep = ""; char *dir_end; char dir_end_sep; # endif size_t dirlen = dir != NULL ? strlen(dir) : 0; size_t len = dirlen + strlen(sep) + strlen(file) + 1; char *full_file = OPENSSL_zalloc(len); if (full_file != NULL) { if (dir != NULL && dirlen > 0) { OPENSSL_strlcpy(full_file, dir, len); # ifdef OPENSSL_SYS_VMS /* * If |file| contains a directory spec, we need to do some * careful merging. * "vol:[dir.dir]" + "[.certs]sm2-root.crt" should become * "vol:[dir.dir.certs]sm2-root.crt" */ dir_end = &full_file[strlen(full_file) - 1]; dir_end_sep = *dir_end; if ((dir_end_sep == ']' || dir_end_sep == '>') && (file[0] == '[' || file[0] == '<')) { file++; if (file[0] == '.') *dir_end = '\0'; else *dir_end = '.'; } #else OPENSSL_strlcat(full_file, sep, len); #endif } OPENSSL_strlcat(full_file, file, len); } return full_file; }
13,246
26.947257
95
c
openssl
openssl-master/test/testutil/fake_random.c
/* * Copyright 2021 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 may obtain a copy of the License at * https://www.openssl.org/source/license.html * or in the file LICENSE in the source distribution. */ #include <string.h> #include <openssl/core_names.h> #include <openssl/rand.h> #include <openssl/provider.h> #include "../include/crypto/evp.h" #include "../../crypto/evp/evp_local.h" #include "../testutil.h" typedef struct { fake_random_generate_cb *cb; int state; const char *name; EVP_RAND_CTX *ctx; } FAKE_RAND; static OSSL_FUNC_rand_newctx_fn fake_rand_newctx; static OSSL_FUNC_rand_freectx_fn fake_rand_freectx; static OSSL_FUNC_rand_instantiate_fn fake_rand_instantiate; static OSSL_FUNC_rand_uninstantiate_fn fake_rand_uninstantiate; static OSSL_FUNC_rand_generate_fn fake_rand_generate; static OSSL_FUNC_rand_gettable_ctx_params_fn fake_rand_gettable_ctx_params; static OSSL_FUNC_rand_get_ctx_params_fn fake_rand_get_ctx_params; static OSSL_FUNC_rand_enable_locking_fn fake_rand_enable_locking; static void *fake_rand_newctx(void *provctx, void *parent, const OSSL_DISPATCH *parent_dispatch) { FAKE_RAND *r = OPENSSL_zalloc(sizeof(*r)); if (r != NULL) r->state = EVP_RAND_STATE_UNINITIALISED; return r; } static void fake_rand_freectx(void *vrng) { OPENSSL_free(vrng); } static int fake_rand_instantiate(void *vrng, ossl_unused unsigned int strength, ossl_unused int prediction_resistance, ossl_unused const unsigned char *pstr, size_t pstr_len, ossl_unused const OSSL_PARAM params[]) { FAKE_RAND *frng = (FAKE_RAND *)vrng; frng->state = EVP_RAND_STATE_READY; return 1; } static int fake_rand_uninstantiate(void *vrng) { FAKE_RAND *frng = (FAKE_RAND *)vrng; frng->state = EVP_RAND_STATE_UNINITIALISED; return 1; } static int fake_rand_generate(void *vrng, unsigned char *out, size_t outlen, unsigned int strength, int prediction_resistance, const unsigned char *adin, size_t adinlen) { FAKE_RAND *frng = (FAKE_RAND *)vrng; size_t l; uint32_t r; if (frng->cb != NULL) return (*frng->cb)(out, outlen, frng->name, frng->ctx); while (outlen > 0) { r = test_random(); l = outlen < sizeof(r) ? outlen : sizeof(r); memcpy(out, &r, l); out += l; outlen -= l; } return 1; } static int fake_rand_enable_locking(void *vrng) { return 1; } static int fake_rand_get_ctx_params(ossl_unused void *vrng, OSSL_PARAM params[]) { FAKE_RAND *frng = (FAKE_RAND *)vrng; OSSL_PARAM *p; p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STATE); if (p != NULL && !OSSL_PARAM_set_int(p, frng->state)) return 0; p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_STRENGTH); if (p != NULL && !OSSL_PARAM_set_int(p, 256)) return 0; p = OSSL_PARAM_locate(params, OSSL_RAND_PARAM_MAX_REQUEST); if (p != NULL && !OSSL_PARAM_set_size_t(p, INT_MAX)) return 0; return 1; } static const OSSL_PARAM *fake_rand_gettable_ctx_params(ossl_unused void *vrng, ossl_unused void *provctx) { static const OSSL_PARAM known_gettable_ctx_params[] = { OSSL_PARAM_int(OSSL_RAND_PARAM_STATE, NULL), OSSL_PARAM_uint(OSSL_RAND_PARAM_STRENGTH, NULL), OSSL_PARAM_size_t(OSSL_RAND_PARAM_MAX_REQUEST, NULL), OSSL_PARAM_END }; return known_gettable_ctx_params; } static const OSSL_DISPATCH fake_rand_functions[] = { { OSSL_FUNC_RAND_NEWCTX, (void (*)(void))fake_rand_newctx }, { OSSL_FUNC_RAND_FREECTX, (void (*)(void))fake_rand_freectx }, { OSSL_FUNC_RAND_INSTANTIATE, (void (*)(void))fake_rand_instantiate }, { OSSL_FUNC_RAND_UNINSTANTIATE, (void (*)(void))fake_rand_uninstantiate }, { OSSL_FUNC_RAND_GENERATE, (void (*)(void))fake_rand_generate }, { OSSL_FUNC_RAND_ENABLE_LOCKING, (void (*)(void))fake_rand_enable_locking }, { OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS, (void(*)(void))fake_rand_gettable_ctx_params }, { OSSL_FUNC_RAND_GET_CTX_PARAMS, (void(*)(void))fake_rand_get_ctx_params }, OSSL_DISPATCH_END }; static const OSSL_ALGORITHM fake_rand_rand[] = { { "FAKE", "provider=fake", fake_rand_functions }, { NULL, NULL, NULL } }; static const OSSL_ALGORITHM *fake_rand_query(void *provctx, int operation_id, int *no_cache) { *no_cache = 0; switch (operation_id) { case OSSL_OP_RAND: return fake_rand_rand; } return NULL; } /* Functions we provide to the core */ static const OSSL_DISPATCH fake_rand_method[] = { { OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))OSSL_LIB_CTX_free }, { OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))fake_rand_query }, OSSL_DISPATCH_END }; static int fake_rand_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx) { if (!TEST_ptr(*provctx = OSSL_LIB_CTX_new())) return 0; *out = fake_rand_method; return 1; } static int check_rng(EVP_RAND_CTX *rng, const char *name) { FAKE_RAND *f; if (!TEST_ptr(rng)) { TEST_info("random: %s", name); return 0; } f = rng->algctx; f->name = name; f->ctx = rng; return 1; } OSSL_PROVIDER *fake_rand_start(OSSL_LIB_CTX *libctx) { OSSL_PROVIDER *p; if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "fake-rand", fake_rand_provider_init)) || !TEST_true(RAND_set_DRBG_type(libctx, "fake", NULL, NULL, NULL)) || !TEST_ptr(p = OSSL_PROVIDER_try_load(libctx, "fake-rand", 1))) return NULL; /* Ensure that the fake rand is initialized. */ if (!TEST_true(check_rng(RAND_get0_primary(libctx), "primary")) || !TEST_true(check_rng(RAND_get0_private(libctx), "private")) || !TEST_true(check_rng(RAND_get0_public(libctx), "public"))) { OSSL_PROVIDER_unload(p); return NULL; } return p; } void fake_rand_finish(OSSL_PROVIDER *p) { OSSL_PROVIDER_unload(p); } void fake_rand_set_callback(EVP_RAND_CTX *rng, int (*cb)(unsigned char *out, size_t outlen, const char *name, EVP_RAND_CTX *ctx)) { if (rng != NULL) ((FAKE_RAND *)rng->algctx)->cb = cb; } void fake_rand_set_public_private_callbacks(OSSL_LIB_CTX *libctx, int (*cb)(unsigned char *out, size_t outlen, const char *name, EVP_RAND_CTX *ctx)) { fake_rand_set_callback(RAND_get0_private(libctx), cb); fake_rand_set_callback(RAND_get0_public(libctx), cb); }
7,322
30.564655
81
c
openssl
openssl-master/test/testutil/format_output.c
/* * Copyright 2017-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 "../testutil.h" #include "output.h" #include "tu_local.h" #include <string.h> #include <ctype.h> /* The size of memory buffers to display on failure */ #define MEM_BUFFER_SIZE (2000) #define MAX_STRING_WIDTH (80) #define BN_OUTPUT_SIZE (8) /* Output a diff header */ static void test_diff_header(const char *left, const char *right) { test_printf_stderr("--- %s\n", left); test_printf_stderr("+++ %s\n", right); } /* Formatted string output routines */ static void test_string_null_empty(const char *m, char c) { if (m == NULL) test_printf_stderr("%4s %c NULL\n", "", c); else test_printf_stderr("%4u:%c ''\n", 0u, c); } static void test_fail_string_common(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const char *m1, size_t l1, const char *m2, size_t l2) { const size_t width = (MAX_STRING_WIDTH - BIO_get_indent(bio_err) - 12) / 16 * 16; char b1[MAX_STRING_WIDTH + 1], b2[MAX_STRING_WIDTH + 1]; char bdiff[MAX_STRING_WIDTH + 1]; size_t n1, n2, i; unsigned int cnt = 0, diff; test_fail_message_prefix(prefix, file, line, type, left, right, op); if (m1 == NULL) l1 = 0; if (m2 == NULL) l2 = 0; if (l1 == 0 && l2 == 0) { if ((m1 == NULL) == (m2 == NULL)) { test_string_null_empty(m1, ' '); } else { test_diff_header(left, right); test_string_null_empty(m1, '-'); test_string_null_empty(m2, '+'); } goto fin; } if (l1 != l2 || strncmp(m1, m2, l1) != 0) test_diff_header(left, right); while (l1 > 0 || l2 > 0) { n1 = n2 = 0; if (l1 > 0) { b1[n1 = l1 > width ? width : l1] = 0; for (i = 0; i < n1; i++) b1[i] = isprint((unsigned char)m1[i]) ? m1[i] : '.'; } if (l2 > 0) { b2[n2 = l2 > width ? width : l2] = 0; for (i = 0; i < n2; i++) b2[i] = isprint((unsigned char)m2[i]) ? m2[i] : '.'; } diff = 0; i = 0; if (n1 > 0 && n2 > 0) { const size_t j = n1 < n2 ? n1 : n2; for (; i < j; i++) if (m1[i] == m2[i]) { bdiff[i] = ' '; } else { bdiff[i] = '^'; diff = 1; } bdiff[i] = '\0'; } if (n1 == n2 && !diff) { test_printf_stderr("%4u: '%s'\n", cnt, n2 > n1 ? b2 : b1); } else { if (cnt == 0 && (m1 == NULL || *m1 == '\0')) test_string_null_empty(m1, '-'); else if (n1 > 0) test_printf_stderr("%4u:- '%s'\n", cnt, b1); if (cnt == 0 && (m2 == NULL || *m2 == '\0')) test_string_null_empty(m2, '+'); else if (n2 > 0) test_printf_stderr("%4u:+ '%s'\n", cnt, b2); if (diff && i > 0) test_printf_stderr("%4s %s\n", "", bdiff); } if (m1 != NULL) m1 += n1; if (m2 != NULL) m2 += n2; l1 -= n1; l2 -= n2; cnt += width; } fin: test_flush_stderr(); } /* * Wrapper routines so that the underlying code can be shared. * The first is the call from inside the test utilities when a conditional * fails. The second is the user's call to dump a string. */ void test_fail_string_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const char *m1, size_t l1, const char *m2, size_t l2) { test_fail_string_common(prefix, file, line, type, left, right, op, m1, l1, m2, l2); test_printf_stderr("\n"); } void test_output_string(const char *name, const char *m, size_t l) { test_fail_string_common("string", NULL, 0, NULL, NULL, NULL, name, m, l, m, l); } /* BIGNUM formatted output routines */ /* * A basic memory byte to hex digit converter with allowance for spacing * every so often. */ static void hex_convert_memory(const unsigned char *m, size_t n, char *b, size_t width) { size_t i; for (i = 0; i < n; i++) { const unsigned char c = *m++; *b++ = "0123456789abcdef"[c >> 4]; *b++ = "0123456789abcdef"[c & 15]; if (i % width == width - 1 && i != n - 1) *b++ = ' '; } *b = '\0'; } /* * Constants to define the number of bytes to display per line and the number * of characters these take. */ static const int bn_bytes = (MAX_STRING_WIDTH - 9) / (BN_OUTPUT_SIZE * 2 + 1) * BN_OUTPUT_SIZE; static const int bn_chars = (MAX_STRING_WIDTH - 9) / (BN_OUTPUT_SIZE * 2 + 1) * (BN_OUTPUT_SIZE * 2 + 1) - 1; /* * Output the header line for the bignum */ static void test_bignum_header_line(void) { test_printf_stderr(" %*s\n", bn_chars + 6, "bit position"); } static const char *test_bignum_zero_null(const BIGNUM *bn) { if (bn != NULL) return BN_is_negative(bn) ? "-0" : "0"; return "NULL"; } /* * Print a bignum zero taking care to include the correct sign. * This routine correctly deals with a NULL bignum pointer as input. */ static void test_bignum_zero_print(const BIGNUM *bn, char sep) { const char *v = test_bignum_zero_null(bn); const char *suf = bn != NULL ? ": 0" : ""; test_printf_stderr("%c%*s%s\n", sep, bn_chars, v, suf); } /* * Convert a section of memory from inside a bignum into a displayable * string with appropriate visual aid spaces inserted. */ static int convert_bn_memory(const unsigned char *in, size_t bytes, char *out, int *lz, const BIGNUM *bn) { int n = bytes * 2, i; char *p = out, *q = NULL; const char *r; if (bn != NULL && !BN_is_zero(bn)) { hex_convert_memory(in, bytes, out, BN_OUTPUT_SIZE); if (*lz) { for (; *p == '0' || *p == ' '; p++) if (*p == '0') { q = p; *p = ' '; n--; } if (*p == '\0') { /* * in[bytes] is defined because we're converting a non-zero * number and we've not seen a non-zero yet. */ if ((in[bytes] & 0xf0) != 0 && BN_is_negative(bn)) { *lz = 0; *q = '-'; n++; } } else { *lz = 0; if (BN_is_negative(bn)) { /* * This is valid because we always convert more digits than * the number holds. */ *q = '-'; n++; } } } return n; } for (i = 0; i < n; i++) { *p++ = ' '; if (i % (2 * BN_OUTPUT_SIZE) == 2 * BN_OUTPUT_SIZE - 1 && i != n - 1) *p++ = ' '; } *p = '\0'; if (bn == NULL) r = "NULL"; else r = BN_is_negative(bn) ? "-0" : "0"; strcpy(p - strlen(r), r); return 0; } /* * Common code to display either one or two bignums, including the diff * pointers for changes (only when there are two). */ static void test_fail_bignum_common(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const BIGNUM *bn1, const BIGNUM *bn2) { const size_t bytes = bn_bytes; char b1[MAX_STRING_WIDTH + 1], b2[MAX_STRING_WIDTH + 1]; char *p, bdiff[MAX_STRING_WIDTH + 1]; size_t l1, l2, n1, n2, i, len; unsigned int cnt, diff, real_diff; unsigned char *m1 = NULL, *m2 = NULL; int lz1 = 1, lz2 = 1; unsigned char buffer[MEM_BUFFER_SIZE * 2], *bufp = buffer; test_fail_message_prefix(prefix, file, line, type, left, right, op); l1 = bn1 == NULL ? 0 : (BN_num_bytes(bn1) + (BN_is_negative(bn1) ? 1 : 0)); l2 = bn2 == NULL ? 0 : (BN_num_bytes(bn2) + (BN_is_negative(bn2) ? 1 : 0)); if (l1 == 0 && l2 == 0) { if ((bn1 == NULL) == (bn2 == NULL)) { test_bignum_header_line(); test_bignum_zero_print(bn1, ' '); } else { test_diff_header(left, right); test_bignum_header_line(); test_bignum_zero_print(bn1, '-'); test_bignum_zero_print(bn2, '+'); } goto fin; } if (l1 != l2 || bn1 == NULL || bn2 == NULL || BN_cmp(bn1, bn2) != 0) test_diff_header(left, right); test_bignum_header_line(); len = ((l1 > l2 ? l1 : l2) + bytes - 1) / bytes * bytes; if (len > MEM_BUFFER_SIZE && (bufp = OPENSSL_malloc(len * 2)) == NULL) { bufp = buffer; len = MEM_BUFFER_SIZE; test_printf_stderr("WARNING: these BIGNUMs have been truncated\n"); } if (bn1 != NULL) { m1 = bufp; BN_bn2binpad(bn1, m1, len); } if (bn2 != NULL) { m2 = bufp + len; BN_bn2binpad(bn2, m2, len); } while (len > 0) { cnt = 8 * (len - bytes); n1 = convert_bn_memory(m1, bytes, b1, &lz1, bn1); n2 = convert_bn_memory(m2, bytes, b2, &lz2, bn2); diff = real_diff = 0; i = 0; p = bdiff; for (i=0; b1[i] != '\0'; i++) if (b1[i] == b2[i] || b1[i] == ' ' || b2[i] == ' ') { *p++ = ' '; diff |= b1[i] != b2[i]; } else { *p++ = '^'; real_diff = diff = 1; } *p++ = '\0'; if (!diff) { test_printf_stderr(" %s:% 5d\n", n2 > n1 ? b2 : b1, cnt); } else { if (cnt == 0 && bn1 == NULL) test_printf_stderr("-%s\n", b1); else if (cnt == 0 || n1 > 0) test_printf_stderr("-%s:% 5d\n", b1, cnt); if (cnt == 0 && bn2 == NULL) test_printf_stderr("+%s\n", b2); else if (cnt == 0 || n2 > 0) test_printf_stderr("+%s:% 5d\n", b2, cnt); if (real_diff && (cnt == 0 || (n1 > 0 && n2 > 0)) && bn1 != NULL && bn2 != NULL) test_printf_stderr(" %s\n", bdiff); } if (m1 != NULL) m1 += bytes; if (m2 != NULL) m2 += bytes; len -= bytes; } fin: test_flush_stderr(); if (bufp != buffer) OPENSSL_free(bufp); } /* * Wrapper routines so that the underlying code can be shared. * The first two are calls from inside the test utilities when a conditional * fails. The third is the user's call to dump a bignum. */ void test_fail_bignum_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const BIGNUM *bn1, const BIGNUM *bn2) { test_fail_bignum_common(prefix, file, line, type, left, right, op, bn1, bn2); test_printf_stderr("\n"); } void test_fail_bignum_mono_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const BIGNUM *bn) { test_fail_bignum_common(prefix, file, line, type, left, right, op, bn, bn); test_printf_stderr("\n"); } void test_output_bignum(const char *name, const BIGNUM *bn) { if (bn == NULL || BN_is_zero(bn)) { test_printf_stderr("bignum: '%s' = %s\n", name, test_bignum_zero_null(bn)); } else if (BN_num_bytes(bn) <= BN_OUTPUT_SIZE) { unsigned char buf[BN_OUTPUT_SIZE]; char out[2 * sizeof(buf) + 1]; char *p = out; int n = BN_bn2bin(bn, buf); hex_convert_memory(buf, n, p, BN_OUTPUT_SIZE); while (*p == '0' && *++p != '\0') ; test_printf_stderr("bignum: '%s' = %s0x%s\n", name, BN_is_negative(bn) ? "-" : "", p); } else { test_fail_bignum_common("bignum", NULL, 0, NULL, NULL, NULL, name, bn, bn); } } /* Memory output routines */ /* * Handle zero length blocks of memory or NULL pointers to memory */ static void test_memory_null_empty(const unsigned char *m, char c) { if (m == NULL) test_printf_stderr("%4s %c%s\n", "", c, "NULL"); else test_printf_stderr("%04x %c%s\n", 0u, c, "empty"); } /* * Common code to display one or two blocks of memory. */ static void test_fail_memory_common(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const unsigned char *m1, size_t l1, const unsigned char *m2, size_t l2) { const size_t bytes = (MAX_STRING_WIDTH - 9) / 17 * 8; char b1[MAX_STRING_WIDTH + 1], b2[MAX_STRING_WIDTH + 1]; char *p, bdiff[MAX_STRING_WIDTH + 1]; size_t n1, n2, i; unsigned int cnt = 0, diff; test_fail_message_prefix(prefix, file, line, type, left, right, op); if (m1 == NULL) l1 = 0; if (m2 == NULL) l2 = 0; if (l1 == 0 && l2 == 0) { if ((m1 == NULL) == (m2 == NULL)) { test_memory_null_empty(m1, ' '); } else { test_diff_header(left, right); test_memory_null_empty(m1, '-'); test_memory_null_empty(m2, '+'); } goto fin; } if (l1 != l2 || (m1 != m2 && memcmp(m1, m2, l1) != 0)) test_diff_header(left, right); while (l1 > 0 || l2 > 0) { n1 = n2 = 0; if (l1 > 0) { n1 = l1 > bytes ? bytes : l1; hex_convert_memory(m1, n1, b1, 8); } if (l2 > 0) { n2 = l2 > bytes ? bytes : l2; hex_convert_memory(m2, n2, b2, 8); } diff = 0; i = 0; p = bdiff; if (n1 > 0 && n2 > 0) { const size_t j = n1 < n2 ? n1 : n2; for (; i < j; i++) { if (m1[i] == m2[i]) { *p++ = ' '; *p++ = ' '; } else { *p++ = '^'; *p++ = '^'; diff = 1; } if (i % 8 == 7 && i != j - 1) *p++ = ' '; } *p++ = '\0'; } if (n1 == n2 && !diff) { test_printf_stderr("%04x: %s\n", cnt, b1); } else { if (cnt == 0 && (m1 == NULL || l1 == 0)) test_memory_null_empty(m1, '-'); else if (n1 > 0) test_printf_stderr("%04x:-%s\n", cnt, b1); if (cnt == 0 && (m2 == NULL || l2 == 0)) test_memory_null_empty(m2, '+'); else if (n2 > 0) test_printf_stderr("%04x:+%s\n", cnt, b2); if (diff && i > 0) test_printf_stderr("%4s %s\n", "", bdiff); } if (m1 != NULL) m1 += n1; if (m2 != NULL) m2 += n2; l1 -= n1; l2 -= n2; cnt += bytes; } fin: test_flush_stderr(); } /* * Wrapper routines so that the underlying code can be shared. * The first is the call from inside the test utilities when a conditional * fails. The second is the user's call to dump memory. */ void test_fail_memory_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const unsigned char *m1, size_t l1, const unsigned char *m2, size_t l2) { test_fail_memory_common(prefix, file, line, type, left, right, op, m1, l1, m2, l2); test_printf_stderr("\n"); } void test_output_memory(const char *name, const unsigned char *m, size_t l) { test_fail_memory_common("memory", NULL, 0, NULL, NULL, NULL, name, m, l, m, l); }
17,217
31.183178
81
c
openssl
openssl-master/test/testutil/load.c
/* * Copyright 2020-2021 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 <openssl/x509.h> #include <openssl/pem.h> #include "../testutil.h" X509 *load_cert_pem(const char *file, OSSL_LIB_CTX *libctx) { X509 *cert = NULL; BIO *bio = NULL; if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new(BIO_s_file()))) return NULL; if (TEST_int_gt(BIO_read_filename(bio, file), 0) && TEST_ptr(cert = X509_new_ex(libctx, NULL))) (void)TEST_ptr(cert = PEM_read_bio_X509(bio, &cert, NULL, NULL)); BIO_free(bio); return cert; } STACK_OF(X509) *load_certs_pem(const char *file) { STACK_OF(X509) *certs; BIO *bio; X509 *x; if (!TEST_ptr(file) || (bio = BIO_new_file(file, "r")) == NULL) return NULL; certs = sk_X509_new_null(); if (certs == NULL) { BIO_free(bio); return NULL; } ERR_set_mark(); do { x = PEM_read_bio_X509(bio, NULL, 0, NULL); if (x != NULL && !sk_X509_push(certs, x)) { OSSL_STACK_OF_X509_free(certs); BIO_free(bio); return NULL; } else if (x == NULL) { /* * We probably just ran out of certs, so ignore any errors * generated */ ERR_pop_to_mark(); } } while (x != NULL); BIO_free(bio); return certs; } EVP_PKEY *load_pkey_pem(const char *file, OSSL_LIB_CTX *libctx) { EVP_PKEY *key = NULL; BIO *bio = NULL; if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new(BIO_s_file()))) return NULL; if (TEST_int_gt(BIO_read_filename(bio, file), 0)) { unsigned long err = ERR_peek_error(); if (TEST_ptr(key = PEM_read_bio_PrivateKey_ex(bio, NULL, NULL, NULL, libctx, NULL)) && err != ERR_peek_error()) { TEST_info("Spurious error from reading PEM"); EVP_PKEY_free(key); key = NULL; } } BIO_free(bio); return key; } X509_REQ *load_csr_der(const char *file, OSSL_LIB_CTX *libctx) { X509_REQ *csr = NULL; BIO *bio = NULL; if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new_file(file, "rb"))) return NULL; csr = X509_REQ_new_ex(libctx, NULL); if (TEST_ptr(csr)) (void)TEST_ptr(d2i_X509_REQ_bio(bio, &csr)); BIO_free(bio); return csr; }
2,696
24.443396
76
c
openssl
openssl-master/test/testutil/main.c
/* * Copyright 2016-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 "../testutil.h" #include "output.h" #include "tu_local.h" int main(int argc, char *argv[]) { int ret = EXIT_FAILURE; test_open_streams(); if (!global_init()) { test_printf_stderr("Global init failed - aborting\n"); return ret; } if (!setup_test_framework(argc, argv)) goto end; if (setup_tests()) { ret = run_tests(argv[0]); cleanup_tests(); opt_check_usage(); } else { opt_help(test_get_options()); } end: ret = pulldown_test_framework(ret); test_close_streams(); return ret; }
931
21.731707
74
c
openssl
openssl-master/test/testutil/options.c
/* * Copyright 2018-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 "../testutil.h" #include "internal/nelem.h" #include "tu_local.h" #include "output.h" static int used[100] = { 0 }; int test_skip_common_options(void) { OPTION_CHOICE_DEFAULT o; while ((o = (OPTION_CHOICE_DEFAULT)opt_next()) != OPT_EOF) { switch (o) { case OPT_TEST_CASES: break; default: case OPT_ERR: return 0; } } return 1; } size_t test_get_argument_count(void) { return opt_num_rest(); } char *test_get_argument(size_t n) { char **argv = opt_rest(); OPENSSL_assert(n < sizeof(used)); if ((int)n >= opt_num_rest() || argv == NULL) return NULL; used[n] = 1; return argv[n]; } void opt_check_usage(void) { int i; char **argv = opt_rest(); int n, arg_count = opt_num_rest(); if (arg_count > (int)OSSL_NELEM(used)) n = (int)OSSL_NELEM(used); else n = arg_count; for (i = 0; i < n; i++) { if (used[i] == 0) test_printf_stderr("Warning ignored command-line argument %d: %s\n", i, argv[i]); } if (i < arg_count) test_printf_stderr("Warning arguments %d and later unchecked\n", i); } int opt_printf_stderr(const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = test_vprintf_stderr(fmt, ap); va_end(ap); return ret; }
1,728
20.6125
80
c
openssl
openssl-master/test/testutil/output.h
/* * Copyright 2014-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 */ #ifndef OSSL_TESTUTIL_OUTPUT_H # define OSSL_TESTUTIL_OUTPUT_H # include <stdarg.h> # define ossl_test__attr__(x) # if defined(__GNUC__) && defined(__STDC_VERSION__) \ && !defined(__MINGW32__) && !defined(__MINGW64__) \ && !defined(__APPLE__) /* * Because we support the 'z' modifier, which made its appearance in C99, * we can't use __attribute__ with pre C99 dialects. */ # if __STDC_VERSION__ >= 199901L # undef ossl_test__attr__ # define ossl_test__attr__ __attribute__ # if __GNUC__*10 + __GNUC_MINOR__ >= 44 # define ossl_test__printf__ __gnu_printf__ # else # define ossl_test__printf__ __printf__ # endif # endif # endif /* * The basic I/O functions used internally by the test framework. These * can be overridden when needed. Note that if one is, then all must be. */ void test_open_streams(void); void test_close_streams(void); void test_adjust_streams_tap_level(int level); /* The following ALL return the number of characters written */ int test_vprintf_stdout(const char *fmt, va_list ap) ossl_test__attr__((__format__(ossl_test__printf__, 1, 0))); int test_vprintf_tapout(const char *fmt, va_list ap) ossl_test__attr__((__format__(ossl_test__printf__, 1, 0))); int test_vprintf_stderr(const char *fmt, va_list ap) ossl_test__attr__((__format__(ossl_test__printf__, 1, 0))); int test_vprintf_taperr(const char *fmt, va_list ap) ossl_test__attr__((__format__(ossl_test__printf__, 1, 0))); /* These return failure or success */ int test_flush_stdout(void); int test_flush_tapout(void); int test_flush_stderr(void); int test_flush_taperr(void); /* Commodity functions. There's no need to override these */ int test_printf_stdout(const char *fmt, ...) ossl_test__attr__((__format__(ossl_test__printf__, 1, 2))); int test_printf_tapout(const char *fmt, ...) ossl_test__attr__((__format__(ossl_test__printf__, 1, 2))); int test_printf_stderr(const char *fmt, ...) ossl_test__attr__((__format__(ossl_test__printf__, 1, 2))); int test_printf_taperr(const char *fmt, ...) ossl_test__attr__((__format__(ossl_test__printf__, 1, 2))); # undef ossl_test__printf__ # undef ossl_test__attr__ #endif /* OSSL_TESTUTIL_OUTPUT_H */
2,576
36.347826
77
h
openssl
openssl-master/test/testutil/provider.c
/* * Copyright 2018-2021 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 "../testutil.h" #include <ctype.h> #include <openssl/provider.h> #include <openssl/core_names.h> #include <string.h> int test_get_libctx(OSSL_LIB_CTX **libctx, OSSL_PROVIDER **default_null_prov, const char *config_file, OSSL_PROVIDER **provider, const char *module_name) { OSSL_LIB_CTX *new_libctx = NULL; if (libctx != NULL) { if ((new_libctx = *libctx = OSSL_LIB_CTX_new()) == NULL) { opt_printf_stderr("Failed to create libctx\n"); goto err; } } if (default_null_prov != NULL && (*default_null_prov = OSSL_PROVIDER_load(NULL, "null")) == NULL) { opt_printf_stderr("Failed to load null provider into default libctx\n"); goto err; } if (config_file != NULL && !OSSL_LIB_CTX_load_config(new_libctx, config_file)) { opt_printf_stderr("Error loading config from file %s\n", config_file); goto err; } if (provider != NULL && module_name != NULL && (*provider = OSSL_PROVIDER_load(new_libctx, module_name)) == NULL) { opt_printf_stderr("Failed to load provider %s\n", module_name); goto err; } return 1; err: ERR_print_errors_fp(stderr); return 0; } int test_arg_libctx(OSSL_LIB_CTX **libctx, OSSL_PROVIDER **default_null_prov, OSSL_PROVIDER **provider, int argn, const char *usage) { const char *module_name; if (!TEST_ptr(module_name = test_get_argument(argn))) { TEST_error("usage: <prog> %s", usage); return 0; } if (strcmp(module_name, "none") == 0) return 1; return test_get_libctx(libctx, default_null_prov, test_get_argument(argn + 1), provider, module_name); } typedef struct { int major, minor, patch; } FIPS_VERSION; /* * Query the FIPS provider to determine it's version number. * Returns 1 if the version is retrieved correctly, 0 if the FIPS provider isn't * loaded and -1 on error. */ static int fips_provider_version(OSSL_LIB_CTX *libctx, FIPS_VERSION *vers) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; OSSL_PROVIDER *fips_prov; char *vs; if (!OSSL_PROVIDER_available(libctx, "fips")) return 0; *params = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_VERSION, &vs, 0); if ((fips_prov = OSSL_PROVIDER_load(libctx, "fips")) == NULL) return -1; if (!OSSL_PROVIDER_get_params(fips_prov, params) || sscanf(vs, "%d.%d.%d", &vers->major, &vers->minor, &vers->patch) != 3) goto err; if (!OSSL_PROVIDER_unload(fips_prov)) return -1; return 1; err: OSSL_PROVIDER_unload(fips_prov); return -1; } int fips_provider_version_eq(OSSL_LIB_CTX *libctx, int major, int minor, int patch) { FIPS_VERSION prov; int res; if ((res = fips_provider_version(libctx, &prov)) <= 0) return res == 0; return major == prov.major && minor == prov.minor && patch == prov.patch; } int fips_provider_version_ne(OSSL_LIB_CTX *libctx, int major, int minor, int patch) { FIPS_VERSION prov; int res; if ((res = fips_provider_version(libctx, &prov)) <= 0) return res == 0; return major != prov.major || minor != prov.minor || patch != prov.patch; } int fips_provider_version_le(OSSL_LIB_CTX *libctx, int major, int minor, int patch) { FIPS_VERSION prov; int res; if ((res = fips_provider_version(libctx, &prov)) <= 0) return res == 0; return prov.major < major || (prov.major == major && (prov.minor < minor || (prov.minor == minor && prov.patch <= patch))); } int fips_provider_version_lt(OSSL_LIB_CTX *libctx, int major, int minor, int patch) { FIPS_VERSION prov; int res; if ((res = fips_provider_version(libctx, &prov)) <= 0) return res == 0; return prov.major < major || (prov.major == major && (prov.minor < minor || (prov.minor == minor && prov.patch < patch))); } int fips_provider_version_gt(OSSL_LIB_CTX *libctx, int major, int minor, int patch) { FIPS_VERSION prov; int res; if ((res = fips_provider_version(libctx, &prov)) <= 0) return res == 0; return prov.major > major || (prov.major == major && (prov.minor > minor || (prov.minor == minor && prov.patch > patch))); } int fips_provider_version_ge(OSSL_LIB_CTX *libctx, int major, int minor, int patch) { FIPS_VERSION prov; int res; if ((res = fips_provider_version(libctx, &prov)) <= 0) return res == 0; return prov.major > major || (prov.major == major && (prov.minor > minor || (prov.minor == minor && prov.patch >= patch))); } int fips_provider_version_match(OSSL_LIB_CTX *libctx, const char *versions) { const char *p; int major, minor, patch, r; enum { MODE_EQ, MODE_NE, MODE_LE, MODE_LT, MODE_GT, MODE_GE } mode; while (*versions != '\0') { for (; isspace((unsigned char)(*versions)); versions++) continue; if (*versions == '\0') break; for (p = versions; *versions != '\0' && !isspace((unsigned char)(*versions)); versions++) continue; if (*p == '!') { mode = MODE_NE; p++; } else if (*p == '=') { mode = MODE_EQ; p++; } else if (*p == '<' && p[1] == '=') { mode = MODE_LE; p += 2; } else if (*p == '>' && p[1] == '=') { mode = MODE_GE; p += 2; } else if (*p == '<') { mode = MODE_LT; p++; } else if (*p == '>') { mode = MODE_GT; p++; } else if (isdigit((unsigned char)*p)) { mode = MODE_EQ; } else { TEST_info("Error matching FIPS version: mode %s\n", p); return -1; } if (sscanf(p, "%d.%d.%d", &major, &minor, &patch) != 3) { TEST_info("Error matching FIPS version: version %s\n", p); return -1; } switch (mode) { case MODE_EQ: r = fips_provider_version_eq(libctx, major, minor, patch); break; case MODE_NE: r = fips_provider_version_ne(libctx, major, minor, patch); break; case MODE_LE: r = fips_provider_version_le(libctx, major, minor, patch); break; case MODE_LT: r = fips_provider_version_lt(libctx, major, minor, patch); break; case MODE_GT: r = fips_provider_version_gt(libctx, major, minor, patch); break; case MODE_GE: r = fips_provider_version_ge(libctx, major, minor, patch); break; } if (r < 0) { TEST_info("Error matching FIPS version: internal error\n"); return -1; } if (r == 0) return 0; } return 1; }
7,429
29.576132
97
c
openssl
openssl-master/test/testutil/random.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 "../testutil.h" /* * This is an implementation of the algorithm used by the GNU C library's * random(3) pseudorandom number generator as described: * https://www.mscs.dal.ca/~selinger/random/ */ static uint32_t test_random_state[31]; uint32_t test_random(void) { static unsigned int pos = 3; if (pos == 31) pos = 0; test_random_state[pos] += test_random_state[(pos + 28) % 31]; return test_random_state[pos++] / 2; } void test_random_seed(uint32_t sd) { int i; int32_t s; const unsigned int mod = (1u << 31) - 1; test_random_state[0] = sd; for (i = 1; i < 31; i++) { s = (int32_t)test_random_state[i - 1]; test_random_state[i] = (uint32_t)((16807 * (int64_t)s) % mod); } for (i = 34; i < 344; i++) test_random(); }
1,146
26.97561
74
c
openssl
openssl-master/test/testutil/stanza.c
/* * Copyright 2017 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 <assert.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "internal/nelem.h" #include "../testutil.h" #include "tu_local.h" int test_start_file(STANZA *s, const char *testfile) { TEST_info("Reading %s", testfile); set_test_title(testfile); memset(s, 0, sizeof(*s)); if (!TEST_ptr(s->fp = BIO_new_file(testfile, "r"))) return 0; s->test_file = testfile; return 1; } int test_end_file(STANZA *s) { TEST_info("Completed %d tests with %d errors and %d skipped", s->numtests, s->errors, s->numskip); BIO_free(s->fp); return 1; } /* * Read a PEM block. Return 1 if okay, 0 on error. */ static int read_key(STANZA *s) { char tmpbuf[128]; if (s->key == NULL) { if (!TEST_ptr(s->key = BIO_new(BIO_s_mem()))) return 0; } else if (!TEST_int_gt(BIO_reset(s->key), 0)) { return 0; } /* Read to PEM end line and place content in memory BIO */ while (BIO_gets(s->fp, tmpbuf, sizeof(tmpbuf))) { s->curr++; if (!TEST_int_gt(BIO_puts(s->key, tmpbuf), 0)) return 0; if (HAS_PREFIX(tmpbuf, "-----END")) return 1; } TEST_error("Can't find key end"); return 0; } /* * Delete leading and trailing spaces from a string */ static char *strip_spaces(char *p) { char *q; /* Skip over leading spaces */ while (*p && isspace((unsigned char)*p)) p++; if (*p == '\0') return NULL; for (q = p + strlen(p) - 1; q != p && isspace((unsigned char)*q); ) *q-- = '\0'; return *p ? p : NULL; } /* * Read next test stanza; return 1 if found, 0 on EOF or error. */ int test_readstanza(STANZA *s) { PAIR *pp = s->pairs; char *p, *equals, *key; const char *value; for (s->numpairs = 0; BIO_gets(s->fp, s->buff, sizeof(s->buff)); ) { s->curr++; if (!TEST_ptr(p = strchr(s->buff, '\n'))) { TEST_info("Line %d too long", s->curr); return 0; } *p = '\0'; /* Blank line marks end of tests. */ if (s->buff[0] == '\0') break; /* Lines starting with a pound sign are ignored. */ if (s->buff[0] == '#') continue; /* Parse into key=value */ if (!TEST_ptr(equals = strchr(s->buff, '='))) { TEST_info("Missing = at line %d\n", s->curr); return 0; } *equals++ = '\0'; if (!TEST_ptr(key = strip_spaces(s->buff))) { TEST_info("Empty field at line %d\n", s->curr); return 0; } if ((value = strip_spaces(equals)) == NULL) value = ""; if (strcmp(key, "Title") == 0) { TEST_info("Starting \"%s\" tests at line %d", value, s->curr); continue; } if (s->numpairs == 0) s->start = s->curr; if (strcmp(key, "PrivateKey") == 0) { if (!read_key(s)) return 0; } if (strcmp(key, "PublicKey") == 0) { if (!read_key(s)) return 0; } if (!TEST_int_lt(s->numpairs++, TESTMAXPAIRS) || !TEST_ptr(pp->key = OPENSSL_strdup(key)) || !TEST_ptr(pp->value = OPENSSL_strdup(value))) return 0; pp++; } /* If we read anything, return ok. */ return 1; } void test_clearstanza(STANZA *s) { PAIR *pp = s->pairs; int i = s->numpairs; for ( ; --i >= 0; pp++) { OPENSSL_free(pp->key); OPENSSL_free(pp->value); } s->numpairs = 0; }
3,964
23.78125
74
c
openssl
openssl-master/test/testutil/test_options.c
/* * Copyright 2018-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 "../testutil.h" #include "tu_local.h" /* An overridable list of command line options */ const OPTIONS *test_get_options(void) { static const OPTIONS default_options[] = { OPT_TEST_OPTIONS_DEFAULT_USAGE, { NULL } }; return default_options; }
616
27.045455
74
c
openssl
openssl-master/test/testutil/tests.c
/* * Copyright 2017-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 "../testutil.h" #include "output.h" #include "tu_local.h" #include <errno.h> #include <string.h> #include <ctype.h> #include <openssl/asn1.h> /* * Output a failed test first line. * All items are optional are generally not preinted if passed as NULL. * The special cases are for prefix where "ERROR" is assumed and for left * and right where a non-failure message is produced if either is NULL. */ void test_fail_message_prefix(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op) { test_printf_stderr("%s: ", prefix != NULL ? prefix : "ERROR"); if (type) test_printf_stderr("(%s) ", type); if (op != NULL) { if (left != NULL && right != NULL) test_printf_stderr("'%s %s %s' failed", left, op, right); else test_printf_stderr("'%s'", op); } if (file != NULL) { test_printf_stderr(" @ %s:%d", file, line); } test_printf_stderr("\n"); } /* * A common routine to output test failure messages. Generally this should not * be called directly, rather it should be called by the following functions. * * |desc| is a printf formatted description with arguments |args| that is * supplied by the user and |desc| can be NULL. |type| is the data type * that was tested (int, char, ptr, ...). |fmt| is a system provided * printf format with following arguments that spell out the failure * details i.e. the actual values compared and the operator used. * * The typical use for this is from an utility test function: * * int test6(const char *file, int line, int n) { * if (n != 6) { * test_fail_message(1, file, line, "int", "value %d is not %d", n, 6); * return 0; * } * return 1; * } * * calling test6(3, "oops") will return 0 and produce out along the lines of: * FAIL oops: (int) value 3 is not 6\n */ static void test_fail_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const char *fmt, ...) PRINTF_FORMAT(8, 9); static void test_fail_message_va(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const char *fmt, va_list ap) { test_fail_message_prefix(prefix, file, line, type, left, right, op); if (fmt != NULL) { test_vprintf_stderr(fmt, ap); test_printf_stderr("\n"); } test_flush_stderr(); } static void test_fail_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const char *fmt, ...) { va_list ap; va_start(ap, fmt); test_fail_message_va(prefix, file, line, type, left, right, op, fmt, ap); va_end(ap); } void test_info_c90(const char *desc, ...) { va_list ap; va_start(ap, desc); test_fail_message_va("INFO", NULL, -1, NULL, NULL, NULL, NULL, desc, ap); va_end(ap); } void test_info(const char *file, int line, const char *desc, ...) { va_list ap; va_start(ap, desc); test_fail_message_va("INFO", file, line, NULL, NULL, NULL, NULL, desc, ap); va_end(ap); } void test_error_c90(const char *desc, ...) { va_list ap; va_start(ap, desc); test_fail_message_va(NULL, NULL, -1, NULL, NULL, NULL, NULL, desc, ap); va_end(ap); test_printf_stderr("\n"); } void test_error(const char *file, int line, const char *desc, ...) { va_list ap; va_start(ap, desc); test_fail_message_va(NULL, file, line, NULL, NULL, NULL, NULL, desc, ap); va_end(ap); test_printf_stderr("\n"); } void test_perror(const char *s) { /* * Using openssl_strerror_r causes linking issues since it isn't * exported from libcrypto.so */ TEST_error("%s: %s", s, strerror(errno)); } void test_note(const char *fmt, ...) { if (fmt != NULL) { va_list ap; va_start(ap, fmt); test_vprintf_stderr(fmt, ap); va_end(ap); test_printf_stderr("\n"); } test_flush_stderr(); } int test_skip(const char *file, int line, const char *desc, ...) { va_list ap; va_start(ap, desc); test_fail_message_va("SKIP", file, line, NULL, NULL, NULL, NULL, desc, ap); va_end(ap); return TEST_SKIP_CODE; } int test_skip_c90(const char *desc, ...) { va_list ap; va_start(ap, desc); test_fail_message_va("SKIP", NULL, -1, NULL, NULL, NULL, NULL, desc, ap); va_end(ap); test_printf_stderr("\n"); return TEST_SKIP_CODE; } void test_openssl_errors(void) { ERR_print_errors_cb(openssl_error_cb, NULL); ERR_clear_error(); } /* * Define some comparisons between pairs of various types. * These functions return 1 if the test is true. * Otherwise, they return 0 and pretty-print diagnostics. * * In each case the functions produced are: * int test_name_eq(const type t1, const type t2, const char *desc, ...); * int test_name_ne(const type t1, const type t2, const char *desc, ...); * int test_name_lt(const type t1, const type t2, const char *desc, ...); * int test_name_le(const type t1, const type t2, const char *desc, ...); * int test_name_gt(const type t1, const type t2, const char *desc, ...); * int test_name_ge(const type t1, const type t2, const char *desc, ...); * * The t1 and t2 arguments are to be compared for equality, inequality, * less than, less than or equal to, greater than and greater than or * equal to respectively. If the specified condition holds, the functions * return 1. If the condition does not hold, the functions print a diagnostic * message and return 0. * * The desc argument is a printf format string followed by its arguments and * this is included in the output if the condition being tested for is false. */ #define DEFINE_COMPARISON(type, name, opname, op, fmt, cast) \ int test_ ## name ## _ ## opname(const char *file, int line, \ const char *s1, const char *s2, \ const type t1, const type t2) \ { \ if (t1 op t2) \ return 1; \ test_fail_message(NULL, file, line, #type, s1, s2, #op, \ "[" fmt "] compared to [" fmt "]", \ (cast)t1, (cast)t2); \ return 0; \ } #define DEFINE_COMPARISONS(type, name, fmt, cast) \ DEFINE_COMPARISON(type, name, eq, ==, fmt, cast) \ DEFINE_COMPARISON(type, name, ne, !=, fmt, cast) \ DEFINE_COMPARISON(type, name, lt, <, fmt, cast) \ DEFINE_COMPARISON(type, name, le, <=, fmt, cast) \ DEFINE_COMPARISON(type, name, gt, >, fmt, cast) \ DEFINE_COMPARISON(type, name, ge, >=, fmt, cast) DEFINE_COMPARISONS(int, int, "%d", int) DEFINE_COMPARISONS(unsigned int, uint, "%u", unsigned int) DEFINE_COMPARISONS(char, char, "%c", char) DEFINE_COMPARISONS(unsigned char, uchar, "%u", unsigned char) DEFINE_COMPARISONS(long, long, "%ld", long) DEFINE_COMPARISONS(unsigned long, ulong, "%lu", unsigned long) DEFINE_COMPARISONS(int64_t, int64_t, "%lld", long long) DEFINE_COMPARISONS(uint64_t, uint64_t, "%llu", unsigned long long) DEFINE_COMPARISONS(size_t, size_t, "%zu", size_t) DEFINE_COMPARISONS(double, double, "%g", double) DEFINE_COMPARISON(void *, ptr, eq, ==, "%p", void *) DEFINE_COMPARISON(void *, ptr, ne, !=, "%p", void *) int test_ptr_null(const char *file, int line, const char *s, const void *p) { if (p == NULL) return 1; test_fail_message(NULL, file, line, "ptr", s, "NULL", "==", "%p", p); return 0; } int test_ptr(const char *file, int line, const char *s, const void *p) { if (p != NULL) return 1; test_fail_message(NULL, file, line, "ptr", s, "NULL", "!=", "%p", p); return 0; } int test_true(const char *file, int line, const char *s, int b) { if (b) return 1; test_fail_message(NULL, file, line, "bool", s, "true", "==", "false"); return 0; } int test_false(const char *file, int line, const char *s, int b) { if (!b) return 1; test_fail_message(NULL, file, line, "bool", s, "false", "==", "true"); return 0; } int test_str_eq(const char *file, int line, const char *st1, const char *st2, const char *s1, const char *s2) { if (s1 == NULL && s2 == NULL) return 1; if (s1 == NULL || s2 == NULL || strcmp(s1, s2) != 0) { test_fail_string_message(NULL, file, line, "string", st1, st2, "==", s1, s1 == NULL ? 0 : strlen(s1), s2, s2 == NULL ? 0 : strlen(s2)); return 0; } return 1; } int test_str_ne(const char *file, int line, const char *st1, const char *st2, const char *s1, const char *s2) { if ((s1 == NULL) ^ (s2 == NULL)) return 1; if (s1 == NULL || strcmp(s1, s2) == 0) { test_fail_string_message(NULL, file, line, "string", st1, st2, "!=", s1, s1 == NULL ? 0 : strlen(s1), s2, s2 == NULL ? 0 : strlen(s2)); return 0; } return 1; } int test_strn_eq(const char *file, int line, const char *st1, const char *st2, const char *s1, size_t n1, const char *s2, size_t n2) { if (s1 == NULL && s2 == NULL) return 1; if (n1 != n2 || s1 == NULL || s2 == NULL || strncmp(s1, s2, n1) != 0) { test_fail_string_message(NULL, file, line, "string", st1, st2, "==", s1, s1 == NULL ? 0 : OPENSSL_strnlen(s1, n1), s2, s2 == NULL ? 0 : OPENSSL_strnlen(s2, n2)); return 0; } return 1; } int test_strn_ne(const char *file, int line, const char *st1, const char *st2, const char *s1, size_t n1, const char *s2, size_t n2) { if ((s1 == NULL) ^ (s2 == NULL)) return 1; if (n1 != n2 || s1 == NULL || strncmp(s1, s2, n1) == 0) { test_fail_string_message(NULL, file, line, "string", st1, st2, "!=", s1, s1 == NULL ? 0 : OPENSSL_strnlen(s1, n1), s2, s2 == NULL ? 0 : OPENSSL_strnlen(s2, n2)); return 0; } return 1; } int test_mem_eq(const char *file, int line, const char *st1, const char *st2, const void *s1, size_t n1, const void *s2, size_t n2) { if (s1 == NULL && s2 == NULL) return 1; if (n1 != n2 || s1 == NULL || s2 == NULL || memcmp(s1, s2, n1) != 0) { test_fail_memory_message(NULL, file, line, "memory", st1, st2, "==", s1, n1, s2, n2); return 0; } return 1; } int test_mem_ne(const char *file, int line, const char *st1, const char *st2, const void *s1, size_t n1, const void *s2, size_t n2) { if ((s1 == NULL) ^ (s2 == NULL)) return 1; if (n1 != n2) return 1; if (s1 == NULL || memcmp(s1, s2, n1) == 0) { test_fail_memory_message(NULL, file, line, "memory", st1, st2, "!=", s1, n1, s2, n2); return 0; } return 1; } #define DEFINE_BN_COMPARISONS(opname, op, zero_cond) \ int test_BN_ ## opname(const char *file, int line, \ const char *s1, const char *s2, \ const BIGNUM *t1, const BIGNUM *t2) \ { \ if (BN_cmp(t1, t2) op 0) \ return 1; \ test_fail_bignum_message(NULL, file, line, "BIGNUM", s1, s2, \ #op, t1, t2); \ return 0; \ } \ int test_BN_ ## opname ## _zero(const char *file, int line, \ const char *s, const BIGNUM *a) \ { \ if (a != NULL &&(zero_cond)) \ return 1; \ test_fail_bignum_mono_message(NULL, file, line, "BIGNUM", \ s, "0", #op, a); \ return 0; \ } DEFINE_BN_COMPARISONS(eq, ==, BN_is_zero(a)) DEFINE_BN_COMPARISONS(ne, !=, !BN_is_zero(a)) DEFINE_BN_COMPARISONS(gt, >, !BN_is_negative(a) && !BN_is_zero(a)) DEFINE_BN_COMPARISONS(ge, >=, !BN_is_negative(a) || BN_is_zero(a)) DEFINE_BN_COMPARISONS(lt, <, BN_is_negative(a) && !BN_is_zero(a)) DEFINE_BN_COMPARISONS(le, <=, BN_is_negative(a) || BN_is_zero(a)) int test_BN_eq_one(const char *file, int line, const char *s, const BIGNUM *a) { if (a != NULL && BN_is_one(a)) return 1; test_fail_bignum_mono_message(NULL, file, line, "BIGNUM", s, "1", "==", a); return 0; } int test_BN_odd(const char *file, int line, const char *s, const BIGNUM *a) { if (a != NULL && BN_is_odd(a)) return 1; test_fail_bignum_mono_message(NULL, file, line, "BIGNUM", "ODD(", ")", s, a); return 0; } int test_BN_even(const char *file, int line, const char *s, const BIGNUM *a) { if (a != NULL && !BN_is_odd(a)) return 1; test_fail_bignum_mono_message(NULL, file, line, "BIGNUM", "EVEN(", ")", s, a); return 0; } int test_BN_eq_word(const char *file, int line, const char *bns, const char *ws, const BIGNUM *a, BN_ULONG w) { BIGNUM *bw; if (a != NULL && BN_is_word(a, w)) return 1; if ((bw = BN_new()) != NULL) BN_set_word(bw, w); test_fail_bignum_message(NULL, file, line, "BIGNUM", bns, ws, "==", a, bw); BN_free(bw); return 0; } int test_BN_abs_eq_word(const char *file, int line, const char *bns, const char *ws, const BIGNUM *a, BN_ULONG w) { BIGNUM *bw, *aa; if (a != NULL && BN_abs_is_word(a, w)) return 1; if ((aa = BN_dup(a)) != NULL) BN_set_negative(aa, 0); if ((bw = BN_new()) != NULL) BN_set_word(bw, w); test_fail_bignum_message(NULL, file, line, "BIGNUM", bns, ws, "abs==", aa, bw); BN_free(bw); BN_free(aa); return 0; } static const char *print_time(const ASN1_TIME *t) { return t == NULL ? "<null>" : (const char *)ASN1_STRING_get0_data(t); } #define DEFINE_TIME_T_COMPARISON(opname, op) \ int test_time_t_ ## opname(const char *file, int line, \ const char *s1, const char *s2, \ const time_t t1, const time_t t2) \ { \ ASN1_TIME *at1 = ASN1_TIME_set(NULL, t1); \ ASN1_TIME *at2 = ASN1_TIME_set(NULL, t2); \ int r = at1 != NULL && at2 != NULL \ && ASN1_TIME_compare(at1, at2) op 0; \ if (!r) \ test_fail_message(NULL, file, line, "time_t", s1, s2, #op, \ "[%s] compared to [%s]", \ print_time(at1), print_time(at2)); \ ASN1_STRING_free(at1); \ ASN1_STRING_free(at2); \ return r; \ } DEFINE_TIME_T_COMPARISON(eq, ==) DEFINE_TIME_T_COMPARISON(ne, !=) DEFINE_TIME_T_COMPARISON(gt, >) DEFINE_TIME_T_COMPARISON(ge, >=) DEFINE_TIME_T_COMPARISON(lt, <) DEFINE_TIME_T_COMPARISON(le, <=)
17,154
35.191983
81
c
openssl
openssl-master/test/testutil/testutil_init.c
/* * Copyright 2017-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 <string.h> #include <openssl/opensslconf.h> #include <openssl/trace.h> #include "apps.h" #include "../testutil.h" #ifndef OPENSSL_NO_TRACE typedef struct tracedata_st { BIO *bio; unsigned int ingroup:1; } tracedata; static size_t internal_trace_cb(const char *buf, size_t cnt, int category, int cmd, void *vdata) { int ret = 0; tracedata *trace_data = vdata; char buffer[256], *hex; CRYPTO_THREAD_ID tid; switch (cmd) { case OSSL_TRACE_CTRL_BEGIN: trace_data->ingroup = 1; tid = CRYPTO_THREAD_get_current_id(); hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid)); BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ", hex, OSSL_trace_get_category_name(category)); OPENSSL_free(hex); BIO_set_prefix(trace_data->bio, buffer); break; case OSSL_TRACE_CTRL_WRITE: ret = BIO_write(trace_data->bio, buf, cnt); break; case OSSL_TRACE_CTRL_END: trace_data->ingroup = 0; BIO_set_prefix(trace_data->bio, NULL); break; } return ret < 0 ? 0 : ret; } DEFINE_STACK_OF(tracedata) static STACK_OF(tracedata) *trace_data_stack; static void tracedata_free(tracedata *data) { BIO_free_all(data->bio); OPENSSL_free(data); } static STACK_OF(tracedata) *trace_data_stack; static void cleanup_trace(void) { sk_tracedata_pop_free(trace_data_stack, tracedata_free); } static void setup_trace_category(int category) { BIO *channel; tracedata *trace_data; BIO *bio = NULL; if (OSSL_trace_enabled(category)) return; bio = BIO_new(BIO_f_prefix()); channel = BIO_push(bio, BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT)); trace_data = OPENSSL_zalloc(sizeof(*trace_data)); if (trace_data == NULL || bio == NULL || (trace_data->bio = channel) == NULL || OSSL_trace_set_callback(category, internal_trace_cb, trace_data) == 0 || sk_tracedata_push(trace_data_stack, trace_data) == 0) { fprintf(stderr, "warning: unable to setup trace callback for category '%s'.\n", OSSL_trace_get_category_name(category)); OSSL_trace_set_callback(category, NULL, NULL); BIO_free_all(channel); } } static void setup_trace(const char *str) { char *val; /* * We add this handler as early as possible to ensure it's executed * as late as possible, i.e. after the TRACE code has done its cleanup * (which happens last in OPENSSL_cleanup). */ atexit(cleanup_trace); trace_data_stack = sk_tracedata_new_null(); val = OPENSSL_strdup(str); if (val != NULL) { char *valp = val; char *item; for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) { int category = OSSL_trace_get_category_num(item); if (category == OSSL_TRACE_CATEGORY_ALL) { while (++category < OSSL_TRACE_CATEGORY_NUM) setup_trace_category(category); break; } else if (category > 0) { setup_trace_category(category); } else { fprintf(stderr, "warning: unknown trace category: '%s'.\n", item); } } } OPENSSL_free(val); } #endif /* OPENSSL_NO_TRACE */ int global_init(void) { #ifndef OPENSSL_NO_TRACE setup_trace(getenv("OPENSSL_TRACE")); #endif return 1; }
3,916
25.828767
79
c
openssl
openssl-master/test/testutil/tu_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 */ #include <stdlib.h> /* size_t */ #include <openssl/bn.h> #include <openssl/bio.h> #include "../testutil.h" #define TEST_SKIP_CODE 123 int subtest_level(void); int openssl_error_cb(const char *str, size_t len, void *u); const BIO_METHOD *BIO_f_tap(void); void test_fail_message_prefix(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op); void test_fail_string_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const char *m1, size_t l1, const char *m2, size_t l2); void test_fail_bignum_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const BIGNUM *bn1, const BIGNUM *bn2); void test_fail_bignum_mono_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const BIGNUM *bn); void test_fail_memory_message(const char *prefix, const char *file, int line, const char *type, const char *left, const char *right, const char *op, const unsigned char *m1, size_t l1, const unsigned char *m2, size_t l2); __owur int setup_test_framework(int argc, char *argv[]); __owur int pulldown_test_framework(int ret); __owur int run_tests(const char *test_prog_name); void set_test_title(const char *title); typedef enum OPTION_choice_default { OPT_ERR = -1, OPT_EOF = 0, OPT_TEST_ENUM } OPTION_CHOICE_DEFAULT; void opt_check_usage(void);
2,472
38.887097
74
h
openssl
openssl-master/util/check-format-test-positives.c
/* * Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2015-2022 * * 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 */ /* * This demonstrates/tests cases where check-format.pl should report issues. * Some of the reports are due to sanity checks for proper nesting of comment * delimiters and parenthesis-like symbols, e.g., on unexpected/unclosed braces. */ /* * The '@'s after '*' are used for self-tests: they mark lines containing * a single flaw that should be reported. Normally it should be reported * while handling the given line, but in case of delayed checks there is a * following digit indicating the number of reports expected for this line. */ /* For each of the following set of lines the tool should complain once */ /*@ tab character: */ /*@ intra-line carriage return character: */ /*@ non-printable ASCII character:  */ /*@ non-ASCII character: ä */ /*@ whitespace at EOL: */ // /*@ end-of-line comment style not allowed (for C90 compatibility) */ /*@0 intra-line comment indent off by 1, reported unless sloppy-cmt */ /*X */ /*@2 missing spc or '*' after comment start reported unless sloppy-spc */ /* X*/ /*@ missing space before comment end , reported unless sloppy-spc */ /*@ comment starting delimiter: /* inside intra-line comment */ /*@0 *@ above multi-line comment start indent off by 1, reported unless sloppy-cmt; this comment line is too long *@ multi-line comment indent further off by 1 relative to comment start *@ multi-line comment ending with text on last line */ /*@2 multi-line comment starting with text on first line *@ comment starting delimiter: /* inside multi-line comment *@ multi-line comment indent off by -1 *X*@ no spc after leading '*' in multi-line comment, reported unless sloppy-spc *@0 more than two spaces after . in comment, no more reported *@0 more than two spaces after ? in comment, no more reported *@0 more than two spaces after ! in comment, no more reported */ /*@ multi-line comment end indent off by -1 (relative to comment start) */ */ /*@ unexpected comment ending delimiter outside comment */ /*- '-' for formatted comment not allowed in intra-line comment */ /*@ comment line is 4 columns tooooooooooooooooo wide, reported unless sloppy-len */ /*@ comment line is 5 columns toooooooooooooooooooooooooooooooooooooooooooooo wide */ #if ~0 /*@ '#if' with constant condition */ #endif /*@ indent of preproc. directive off by 1 (must be 0) */ #define X (1 + 1) /*@0 extra space in body, reported unless sloppy-spc */ #define Y 1 /*@ extra space before body, reported unless sloppy-spc */ \ #define Z /*@2 preprocessor directive within multi-line directive */ typedef struct { /*@0 extra space in code, reported unless sloppy-spc */ enum { /*@1 extra space in intra-line comment, no more reported */ w = 0 /*@ hanging expr indent off by 1, or 3 for lines after '{' */ && 1, /*@ hanging expr indent off by 3, or -1 for leading '&&' */ x = 1, /*@ hanging expr indent off by -1 */ y,z /*@ no space after ',', reported unless sloppy-spc */ } e_member ; /*@ space before ';', reported unless sloppy-spc */ int v[1; /*@ unclosed bracket in type declaration */ union { /*@ statement/type declaration indent off by -1 */ struct{} s; /*@ no space before '{', reported unless sloppy-spc */ }u_member; /*@ no space after '}', reported unless sloppy-spc */ } s_type; /*@ statement/type declaration indent off by 4 */ int* somefunc(); /*@ no space before '*' in type decl, r unless sloppy-spc */ void main(int n) { /*@ opening brace at end of function definition header */ for (; ; ) ; /*@ space before ')', reported unless sloppy-spc */ for ( ; x; y) ; /*@2 space after '(' and before ';', unless sloppy-spc */ for (;;n++) { /*@ missing space after ';', reported unless sloppy-spc */ return; /*@0 (1-line) single statement in braces */ }} /*@2 code after '}' outside expr */ } /*@ unexpected closing brace (too many '}') outside expr */ ) /*@ unexpected closing paren outside expr */ #endif /*@ unexpected #endif */ int f (int a, /*@ space after fn before '(', reported unless sloppy-spc */ int b, /*@ hanging expr indent off by -1 */ long I) /*@ single-letter name 'I' */ { int x; /*@ code after '{' opening a block */ int xx = 1) + /*@ unexpected closing parenthesis */ 0L < /*@ constant on LHS of comparison operator */ a] - /*@ unexpected closing bracket */ 3: * /*@ unexpected ':' (without preceding '?') within expr */ 4}; /*@ unexpected closing brace within expression */ char y[] = { /*@0 unclosed brace within initializer/enum expression */ 1* 1, /*@ no space etc. before '*', reported unless sloppy-spc */ 2, /*@ hanging expr indent (for lines after '{') off by 1 */ (xx /*@0 unclosed parenthesis in expression */ ? y /*@0 unclosed '? (conditional expression) */ [0; /*@4 unclosed bracket in expression */ /*@ blank line within local decls */ s_type s; /*@2 local variable declaration indent off by -1 */ t_type t; /*@ local variable declaration indent again off by -1 */ /* */ /*@0 missing blank line after local decls */ somefunc(a, /*@2 statement indent off by -1 */ "aligned" /*@ expr indent off by -2 accepted if sloppy-hang */ "right" , b, /*@ expr indent off by -1 */ b, /*@ expr indent as on line above, accepted if sloppy-hang */ b, /*@ expr indent off -8 but @ extra indent accepted if sloppy-hang */ "again aligned" /*@ expr indent off by -9 (left of stmt indent, */ "right", abc == /*@ .. so reported also with sloppy-hang; this line is too long */ 456 # define MAC(A) (A) /*@ nesting indent of preprocessor directive off by 1 */ ? 1 /*@ hanging expr indent off by 1 */ : 2); /*@ hanging expr indent off by 2, or 1 for leading ':' */ if(a /*@ missing space after 'if', reported unless sloppy-spc */ /*@0 intra-line comment indent off by -1 (not: by 3 due to '&&') */ && ! 0 /*@2 space after '!', reported unless sloppy-spc */ || b == /*@ hanging expr indent off by 2, or -2 for leading '||' */ (x<<= 1) + /*@ missing space before '<<=' reported unless sloppy-spc */ (xx+= 2) + /*@ missing space before '+=', reported unless sloppy-spc */ (a^ 1) + /*@ missing space before '^', reported unless sloppy-spc */ (y *=z) + /*@ missing space after '*=' reported unless sloppy-spc */ a %2 / /*@ missing space after '%', reported unless sloppy-spc */ 1 +/* */ /*@ no space before comment, reported unless sloppy-spc */ /* */+ /*@ no space after comment, reported unless sloppy-spc */ s. e_member) /*@ space after '.', reported unless sloppy-spc */ xx = a + b /*@ extra single-statement indent off by 1 */ + 0; /*@ two times extra single-statement indent off by 3 */ if (a ++) /*@ space before postfix '++', reported unless sloppy-spc */ { /*@ {' not on same line as preceding 'if' */ c; /*@0 single stmt in braces, reported on 1-stmt */ } else /*@ missing '{' on same line after '} else' */ { /*@ statement indent off by 2 */ d; /*@0 single stmt in braces, reported on 1-stmt */ } /*@ statement indent off by 6 */ if (1) f(a, /*@ (non-brace) code after end of 'if' condition */ b); else /*@ (non-brace) code before 'else' */ do f(c, c); /*@ (non-brace) code after 'do' */ while ( 2); /*@ space after '(', reported unless sloppy-spc */ b; c; /*@ more than one statement per line */ outer: /*@ outer label special indent off by 1 */ do{ /*@ missing space before '{', reported unless sloppy-spc */ inner: /*@ inner label normal indent off by 1 */ f (3, /*@ space after fn before '(', reported unless sloppy-spc */ 4); /*@0 false negative: should report single stmt in braces */ } /*@0 'while' not on same line as preceding '}' */ while (a+ 0); /*@2 missing space before '+', reported unless sloppy-spc */ switch (b ) { /*@ space before ')', reported unless sloppy-spc */ case 1: /*@ 'case' special statement indent off by -1 */ case(2): /*@ missing space after 'case', reported unless sloppy-spc */ default: ; /*@ code after 'default:' */ } /*@ statement indent off by -4 */ return( /*@ missing space after 'return', reported unless sloppy-spc */ x); } /*@ code before block-level '}' */ /* Here the tool should stop complaining apart from the below issues at EOF */ void f_looong_body() { ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; /*@ 2 essentially blank lines before, if !sloppy-spc */ } /*@ function body length > 200 lines */ #if X /*@0 unclosed #if */ struct t { /*@0 unclosed brace at decl/block level */ enum { /*@0 unclosed brace at enum/expression level */ v = (1 /*@0 unclosed parenthesis */ etyp /*@0 blank line follows just before EOF, if !sloppy-spc: */
11,068
29.747222
110
c
openssl
openssl-master/util/quicserver.c
/* * Copyright 2023 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 */ /* * This is a temporary test server for QUIC. It will eventually be replaced * by s_server and removed once we have full QUIC server support. */ #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> #include "internal/e_os.h" #include "internal/sockets.h" #include "internal/quic_tserver.h" #include "internal/time.h" static void wait_for_activity(QUIC_TSERVER *qtserv) { fd_set readfds, writefds; fd_set *readfdsp = NULL, *writefdsp = NULL; struct timeval timeout, *timeoutp = NULL; int width; int sock; BIO *bio = ossl_quic_tserver_get0_rbio(qtserv); OSSL_TIME deadline; BIO_get_fd(bio, &sock); if (ossl_quic_tserver_get_net_read_desired(qtserv)) { readfdsp = &readfds; FD_ZERO(readfdsp); openssl_fdset(sock, readfdsp); } if (ossl_quic_tserver_get_net_write_desired(qtserv)) { writefdsp = &writefds; FD_ZERO(writefdsp); openssl_fdset(sock, writefdsp); } deadline = ossl_quic_tserver_get_deadline(qtserv); if (!ossl_time_is_infinite(deadline)) { timeout = ossl_time_to_timeval(ossl_time_subtract(deadline, ossl_time_now())); timeoutp = &timeout; } width = sock + 1; if (readfdsp == NULL && writefdsp == NULL && timeoutp == NULL) return; select(width, readfdsp, writefdsp, NULL, timeoutp); } /* Helper function to create a BIO connected to the server */ static BIO *create_dgram_bio(int family, const char *hostname, const char *port) { int sock = -1; BIO_ADDRINFO *res; const BIO_ADDRINFO *ai = NULL; BIO *bio; if (BIO_sock_init() != 1) return NULL; /* * Lookup IP address info for the server. */ if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_SERVER, family, SOCK_DGRAM, 0, &res)) return NULL; /* * Loop through all the possible addresses for the server and find one * we can create and start listening on */ for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { /* Create the UDP socket */ sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0); if (sock == -1) continue; /* Start listening on the socket */ if (!BIO_listen(sock, BIO_ADDRINFO_address(ai), 0)) { BIO_closesocket(sock); sock = -1; continue; } /* Set to non-blocking mode */ if (!BIO_socket_nbio(sock, 1)) { BIO_closesocket(sock); sock = -1; continue; } } /* Free the address information resources we allocated earlier */ BIO_ADDRINFO_free(res); /* If sock is -1 then we've been unable to connect to the server */ if (sock == -1) return NULL; /* Create a BIO to wrap the socket*/ bio = BIO_new(BIO_s_datagram()); if (bio == NULL) BIO_closesocket(sock); /* * Associate the newly created BIO with the underlying socket. By * passing BIO_CLOSE here the socket will be automatically closed when * the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which * case you must close the socket explicitly when it is no longer * needed. */ BIO_set_fd(bio, sock, BIO_CLOSE); return bio; } static void usage(void) { printf("quicserver [-6] hostname port certfile keyfile\n"); } int main(int argc, char *argv[]) { QUIC_TSERVER_ARGS tserver_args = {0}; QUIC_TSERVER *qtserv = NULL; int ipv6 = 0; int argnext = 1; BIO *bio = NULL; char *hostname, *port, *certfile, *keyfile; int ret = EXIT_FAILURE; unsigned char reqbuf[1024]; size_t numbytes, reqbytes = 0; const char reqterm[] = { '\r', '\n', '\r', '\n' }; const char *msg = "Hello world\n"; unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' }; int first = 1; if (argc == 0) return EXIT_FAILURE; while (argnext < argc) { if (argv[argnext][0] != '-') break; if (strcmp(argv[argnext], "-6") == 0) { ipv6 = 1; } else { printf("Unrecognised argument %s\n", argv[argnext]); usage(); return EXIT_FAILURE; } argnext++; } if (argc - argnext != 4) { usage(); return EXIT_FAILURE; } hostname = argv[argnext++]; port = argv[argnext++]; certfile = argv[argnext++]; keyfile = argv[argnext++]; bio = create_dgram_bio(ipv6 ? AF_INET6 : AF_INET, hostname, port); if (bio == NULL || !BIO_up_ref(bio)) { BIO_free(bio); printf("Unable to create server socket\n"); return EXIT_FAILURE; } tserver_args.libctx = NULL; tserver_args.net_rbio = bio; tserver_args.net_wbio = bio; tserver_args.alpn = alpn; tserver_args.alpnlen = sizeof(alpn); qtserv = ossl_quic_tserver_new(&tserver_args, certfile, keyfile); if (qtserv == NULL) { printf("Failed to create the QUIC_TSERVER\n"); goto end; } printf("Starting quicserver\n"); printf("Note that this utility will be removed in a future OpenSSL version\n"); printf("For test purposes only. Not for use in a production environment\n"); /* Ownership of the BIO is passed to qtserv */ bio = NULL; /* Read the request */ do { if (first) first = 0; else wait_for_activity(qtserv); ossl_quic_tserver_tick(qtserv); if (ossl_quic_tserver_read(qtserv, 0, reqbuf, sizeof(reqbuf), &numbytes)) { if (numbytes > 0) { fwrite(reqbuf, 1, numbytes, stdout); } reqbytes += numbytes; } } while (reqbytes < sizeof(reqterm) || memcmp(reqbuf + reqbytes - sizeof(reqterm), reqterm, sizeof(reqterm)) != 0); /* Send the response */ ossl_quic_tserver_tick(qtserv); if (!ossl_quic_tserver_write(qtserv, 0, (unsigned char *)msg, strlen(msg), &numbytes)) goto end; if (!ossl_quic_tserver_conclude(qtserv, 0)) goto end; /* Wait until all data we have sent has been acked */ while (!ossl_quic_tserver_is_terminated(qtserv) && !ossl_quic_tserver_is_stream_totally_acked(qtserv, 0)) { ossl_quic_tserver_tick(qtserv); wait_for_activity(qtserv); } while (!ossl_quic_tserver_shutdown(qtserv)) wait_for_activity(qtserv); /* Close down here */ ret = EXIT_SUCCESS; end: /* Free twice because we did an up-ref */ BIO_free(bio); BIO_free(bio); ossl_quic_tserver_free(qtserv); return ret; }
7,127
27.062992
83
c
null
systemd-main/coccinelle/macros.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Collected macros from our systemd codebase to make the cocci semantic * parser happy. Inspired by the original cocci macros file * /usr/lib64/coccinelle/standard.h (including the YACFE_* symbols) */ // General #define PTR_TO_PID(x) // src/basic/macro.h #define _printf_(a, b) __attribute__((__format__(printf, a, b))) #define _alloc_(...) __attribute__((__alloc_size__(__VA_ARGS__))) #define _sentinel_ __attribute__((__sentinel__)) #define _section_(x) __attribute__((__section__(x))) #define _used_ __attribute__((__used__)) #define _unused_ __attribute__((__unused__)) #define _destructor_ __attribute__((__destructor__)) #define _pure_ __attribute__((__pure__)) #define _const_ __attribute__((__const__)) #define _deprecated_ __attribute__((__deprecated__)) #define _packed_ __attribute__((__packed__)) #define _malloc_ __attribute__((__malloc__)) #define _weak_ __attribute__((__weak__)) #define _likely_(x) (__builtin_expect(!!(x), 1)) #define _unlikely_(x) (__builtin_expect(!!(x), 0)) #define _public_ __attribute__((__visibility__("default"))) #define _hidden_ __attribute__((__visibility__("hidden"))) #define _weakref_(x) __attribute__((__weakref__(#x))) #define _align_(x) __attribute__((__aligned__(x))) #define _alignas_(x) __attribute__((__aligned__(__alignof(x)))) #define _alignptr_ __attribute__((__aligned__(sizeof(void*)))) #define _cleanup_(x) __attribute__((__cleanup__(x))) #define _fallthrough_ #define _noreturn_ __attribute__((__noreturn__)) #define thread_local __thread #define ELEMENTSOF(x) \ (__builtin_choose_expr( \ !__builtin_types_compatible_p(typeof(x), typeof(&*(x))), \ sizeof(x)/sizeof((x)[0]), \ VOID_0)) // src/basic/umask-util.h #define _cleanup_umask_ #define WITH_UMASK(mask) \ for (_cleanup_umask_ mode_t _saved_umask_ = umask(mask) | S_IFMT; \ FLAGS_SET(_saved_umask_, S_IFMT); \ _saved_umask_ &= 0777) // src/basic/hashmap.h #define _IDX_ITERATOR_FIRST (UINT_MAX - 1) #define HASHMAP_FOREACH(e, h) YACFE_ITERATOR #define ORDERED_HASHMAP_FOREACH(e, h) YACFE_ITERATOR #define HASHMAP_FOREACH_KEY(e, k, h) YACFE_ITERATOR #define ORDERED_HASHMAP_FOREACH_KEY(e, k, h) YACFE_ITERATOR // src/basic/list.h #define LIST_HEAD(t,name) \ t *name #define LIST_FIELDS(t,name) \ t *name##_next, *name##_prev #define LIST_HEAD_INIT(head) \ do { \ (head) = NULL; \ } while (false) #define LIST_INIT(name,item) \ do { \ typeof(*(item)) *_item = (item); \ assert(_item); \ _item->name##_prev = _item->name##_next = NULL; \ } while (false) #define LIST_PREPEND(name,head,item) \ do { \ typeof(*(head)) **_head = &(head), *_item = (item); \ assert(_item); \ if ((_item->name##_next = *_head)) \ _item->name##_next->name##_prev = _item; \ _item->name##_prev = NULL; \ *_head = _item; \ } while (false) #define LIST_APPEND(name,head,item) \ do { \ typeof(*(head)) **_hhead = &(head), *_tail; \ LIST_FIND_TAIL(name, *_hhead, _tail); \ LIST_INSERT_AFTER(name, *_hhead, _tail, item); \ } while (false) #define LIST_REMOVE(name,head,item) \ do { \ typeof(*(head)) **_head = &(head), *_item = (item); \ assert(_item); \ if (_item->name##_next) \ _item->name##_next->name##_prev = _item->name##_prev; \ if (_item->name##_prev) \ _item->name##_prev->name##_next = _item->name##_next; \ else { \ assert(*_head == _item); \ *_head = _item->name##_next; \ } \ _item->name##_next = _item->name##_prev = NULL; \ } while (false) #define LIST_FIND_HEAD(name,item,head) \ do { \ typeof(*(item)) *_item = (item); \ if (!_item) \ (head) = NULL; \ else { \ while (_item->name##_prev) \ _item = _item->name##_prev; \ (head) = _item; \ } \ } while (false) #define LIST_FIND_TAIL(name,item,tail) \ do { \ typeof(*(item)) *_item = (item); \ if (!_item) \ (tail) = NULL; \ else { \ while (_item->name##_next) \ _item = _item->name##_next; \ (tail) = _item; \ } \ } while (false) #define LIST_INSERT_AFTER(name,head,a,b) \ do { \ typeof(*(head)) **_head = &(head), *_a = (a), *_b = (b); \ assert(_b); \ if (!_a) { \ if ((_b->name##_next = *_head)) \ _b->name##_next->name##_prev = _b; \ _b->name##_prev = NULL; \ *_head = _b; \ } else { \ if ((_b->name##_next = _a->name##_next)) \ _b->name##_next->name##_prev = _b; \ _b->name##_prev = _a; \ _a->name##_next = _b; \ } \ } while (false) #define LIST_INSERT_BEFORE(name,head,a,b) \ do { \ typeof(*(head)) **_head = &(head), *_a = (a), *_b = (b); \ assert(_b); \ if (!_a) { \ if (!*_head) { \ _b->name##_next = NULL; \ _b->name##_prev = NULL; \ *_head = _b; \ } else { \ typeof(*(head)) *_tail = (head); \ while (_tail->name##_next) \ _tail = _tail->name##_next; \ _b->name##_next = NULL; \ _b->name##_prev = _tail; \ _tail->name##_next = _b; \ } \ } else { \ if ((_b->name##_prev = _a->name##_prev)) \ _b->name##_prev->name##_next = _b; \ else \ *_head = _b; \ _b->name##_next = _a; \ _a->name##_prev = _b; \ } \ } while (false) #define LIST_JUST_US(name,item) \ (!(item)->name##_prev && !(item)->name##_next) #define LIST_FOREACH(name,i,head) \ for ((i) = (head); (i); (i) = (i)->name##_next) #define LIST_FOREACH_SAFE(name,i,n,head) \ for ((i) = (head); (i) && (((n) = (i)->name##_next), 1); (i) = (n)) #define LIST_FOREACH_BEFORE(name,i,p) \ for ((i) = (p)->name##_prev; (i); (i) = (i)->name##_prev) #define LIST_FOREACH_AFTER(name,i,p) \ for ((i) = (p)->name##_next; (i); (i) = (i)->name##_next) #define LIST_FOREACH_OTHERS(name,i,p) \ for (({ \ (i) = (p); \ while ((i) && (i)->name##_prev) \ (i) = (i)->name##_prev; \ if ((i) == (p)) \ (i) = (p)->name##_next; \ }); \ (i); \ (i) = (i)->name##_next == (p) ? (p)->name##_next : (i)->name##_next) #define LIST_LOOP_BUT_ONE(name,i,head,p) \ for ((i) = (p)->name##_next ? (p)->name##_next : (head); \ (i) != (p); \ (i) = (i)->name##_next ? (i)->name##_next : (head)) #define LIST_JOIN(name,a,b) \ do { \ assert(b); \ if (!(a)) \ (a) = (b); \ else { \ typeof(*(a)) *_head = (b), *_tail; \ LIST_FIND_TAIL(name, (a), _tail); \ _tail->name##_next = _head; \ _head->name##_prev = _tail; \ } \ (b) = NULL; \ } while (false) // src/basic/strv.h #define STRV_FOREACH(s, l) YACFE_ITERATOR #define STRV_FOREACH_BACKWARDS(s, l) YACFE_ITERATOR #define STRV_FOREACH_PAIR(x, y, l) YACFE_ITERATOR // src/basic/socket-util.h #define CMSG_BUFFER_TYPE(size) \ union { \ struct cmsghdr cmsghdr; \ uint8_t buf[size]; \ uint8_t align_check[(size) >= CMSG_SPACE(0) && \ (size) == CMSG_ALIGN(size) ? 1 : -1]; \ } // src/libsystemd/sd-device/device-util.h #define FOREACH_DEVICE_PROPERTY(device, key, value) YACFE_ITERATOR #define FOREACH_DEVICE_TAG(device, tag) YACFE_ITERATOR #define FOREACH_DEVICE_CURRENT_TAG(device, tag) YACFE_ITERATOR #define FOREACH_DEVICE_SYSATTR(device, attr) YACFE_ITERATOR #define FOREACH_DEVICE_DEVLINK(device, devlink) YACFE_ITERATOR #define FOREACH_DEVICE(enumerator, device) YACFE_ITERATOR #define FOREACH_SUBSYSTEM(enumerator, device) YACFE_ITERATOR // src/basic/dirent-util.h #define FOREACH_DIRENT(de, d, on_error) YACFE_ITERATOR #define FOREACH_DIRENT_ALL(de, d, on_error) YACFE_ITERATOR
13,772
58.366379
81
h
null
systemd-main/man/event-quick-child.c
/* SPDX-License-Identifier: MIT-0 */ #include <assert.h> #include <stdio.h> #include <unistd.h> #include <sd-event.h> int main(int argc, char **argv) { pid_t pid = fork(); assert(pid >= 0); /* SIGCHLD signal must be blocked for sd_event_add_child to work */ sigset_t ss; sigemptyset(&ss); sigaddset(&ss, SIGCHLD); sigprocmask(SIG_BLOCK, &ss, NULL); if (pid == 0) /* child */ sleep(1); else { /* parent */ sd_event *e = NULL; int r; /* Create the default event loop */ sd_event_default(&e); assert(e); /* We create a floating child event source (attached to 'e'). * The default handler will be called with 666 as userdata, which * will become the exit value of the loop. */ r = sd_event_add_child(e, NULL, pid, WEXITED, NULL, (void*) 666); assert(r >= 0); r = sd_event_loop(e); assert(r == 666); sd_event_unref(e); } return 0; }
927
20.581395
69
c
null
systemd-main/man/glib-event-glue.c
/* SPDX-License-Identifier: MIT-0 */ #include <stdlib.h> #include <glib.h> #include <systemd/sd-event.h> typedef struct SDEventSource { GSource source; GPollFD pollfd; sd_event *event; } SDEventSource; static gboolean event_prepare(GSource *source, gint *timeout_) { return sd_event_prepare(((SDEventSource *)source)->event) > 0; } static gboolean event_check(GSource *source) { return sd_event_wait(((SDEventSource *)source)->event, 0) > 0; } static gboolean event_dispatch(GSource *source, GSourceFunc callback, gpointer user_data) { return sd_event_dispatch(((SDEventSource *)source)->event) > 0; } static void event_finalize(GSource *source) { sd_event_unref(((SDEventSource *)source)->event); } static GSourceFuncs event_funcs = { .prepare = event_prepare, .check = event_check, .dispatch = event_dispatch, .finalize = event_finalize, }; GSource *g_sd_event_create_source(sd_event *event) { SDEventSource *source; source = (SDEventSource *)g_source_new(&event_funcs, sizeof(SDEventSource)); source->event = sd_event_ref(event); source->pollfd.fd = sd_event_get_fd(event); source->pollfd.events = G_IO_IN | G_IO_HUP | G_IO_ERR; g_source_add_poll((GSource *)source, &source->pollfd); return (GSource *)source; }
1,263
24.795918
91
c
null
systemd-main/man/hwdb-usb-device.c
/* SPDX-License-Identifier: MIT-0 */ #include <stdio.h> #include <stdint.h> #include <sd-hwdb.h> int print_usb_properties(uint16_t vid, uint16_t pid) { char match[STRLEN("usb:vp") + DECIMAL_STR_MAX(uint16_t) * 2]; sd_hwdb *hwdb; const char *key, *value; int r; /* Match this USB vendor and product ID combination */ xsprintf(match, "usb:v%04Xp%04X", vid, pid); r = sd_hwdb_new(&hwdb); if (r < 0) return r; SD_HWDB_FOREACH_PROPERTY(hwdb, match, key, value) printf("%s: \"%s\" → \"%s\"\n", match, key, value); sd_hwdb_unref(hwdb); return 0; } int main(int argc, char **argv) { print_usb_properties(0x046D, 0xC534); return 0; }
666
20.516129
63
c
null
systemd-main/man/inotify-watch-tmp.c
/* SPDX-License-Identifier: MIT-0 */ #include <stdio.h> #include <string.h> #include <sys/inotify.h> #include <systemd/sd-event.h> #define _cleanup_(f) __attribute__((cleanup(f))) static int inotify_handler(sd_event_source *source, const struct inotify_event *event, void *userdata) { const char *desc = NULL; sd_event_source_get_description(source, &desc); if (event->mask & IN_Q_OVERFLOW) printf("inotify-handler <%s>: overflow\n", desc); else if (event->mask & IN_CREATE) printf("inotify-handler <%s>: create on %s\n", desc, event->name); else if (event->mask & IN_DELETE) printf("inotify-handler <%s>: delete on %s\n", desc, event->name); else if (event->mask & IN_MOVED_TO) printf("inotify-handler <%s>: moved-to on %s\n", desc, event->name); /* Terminate the program if an "exit" file appears */ if ((event->mask & (IN_CREATE|IN_MOVED_TO)) && strcmp(event->name, "exit") == 0) sd_event_exit(sd_event_source_get_event(source), 0); return 1; } int main(int argc, char **argv) { _cleanup_(sd_event_unrefp) sd_event *event = NULL; _cleanup_(sd_event_source_unrefp) sd_event_source *source1 = NULL, *source2 = NULL; const char *path1 = argc > 1 ? argv[1] : "/tmp"; const char *path2 = argc > 2 ? argv[2] : NULL; /* Note: failure handling is omitted for brevity */ sd_event_default(&event); sd_event_add_inotify(event, &source1, path1, IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_TO, inotify_handler, NULL); if (path2) sd_event_add_inotify(event, &source2, path2, IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_TO, inotify_handler, NULL); sd_event_loop(event); return 0; }
1,806
29.627119
85
c
null
systemd-main/man/journal-iterate-poll.c
/* SPDX-License-Identifier: MIT-0 */ #include <poll.h> #include <time.h> #include <systemd/sd-journal.h> int wait_for_changes(sd_journal *j) { uint64_t t; int msec; struct pollfd pollfd; sd_journal_get_timeout(j, &t); if (t == (uint64_t) -1) msec = -1; else { struct timespec ts; uint64_t n; clock_gettime(CLOCK_MONOTONIC, &ts); n = (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000; msec = t > n ? (int) ((t - n + 999) / 1000) : 0; } pollfd.fd = sd_journal_get_fd(j); pollfd.events = sd_journal_get_events(j); poll(&pollfd, 1, msec); return sd_journal_process(j); }
618
21.107143
59
c
null
systemd-main/man/journal-iterate-wait.c
/* SPDX-License-Identifier: MIT-0 */ #include <errno.h> #include <stdio.h> #include <systemd/sd-journal.h> int main(int argc, char *argv[]) { int r; sd_journal *j; r = sd_journal_open(&j, SD_JOURNAL_LOCAL_ONLY); if (r < 0) { errno = -r; fprintf(stderr, "Failed to open journal: %m\n"); return 1; } for (;;) { const void *d; size_t l; r = sd_journal_next(j); if (r < 0) { errno = -r; fprintf(stderr, "Failed to iterate to next entry: %m\n"); break; } if (r == 0) { /* Reached the end, let's wait for changes, and try again */ r = sd_journal_wait(j, (uint64_t) -1); if (r < 0) { errno = -r; fprintf(stderr, "Failed to wait for changes: %m\n"); break; } continue; } r = sd_journal_get_data(j, "MESSAGE", &d, &l); if (r < 0) { errno = -r; fprintf(stderr, "Failed to read message field: %m\n"); continue; } printf("%.*s\n", (int) l, (const char*) d); } sd_journal_close(j); return 0; }
1,048
21.804348
66
c
null
systemd-main/man/journal-stream-fd.c
/* SPDX-License-Identifier: MIT-0 */ #include <errno.h> #include <syslog.h> #include <stdio.h> #include <unistd.h> #include <systemd/sd-journal.h> #include <systemd/sd-daemon.h> int main(int argc, char *argv[]) { int fd; FILE *log; fd = sd_journal_stream_fd("test", LOG_INFO, 1); if (fd < 0) { errno = -fd; fprintf(stderr, "Failed to create stream fd: %m\n"); return 1; } log = fdopen(fd, "w"); if (!log) { fprintf(stderr, "Failed to create file object: %m\n"); close(fd); return 1; } fprintf(log, "Hello World!\n"); fprintf(log, SD_WARNING "This is a warning!\n"); fclose(log); return 0; }
641
20.4
58
c
null
systemd-main/man/logcontrol-example.c
/* SPDX-License-Identifier: MIT-0 */ /* Implements the LogControl1 interface as per specification: * https://www.freedesktop.org/software/systemd/man/org.freedesktop.LogControl1.html * * Compile with 'cc logcontrol-example.c $(pkg-config --libs --cflags libsystemd)' * * To get and set properties via busctl: * * $ busctl --user get-property org.freedesktop.Example \ * /org/freedesktop/LogControl1 \ * org.freedesktop.LogControl1 \ * SyslogIdentifier * s "example" * $ busctl --user get-property org.freedesktop.Example \ * /org/freedesktop/LogControl1 \ * org.freedesktop.LogControl1 \ * LogTarget * s "journal" * $ busctl --user get-property org.freedesktop.Example \ * /org/freedesktop/LogControl1 \ * org.freedesktop.LogControl1 \ * LogLevel * s "info" * $ busctl --user set-property org.freedesktop.Example \ * /org/freedesktop/LogControl1 \ * org.freedesktop.LogControl1 \ * LogLevel \ * "s" debug * $ busctl --user get-property org.freedesktop.Example \ * /org/freedesktop/LogControl1 \ * org.freedesktop.LogControl1 \ * LogLevel * s "debug" */ #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <syslog.h> #include <systemd/sd-bus.h> #include <systemd/sd-journal.h> #define _cleanup_(f) __attribute__((cleanup(f))) #define check(log_level, x) ({ \ int _r = (x); \ errno = _r < 0 ? -_r : 0; \ sd_journal_print((log_level), #x ": %m"); \ if (_r < 0) \ return EXIT_FAILURE; \ }) typedef enum LogTarget { LOG_TARGET_JOURNAL, LOG_TARGET_KMSG, LOG_TARGET_SYSLOG, LOG_TARGET_CONSOLE, _LOG_TARGET_MAX, } LogTarget; static const char* const log_target_table[_LOG_TARGET_MAX] = { [LOG_TARGET_JOURNAL] = "journal", [LOG_TARGET_KMSG] = "kmsg", [LOG_TARGET_SYSLOG] = "syslog", [LOG_TARGET_CONSOLE] = "console", }; static const char* const log_level_table[LOG_DEBUG + 1] = { [LOG_EMERG] = "emerg", [LOG_ALERT] = "alert", [LOG_CRIT] = "crit", [LOG_ERR] = "err", [LOG_WARNING] = "warning", [LOG_NOTICE] = "notice", [LOG_INFO] = "info", [LOG_DEBUG] = "debug", }; typedef struct object { const char *syslog_identifier; LogTarget log_target; int log_level; } object; static int property_get( sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *reply, void *userdata, sd_bus_error *error) { object *o = userdata; if (strcmp(property, "LogLevel") == 0) return sd_bus_message_append(reply, "s", log_level_table[o->log_level]); if (strcmp(property, "LogTarget") == 0) return sd_bus_message_append(reply, "s", log_target_table[o->log_target]); if (strcmp(property, "SyslogIdentifier") == 0) return sd_bus_message_append(reply, "s", o->syslog_identifier); return sd_bus_error_setf(error, SD_BUS_ERROR_UNKNOWN_PROPERTY, "Unknown property '%s'", property); } static int property_set( sd_bus *bus, const char *path, const char *interface, const char *property, sd_bus_message *message, void *userdata, sd_bus_error *error) { object *o = userdata; const char *value; int r; r = sd_bus_message_read(message, "s", &value); if (r < 0) return r; if (strcmp(property, "LogLevel") == 0) { for (int i = 0; i < LOG_DEBUG + 1; i++) if (strcmp(value, log_level_table[i]) == 0) { o->log_level = i; setlogmask(LOG_UPTO(i)); return 0; } return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid value for LogLevel: '%s'", value); } if (strcmp(property, "LogTarget") == 0) { for (LogTarget i = 0; i < _LOG_TARGET_MAX; i++) if (strcmp(value, log_target_table[i]) == 0) { o->log_target = i; return 0; } return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid value for LogTarget: '%s'", value); } return sd_bus_error_setf(error, SD_BUS_ERROR_UNKNOWN_PROPERTY, "Unknown property '%s'", property); } /* https://www.freedesktop.org/software/systemd/man/sd_bus_add_object.html */ static const sd_bus_vtable vtable[] = { SD_BUS_VTABLE_START(0), SD_BUS_WRITABLE_PROPERTY( "LogLevel", "s", property_get, property_set, 0, 0), SD_BUS_WRITABLE_PROPERTY( "LogTarget", "s", property_get, property_set, 0, 0), SD_BUS_PROPERTY( "SyslogIdentifier", "s", property_get, 0, SD_BUS_VTABLE_PROPERTY_CONST), SD_BUS_VTABLE_END }; int main(int argc, char **argv) { /* The bus should be relinquished before the program terminates. The cleanup * attribute allows us to do it nicely and cleanly whenever we exit the * block. */ _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; object o = { .log_level = LOG_INFO, .log_target = LOG_TARGET_JOURNAL, .syslog_identifier = "example", }; /* https://man7.org/linux/man-pages/man3/setlogmask.3.html * Programs using syslog() instead of sd_journal can use this API to cut logs * emission at the source. */ setlogmask(LOG_UPTO(o.log_level)); /* Acquire a connection to the bus, letting the library work out the details. * https://www.freedesktop.org/software/systemd/man/sd_bus_default.html */ check(o.log_level, sd_bus_default(&bus)); /* Publish an interface on the bus, specifying our well-known object access * path and public interface name. * https://www.freedesktop.org/software/systemd/man/sd_bus_add_object.html * https://dbus.freedesktop.org/doc/dbus-tutorial.html */ check(o.log_level, sd_bus_add_object_vtable(bus, NULL, "/org/freedesktop/LogControl1", "org.freedesktop.LogControl1", vtable, &o)); /* By default the service is assigned an ephemeral name. Also add a fixed * one, so that clients know whom to call. * https://www.freedesktop.org/software/systemd/man/sd_bus_request_name.html */ check(o.log_level, sd_bus_request_name(bus, "org.freedesktop.Example", 0)); for (;;) { /* https://www.freedesktop.org/software/systemd/man/sd_bus_wait.html */ check(o.log_level, sd_bus_wait(bus, UINT64_MAX)); /* https://www.freedesktop.org/software/systemd/man/sd_bus_process.html */ check(o.log_level, sd_bus_process(bus, NULL)); } /* https://www.freedesktop.org/software/systemd/man/sd_bus_release_name.html */ check(o.log_level, sd_bus_release_name(bus, "org.freedesktop.Example")); return 0; }
7,656
30.904167
84
c
null
systemd-main/man/print-unit-path-call-method.c
/* SPDX-License-Identifier: MIT-0 */ /* This is equivalent to: * busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 \ * org.freedesktop.systemd1.Manager GetUnitByPID $$ * * Compile with 'cc print-unit-path-call-method.c -lsystemd' */ #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <systemd/sd-bus.h> #define _cleanup_(f) __attribute__((cleanup(f))) #define DESTINATION "org.freedesktop.systemd1" #define PATH "/org/freedesktop/systemd1" #define INTERFACE "org.freedesktop.systemd1.Manager" #define MEMBER "GetUnitByPID" static int log_error(int error, const char *message) { errno = -error; fprintf(stderr, "%s: %m\n", message); return error; } int main(int argc, char **argv) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; int r; r = sd_bus_open_system(&bus); if (r < 0) return log_error(r, "Failed to acquire bus"); r = sd_bus_call_method(bus, DESTINATION, PATH, INTERFACE, MEMBER, &error, &reply, "u", (unsigned) getpid()); if (r < 0) return log_error(r, MEMBER " call failed"); const char *ans; r = sd_bus_message_read(reply, "o", &ans); if (r < 0) return log_error(r, "Failed to read reply"); printf("Unit path is \"%s\".\n", ans); return 0; }
1,428
26.480769
110
c
null
systemd-main/man/print-unit-path.c
/* SPDX-License-Identifier: MIT-0 */ /* This is equivalent to: * busctl call org.freedesktop.systemd1 /org/freedesktop/systemd1 \ * org.freedesktop.systemd1.Manager GetUnitByPID $$ * * Compile with 'cc print-unit-path.c -lsystemd' */ #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <systemd/sd-bus.h> #define _cleanup_(f) __attribute__((cleanup(f))) #define DESTINATION "org.freedesktop.systemd1" #define PATH "/org/freedesktop/systemd1" #define INTERFACE "org.freedesktop.systemd1.Manager" #define MEMBER "GetUnitByPID" static int log_error(int error, const char *message) { errno = -error; fprintf(stderr, "%s: %m\n", message); return error; } int main(int argc, char **argv) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL; int r; r = sd_bus_open_system(&bus); if (r < 0) return log_error(r, "Failed to acquire bus"); r = sd_bus_message_new_method_call(bus, &m, DESTINATION, PATH, INTERFACE, MEMBER); if (r < 0) return log_error(r, "Failed to create bus message"); r = sd_bus_message_append(m, "u", (unsigned) getpid()); if (r < 0) return log_error(r, "Failed to append to bus message"); r = sd_bus_call(bus, m, -1, &error, &reply); if (r < 0) return log_error(r, MEMBER " call failed"); const char *ans; r = sd_bus_message_read(reply, "o", &ans); if (r < 0) return log_error(r, "Failed to read reply"); printf("Unit path is \"%s\".\n", ans); return 0; }
1,688
26.688525
75
c
null
systemd-main/man/sd_bus_error-example.c
/* SPDX-License-Identifier: MIT-0 */ #include <errno.h> #include <string.h> #include <unistd.h> #include <sd-bus.h> int writer_with_negative_errno_return(int fd, sd_bus_error *error) { const char *message = "Hello, World!\n"; ssize_t n = write(fd, message, strlen(message)); if (n >= 0) return n; /* On success, return the number of bytes written, possibly 0. */ /* On error, initialize the error structure, and also propagate the errno * value that write(2) set for us. */ return sd_bus_error_set_errnof(error, errno, "Failed to write to fd %i: %m", fd); }
579
29.526316
83
c
null
systemd-main/man/send-unit-files-changed.c
/* SPDX-License-Identifier: MIT-0 */ #include <systemd/sd-bus.h> #define _cleanup_(f) __attribute__((cleanup(f))) int send_unit_files_changed(sd_bus *bus) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *message = NULL; int r; r = sd_bus_message_new_signal(bus, &message, "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "UnitFilesChanged"); if (r < 0) return r; return sd_bus_send(bus, message, NULL); }
537
27.315789
67
c
null
systemd-main/man/vtable-example.c
/* SPDX-License-Identifier: MIT-0 */ #include <errno.h> #include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <systemd/sd-bus.h> #define _cleanup_(f) __attribute__((cleanup(f))) #define check(x) ({ \ int r = (x); \ errno = r < 0 ? -r : 0; \ printf(#x ": %m\n"); \ if (r < 0) \ return EXIT_FAILURE; \ }) typedef struct object { char *name; uint32_t number; } object; static int method(sd_bus_message *m, void *userdata, sd_bus_error *error) { printf("Got called with userdata=%p\n", userdata); if (sd_bus_message_is_method_call(m, "org.freedesktop.systemd.VtableExample", "Method4")) return 1; const char *string; check(sd_bus_message_read(m, "s", &string)); check(sd_bus_reply_method_return(m, "s", string)); return 1; } static const sd_bus_vtable vtable[] = { SD_BUS_VTABLE_START(0), SD_BUS_METHOD( "Method1", "s", "s", method, 0), SD_BUS_METHOD_WITH_NAMES_OFFSET( "Method2", "so", SD_BUS_PARAM(string) SD_BUS_PARAM(path), "s", SD_BUS_PARAM(returnstring), method, offsetof(object, number), SD_BUS_VTABLE_DEPRECATED), SD_BUS_METHOD_WITH_ARGS_OFFSET( "Method3", SD_BUS_ARGS("s", string, "o", path), SD_BUS_RESULT("s", returnstring), method, offsetof(object, number), SD_BUS_VTABLE_UNPRIVILEGED), SD_BUS_METHOD_WITH_ARGS( "Method4", SD_BUS_NO_ARGS, SD_BUS_NO_RESULT, method, SD_BUS_VTABLE_UNPRIVILEGED), SD_BUS_SIGNAL( "Signal1", "so", 0), SD_BUS_SIGNAL_WITH_NAMES( "Signal2", "so", SD_BUS_PARAM(string) SD_BUS_PARAM(path), 0), SD_BUS_SIGNAL_WITH_ARGS( "Signal3", SD_BUS_ARGS("s", string, "o", path), 0), SD_BUS_WRITABLE_PROPERTY( "AutomaticStringProperty", "s", NULL, NULL, offsetof(object, name), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE), SD_BUS_WRITABLE_PROPERTY( "AutomaticIntegerProperty", "u", NULL, NULL, offsetof(object, number), SD_BUS_VTABLE_PROPERTY_EMITS_INVALIDATION), SD_BUS_VTABLE_END }; int main(int argc, char **argv) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; sd_bus_default(&bus); object object = { .number = 666 }; check((object.name = strdup("name")) != NULL); check(sd_bus_add_object_vtable(bus, NULL, "/org/freedesktop/systemd/VtableExample", "org.freedesktop.systemd.VtableExample", vtable, &object)); check(sd_bus_request_name(bus, "org.freedesktop.systemd.VtableExample", 0)); for (;;) { check(sd_bus_wait(bus, UINT64_MAX)); check(sd_bus_process(bus, NULL)); } check(sd_bus_release_name(bus, "org.freedesktop.systemd.VtableExample")); free(object.name); return 0; }
3,404
29.132743
76
c
null
systemd-main/src/ac-power/ac-power.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include "battery-util.h" #include "build.h" #include "main-func.h" static bool arg_verbose = false; static enum { ACTION_AC_POWER, ACTION_LOW, } arg_action = ACTION_AC_POWER; static void help(void) { printf("%s\n\n" "Report whether we are connected to an external power source.\n\n" " -h --help Show this help\n" " --version Show package version\n" " -v --verbose Show state as text\n" " --low Check if battery is discharging and low\n", program_invocation_short_name); } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_LOW, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "verbose", no_argument, NULL, 'v' }, { "low", no_argument, NULL, ARG_LOW }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "hv", options, NULL)) >= 0) switch (c) { case 'h': help(); return 0; case ARG_VERSION: return version(); case 'v': arg_verbose = true; break; case ARG_LOW: arg_action = ACTION_LOW; break; case '?': return -EINVAL; default: assert_not_reached(); } if (optind < argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s takes no arguments.", program_invocation_short_name); return 1; } static int run(int argc, char *argv[]) { int r; /* This is mostly intended to be used for scripts which want * to detect whether AC power is plugged in or not. */ log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; if (arg_action == ACTION_AC_POWER) { r = on_ac_power(); if (r < 0) return log_error_errno(r, "Failed to read AC status: %m"); } else { r = battery_is_discharging_and_low(); if (r < 0) return log_error_errno(r, "Failed to read battery discharging + low status: %m"); } if (arg_verbose) puts(yes_no(r)); return r == 0; } DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
3,009
26.363636
105
c
null
systemd-main/src/analyze/analyze-blame.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-blame.h" #include "analyze-time-data.h" #include "format-table.h" int verb_blame(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL; _cleanup_(table_unrefp) Table *table = NULL; TableCell *cell; int n, r; r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); n = acquire_time_data(bus, /* require_finished = */ false, &times); if (n <= 0) return n; table = table_new("time", "unit"); if (!table) return log_oom(); table_set_header(table, false); assert_se(cell = table_get_cell(table, 0, 0)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; r = table_set_align_percent(table, cell, 100); if (r < 0) return r; assert_se(cell = table_get_cell(table, 0, 1)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; r = table_set_sort(table, (size_t) 0); if (r < 0) return r; r = table_set_reverse(table, 0, true); if (r < 0) return r; for (UnitTimes *u = times; u->has_data; u++) { if (u->time <= 0) continue; r = table_add_many(table, TABLE_TIMESPAN_MSEC, u->time, TABLE_STRING, u->name); if (r < 0) return table_log_add_error(r); } pager_open(arg_pager_flags); r = table_print(table, NULL); if (r < 0) return r; return EXIT_SUCCESS; }
1,968
27.128571
75
c
null
systemd-main/src/analyze/analyze-calendar.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-calendar.h" #include "calendarspec.h" #include "format-table.h" #include "terminal-util.h" static int test_calendar_one(usec_t n, const char *p) { _cleanup_(calendar_spec_freep) CalendarSpec *spec = NULL; _cleanup_(table_unrefp) Table *table = NULL; _cleanup_free_ char *t = NULL; TableCell *cell; int r; r = calendar_spec_from_string(p, &spec); if (r < 0) { log_error_errno(r, "Failed to parse calendar specification '%s': %m", p); time_parsing_hint(p, /* calendar= */ false, /* timestamp= */ true, /* timespan= */ true); return r; } r = calendar_spec_to_string(spec, &t); if (r < 0) return log_error_errno(r, "Failed to format calendar specification '%s': %m", p); table = table_new_vertical(); if (!table) return log_oom(); assert_se(cell = table_get_cell(table, 0, 0)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; assert_se(cell = table_get_cell(table, 0, 1)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; if (!streq(t, p)) { r = table_add_many(table, TABLE_FIELD, "Original form", TABLE_STRING, p); if (r < 0) return table_log_add_error(r); } r = table_add_many(table, TABLE_FIELD, "Normalized form", TABLE_STRING, t); if (r < 0) return table_log_add_error(r); for (unsigned i = 0; i < arg_iterations; i++) { usec_t next; r = calendar_spec_next_usec(spec, n, &next); if (r == -ENOENT) { if (i == 0) { r = table_add_many(table, TABLE_FIELD, "Next elapse", TABLE_STRING, "never", TABLE_SET_COLOR, ansi_highlight_yellow()); if (r < 0) return table_log_add_error(r); } break; } if (r < 0) return log_error_errno(r, "Failed to determine next elapse for '%s': %m", p); if (i == 0) { r = table_add_many(table, TABLE_FIELD, "Next elapse", TABLE_TIMESTAMP, next, TABLE_SET_COLOR, ansi_highlight_blue()); if (r < 0) return table_log_add_error(r); } else { int k = DECIMAL_STR_WIDTH(i + 1); if (k < 8) k = 8 - k; else k = 0; r = table_add_cell_stringf_full(table, NULL, TABLE_FIELD, "Iteration #%u", i+1); if (r < 0) return table_log_add_error(r); r = table_add_many(table, TABLE_TIMESTAMP, next, TABLE_SET_COLOR, ansi_highlight_blue()); if (r < 0) return table_log_add_error(r); } if (!in_utc_timezone()) { r = table_add_many(table, TABLE_FIELD, "(in UTC)", TABLE_TIMESTAMP_UTC, next); if (r < 0) return table_log_add_error(r); } r = table_add_many(table, TABLE_FIELD, "From now", TABLE_TIMESTAMP_RELATIVE, next); if (r < 0) return table_log_add_error(r); n = next; } return table_print(table, NULL); } int verb_calendar(int argc, char *argv[], void *userdata) { int r = 0; usec_t n; if (arg_base_time != USEC_INFINITY) n = arg_base_time; else n = now(CLOCK_REALTIME); /* We want to use the same "base" for all expressions */ STRV_FOREACH(p, strv_skip(argv, 1)) { int k; k = test_calendar_one(n, *p); if (r == 0 && k < 0) r = k; if (p[1]) putchar('\n'); } return r; }
5,051
34.829787
105
c
null
systemd-main/src/analyze/analyze-capability.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-capability.h" #include "cap-list.h" #include "capability-util.h" #include "format-table.h" int verb_capabilities(int argc, char *argv[], void *userdata) { _cleanup_(table_unrefp) Table *table = NULL; unsigned last_cap; int r; table = table_new("name", "number"); if (!table) return log_oom(); (void) table_set_align_percent(table, table_get_cell(table, 0, 1), 100); /* Determine the maximum of the last cap known by the kernel and by us */ last_cap = MAX((unsigned) CAP_LAST_CAP, cap_last_cap()); if (strv_isempty(strv_skip(argv, 1))) for (unsigned c = 0; c <= last_cap; c++) { r = table_add_many(table, TABLE_STRING, capability_to_name(c) ?: "cap_???", TABLE_UINT, c); if (r < 0) return table_log_add_error(r); } else { for (int i = 1; i < argc; i++) { int c; c = capability_from_name(argv[i]); if (c < 0 || (unsigned) c > last_cap) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Capability \"%s\" not known.", argv[i]); r = table_add_many(table, TABLE_STRING, capability_to_name(c) ?: "cap_???", TABLE_UINT, (unsigned) c); if (r < 0) return table_log_add_error(r); } (void) table_set_sort(table, (size_t) 1); } pager_open(arg_pager_flags); r = table_print(table, NULL); if (r < 0) return r; return EXIT_SUCCESS; }
1,986
33.859649
121
c
null
systemd-main/src/analyze/analyze-cat-config.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-cat-config.h" #include "conf-files.h" #include "constants.h" #include "nulstr-util.h" #include "path-util.h" #include "pretty-print.h" #include "strv.h" int verb_cat_config(int argc, char *argv[], void *userdata) { char **list; int r; pager_open(arg_pager_flags); list = strv_skip(argv, 1); STRV_FOREACH(arg, list) { const char *t = NULL; if (arg != list) print_separator(); if (path_is_absolute(*arg)) { NULSTR_FOREACH(dir, CONF_PATHS_NULSTR("")) { t = path_startswith(*arg, dir); if (t) break; } if (!t) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path %s does not start with any known prefix.", *arg); } else t = *arg; r = conf_files_cat(arg_root, t); if (r < 0) return r; } return EXIT_SUCCESS; }
1,290
27.688889
110
c
null
systemd-main/src/analyze/analyze-compare-versions.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include "analyze-compare-versions.h" #include "compare-operator.h" #include "macro.h" #include "string-util.h" #include "strv.h" int verb_compare_versions(int argc, char *argv[], void *userdata) { const char *v1 = ASSERT_PTR(argv[1]), *v2 = ASSERT_PTR(argv[argc-1]); int r; assert(IN_SET(argc, 3, 4)); assert(argv); /* We only output a warning on invalid version strings (instead of failing), since the comparison * functions try to handle invalid strings graceful and it's still interesting to see what the * comparison result will be. */ if (!version_is_valid(v1)) log_warning("Version string 1 is not valid, comparing anyway: %s", v1); if (!version_is_valid(v2)) log_warning("Version string 2 is not valid, comparing anyway: %s", v2); if (argc == 3) { r = strverscmp_improved(v1, v2); printf("%s %s %s\n", isempty(v1) ? "''" : v1, comparison_operator(r), isempty(v2) ? "''" : v2); /* This matches the exit convention used by rpmdev-vercmp. * We don't use named values because 11 and 12 don't have names. */ return r < 0 ? 12 : r > 0 ? 11 : 0; } else { const char *op = ASSERT_PTR(argv[2]); CompareOperator operator; assert(argc == 4); operator = parse_compare_operator(&op, COMPARE_ALLOW_TEXTUAL); if (operator < 0 || !isempty(op)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown operator \"%s\".", op); r = version_or_fnmatch_compare(operator, v1, v2); if (r < 0) return log_error_errno(r, "Failed to compare versions: %m"); return r ? EXIT_SUCCESS : EXIT_FAILURE; } }
2,018
37.09434
105
c
null
systemd-main/src/analyze/analyze-condition.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdlib.h> #include "analyze.h" #include "analyze-condition.h" #include "analyze-verify-util.h" #include "condition.h" #include "conf-parser.h" #include "load-fragment.h" #include "service.h" static int parse_condition(Unit *u, const char *line) { assert(u); assert(line); for (ConditionType t = 0; t < _CONDITION_TYPE_MAX; t++) { ConfigParserCallback callback; Condition **target; const char *p, *name; name = condition_type_to_string(t); p = startswith(line, name); if (p) target = &u->conditions; else { name = assert_type_to_string(t); p = startswith(line, name); if (!p) continue; target = &u->asserts; } p += strspn(p, WHITESPACE); if (*p != '=') continue; p++; p += strspn(p, WHITESPACE); if (condition_takes_path(t)) callback = config_parse_unit_condition_path; else callback = config_parse_unit_condition_string; return callback(NULL, "(cmdline)", 0, NULL, 0, name, t, p, target, u); } return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot parse \"%s\".", line); } _printf_(7, 8) static int log_helper(void *userdata, int level, int error, const char *file, int line, const char *func, const char *format, ...) { Unit *u = ASSERT_PTR(userdata); va_list ap; int r; /* "upgrade" debug messages */ level = MIN(LOG_INFO, level); va_start(ap, format); r = log_object_internalv(level, error, file, line, func, NULL, u->id, NULL, NULL, format, ap); va_end(ap); return r; } static int verify_conditions(char **lines, RuntimeScope scope, const char *unit, const char *root) { _cleanup_(manager_freep) Manager *m = NULL; Unit *u; int r, q = 1; if (unit) { _cleanup_strv_free_ char **filenames = NULL; _cleanup_free_ char *var = NULL; filenames = strv_new(unit); if (!filenames) return log_oom(); r = verify_generate_path(&var, filenames); if (r < 0) return log_error_errno(r, "Failed to generate unit load path: %m"); assert_se(set_unit_path(var) >= 0); } r = manager_new(scope, MANAGER_TEST_RUN_MINIMAL, &m); if (r < 0) return log_error_errno(r, "Failed to initialize manager: %m"); log_debug("Starting manager..."); r = manager_startup(m, /* serialization= */ NULL, /* fds= */ NULL, root); if (r < 0) return r; if (unit) { _cleanup_free_ char *prepared = NULL; r = verify_prepare_filename(unit, &prepared); if (r < 0) return log_error_errno(r, "Failed to prepare filename %s: %m", unit); r = manager_load_startable_unit_or_warn(m, NULL, prepared, &u); if (r < 0) return r; } else { r = unit_new_for_name(m, sizeof(Service), "test.service", &u); if (r < 0) return log_error_errno(r, "Failed to create test.service: %m"); STRV_FOREACH(line, lines) { r = parse_condition(u, *line); if (r < 0) return r; } } condition_test_logger_t logger = arg_quiet ? NULL : log_helper; r = condition_test_list(u->asserts, environ, assert_type_to_string, logger, u); if (u->asserts) log_full(arg_quiet ? LOG_DEBUG : LOG_NOTICE, "Asserts %s.", r > 0 ? "succeeded" : "failed"); q = condition_test_list(u->conditions, environ, condition_type_to_string, logger, u); if (u->conditions) log_full(arg_quiet ? LOG_DEBUG : LOG_NOTICE, "Conditions %s.", q > 0 ? "succeeded" : "failed"); return r > 0 && q > 0 ? 0 : -EIO; } int verb_condition(int argc, char *argv[], void *userdata) { int r; r = verify_conditions(strv_skip(argv, 1), arg_runtime_scope, arg_unit, arg_root); if (r < 0) return r; return EXIT_SUCCESS; }
4,843
31.952381
132
c
null
systemd-main/src/analyze/analyze-critical-chain.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze-critical-chain.h" #include "analyze-time-data.h" #include "analyze.h" #include "bus-error.h" #include "copy.h" #include "path-util.h" #include "sort-util.h" #include "special.h" #include "static-destruct.h" #include "strv.h" #include "terminal-util.h" static Hashmap *unit_times_hashmap = NULL; STATIC_DESTRUCTOR_REGISTER(unit_times_hashmap, hashmap_freep); static int list_dependencies_print( const char *name, unsigned level, unsigned branches, bool last, UnitTimes *times, BootTimes *boot) { for (unsigned i = level; i != 0; i--) printf("%s", special_glyph(branches & (1 << (i-1)) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE)); printf("%s", special_glyph(last ? SPECIAL_GLYPH_TREE_RIGHT : SPECIAL_GLYPH_TREE_BRANCH)); if (times) { if (timestamp_is_set(times->time)) printf("%s%s @%s +%s%s", ansi_highlight_red(), name, FORMAT_TIMESPAN(times->activating - boot->userspace_time, USEC_PER_MSEC), FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal()); else if (times->activated > boot->userspace_time) printf("%s @%s", name, FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC)); else printf("%s", name); } else printf("%s", name); printf("\n"); return 0; } static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***deps) { _cleanup_free_ char *path = NULL; assert(bus); assert(name); assert(deps); path = unit_dbus_path_from_name(name); if (!path) return -ENOMEM; return bus_get_unit_property_strv(bus, path, "After", deps); } static int list_dependencies_compare(char *const *a, char *const *b) { usec_t usa = 0, usb = 0; UnitTimes *times; times = hashmap_get(unit_times_hashmap, *a); if (times) usa = times->activated; times = hashmap_get(unit_times_hashmap, *b); if (times) usb = times->activated; return CMP(usb, usa); } static bool times_in_range(const UnitTimes *times, const BootTimes *boot) { return times && times->activated > 0 && times->activated <= boot->finish_time; } static int list_dependencies_one(sd_bus *bus, const char *name, unsigned level, char ***units, unsigned branches) { _cleanup_strv_free_ char **deps = NULL; int r; usec_t service_longest = 0; int to_print = 0; UnitTimes *times; BootTimes *boot; if (strv_extend(units, name)) return log_oom(); r = list_dependencies_get_dependencies(bus, name, &deps); if (r < 0) return r; typesafe_qsort(deps, strv_length(deps), list_dependencies_compare); r = acquire_boot_times(bus, /* require_finished = */ true, &boot); if (r < 0) return r; STRV_FOREACH(c, deps) { times = hashmap_get(unit_times_hashmap, *c); if (times_in_range(times, boot) && times->activated >= service_longest) service_longest = times->activated; } if (service_longest == 0) return r; STRV_FOREACH(c, deps) { times = hashmap_get(unit_times_hashmap, *c); if (times_in_range(times, boot) && service_longest - times->activated <= arg_fuzz) to_print++; } if (!to_print) return r; STRV_FOREACH(c, deps) { times = hashmap_get(unit_times_hashmap, *c); if (!times_in_range(times, boot) || service_longest - times->activated > arg_fuzz) continue; to_print--; r = list_dependencies_print(*c, level, branches, to_print == 0, times, boot); if (r < 0) return r; if (strv_contains(*units, *c)) { r = list_dependencies_print("...", level + 1, (branches << 1) | (to_print ? 1 : 0), true, NULL, boot); if (r < 0) return r; continue; } r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (to_print ? 1 : 0)); if (r < 0) return r; if (to_print == 0) break; } return 0; } static int list_dependencies(sd_bus *bus, const char *name) { _cleanup_strv_free_ char **units = NULL; UnitTimes *times; int r; const char *id; _cleanup_free_ char *path = NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; BootTimes *boot; assert(bus); path = unit_dbus_path_from_name(name); if (!path) return -ENOMEM; r = sd_bus_get_property( bus, "org.freedesktop.systemd1", path, "org.freedesktop.systemd1.Unit", "Id", &error, &reply, "s"); if (r < 0) return log_error_errno(r, "Failed to get ID: %s", bus_error_message(&error, r)); r = sd_bus_message_read(reply, "s", &id); if (r < 0) return bus_log_parse_error(r); times = hashmap_get(unit_times_hashmap, id); r = acquire_boot_times(bus, /* require_finished = */ true, &boot); if (r < 0) return r; if (times) { if (times->time) printf("%s%s +%s%s\n", ansi_highlight_red(), id, FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal()); else if (times->activated > boot->userspace_time) printf("%s @%s\n", id, FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC)); else printf("%s\n", id); } return list_dependencies_one(bus, name, 0, &units, 0); } int verb_critical_chain(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL; int n, r; r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); n = acquire_time_data(bus, /* require_finished = */ true, &times); if (n <= 0) return n; for (UnitTimes *u = times; u->has_data; u++) { r = hashmap_ensure_put(&unit_times_hashmap, &string_hash_ops, u->name, u); if (r < 0) return log_error_errno(r, "Failed to add entry to hashmap: %m"); } pager_open(arg_pager_flags); puts("The time when unit became active or started is printed after the \"@\" character.\n" "The time the unit took to start is printed after the \"+\" character.\n"); if (argc > 1) STRV_FOREACH(name, strv_skip(argv, 1)) list_dependencies(bus, *name); else list_dependencies(bus, SPECIAL_DEFAULT_TARGET); return EXIT_SUCCESS; }
7,898
33.194805
126
c
null
systemd-main/src/analyze/analyze-dot.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-dot.h" #include "bus-error.h" #include "bus-locator.h" #include "bus-unit-util.h" #include "glob-util.h" #include "terminal-util.h" static int graph_one_property( sd_bus *bus, const UnitInfo *u, const char *prop, const char *color, char *patterns[], char *from_patterns[], char *to_patterns[]) { _cleanup_strv_free_ char **units = NULL; bool match_patterns; int r; assert(u); assert(prop); assert(color); match_patterns = strv_fnmatch(patterns, u->id); if (!strv_isempty(from_patterns) && !match_patterns && !strv_fnmatch(from_patterns, u->id)) return 0; r = bus_get_unit_property_strv(bus, u->unit_path, prop, &units); if (r < 0) return r; STRV_FOREACH(unit, units) { bool match_patterns2; match_patterns2 = strv_fnmatch(patterns, *unit); if (!strv_isempty(to_patterns) && !match_patterns2 && !strv_fnmatch(to_patterns, *unit)) continue; if (!strv_isempty(patterns) && !match_patterns && !match_patterns2) continue; printf("\t\"%s\"->\"%s\" [color=\"%s\"];\n", u->id, *unit, color); } return 0; } static int graph_one(sd_bus *bus, const UnitInfo *u, char *patterns[], char *from_patterns[], char *to_patterns[]) { int r; assert(bus); assert(u); if (IN_SET(arg_dot, DEP_ORDER, DEP_ALL)) { r = graph_one_property(bus, u, "After", "green", patterns, from_patterns, to_patterns); if (r < 0) return r; } if (IN_SET(arg_dot, DEP_REQUIRE, DEP_ALL)) { r = graph_one_property(bus, u, "Requires", "black", patterns, from_patterns, to_patterns); if (r < 0) return r; r = graph_one_property(bus, u, "Requisite", "darkblue", patterns, from_patterns, to_patterns); if (r < 0) return r; r = graph_one_property(bus, u, "Wants", "grey66", patterns, from_patterns, to_patterns); if (r < 0) return r; r = graph_one_property(bus, u, "Conflicts", "red", patterns, from_patterns, to_patterns); if (r < 0) return r; } return 0; } static int expand_patterns(sd_bus *bus, char **patterns, char ***ret) { _cleanup_strv_free_ char **expanded_patterns = NULL; int r; STRV_FOREACH(pattern, patterns) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_free_ char *unit = NULL, *unit_id = NULL; if (strv_extend(&expanded_patterns, *pattern) < 0) return log_oom(); if (string_is_glob(*pattern)) continue; unit = unit_dbus_path_from_name(*pattern); if (!unit) return log_oom(); r = sd_bus_get_property_string( bus, "org.freedesktop.systemd1", unit, "org.freedesktop.systemd1.Unit", "Id", &error, &unit_id); if (r < 0) return log_error_errno(r, "Failed to get ID: %s", bus_error_message(&error, r)); if (!streq(*pattern, unit_id)) { if (strv_extend(&expanded_patterns, unit_id) < 0) return log_oom(); } } *ret = TAKE_PTR(expanded_patterns); /* do not free */ return 0; } int verb_dot(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_strv_free_ char **expanded_patterns = NULL; _cleanup_strv_free_ char **expanded_from_patterns = NULL; _cleanup_strv_free_ char **expanded_to_patterns = NULL; int r; UnitInfo u; r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); r = expand_patterns(bus, strv_skip(argv, 1), &expanded_patterns); if (r < 0) return r; r = expand_patterns(bus, arg_dot_from_patterns, &expanded_from_patterns); if (r < 0) return r; r = expand_patterns(bus, arg_dot_to_patterns, &expanded_to_patterns); if (r < 0) return r; r = bus_call_method(bus, bus_systemd_mgr, "ListUnits", &error, &reply, NULL); if (r < 0) return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r)); r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)"); if (r < 0) return bus_log_parse_error(r); printf("digraph systemd {\n"); while ((r = bus_parse_unit_info(reply, &u)) > 0) { r = graph_one(bus, &u, expanded_patterns, expanded_from_patterns, expanded_to_patterns); if (r < 0) return r; } if (r < 0) return bus_log_parse_error(r); printf("}\n"); log_info(" Color legend: black = Requires\n" " dark blue = Requisite\n" " dark grey = Wants\n" " red = Conflicts\n" " green = After\n"); if (on_tty() && !arg_quiet) log_notice("-- You probably want to process this output with graphviz' dot tool.\n" "-- Try a shell pipeline like 'systemd-analyze dot | dot -Tsvg > systemd.svg'!\n"); return 0; }
6,364
33.781421
116
c
null
systemd-main/src/analyze/analyze-dump.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "sd-bus.h" #include "analyze-dump.h" #include "analyze.h" #include "bus-error.h" #include "bus-locator.h" #include "bus-util.h" #include "copy.h" static int dump_fallback(sd_bus *bus) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; const char *text; int r; assert(bus); r = bus_call_method(bus, bus_systemd_mgr, "Dump", &error, &reply, NULL); if (r < 0) return log_error_errno(r, "Failed to call Dump: %s", bus_error_message(&error, r)); r = sd_bus_message_read(reply, "s", &text); if (r < 0) return bus_log_parse_error(r); fputs(text, stdout); return 0; } static int dump(sd_bus *bus) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; int r; r = bus_call_method(bus, bus_systemd_mgr, "DumpByFileDescriptor", &error, &reply, NULL); if (IN_SET(r, -EACCES, -EBADR)) return 0; /* Fall back to non-fd method. We need to do this even if the bus supports sending * fds to cater to very old managers which didn't have the fd-based method. */ if (r < 0) return log_error_errno(r, "Failed to call DumpByFileDescriptor: %s", bus_error_message(&error, r)); return dump_fd_reply(reply); } static int dump_patterns_fallback(sd_bus *bus, char **patterns) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL; const char *text; int r; r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "DumpUnitsMatchingPatterns"); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_append_strv(m, patterns); if (r < 0) return bus_log_create_error(r); r = sd_bus_call(bus, m, 0, &error, &reply); if (r < 0) return log_error_errno(r, "Failed to call DumpUnitsMatchingPatterns: %s", bus_error_message(&error, r)); r = sd_bus_message_read(reply, "s", &text); if (r < 0) return bus_log_parse_error(r); fputs(text, stdout); return 0; } static int dump_patterns(sd_bus *bus, char **patterns) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL, *m = NULL; int r; r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "DumpUnitsMatchingPatternsByFileDescriptor"); if (r < 0) return bus_log_create_error(r); r = sd_bus_message_append_strv(m, patterns); if (r < 0) return bus_log_create_error(r); r = sd_bus_call(bus, m, 0, &error, &reply); if (r < 0) return log_error_errno(r, "Failed to call DumpUnitsMatchingPatternsByFileDescriptor: %s", bus_error_message(&error, r)); return dump_fd_reply(reply); } static int mangle_patterns(char **args, char ***ret) { _cleanup_strv_free_ char **mangled = NULL; int r; STRV_FOREACH(arg, args) { char *t; r = unit_name_mangle_with_suffix(*arg, NULL, UNIT_NAME_MANGLE_GLOB, ".service", &t); if (r < 0) return log_error_errno(r, "Failed to mangle name '%s': %m", *arg); r = strv_consume(&mangled, t); if (r < 0) return log_oom(); } if (strv_isempty(mangled)) mangled = strv_free(mangled); *ret = TAKE_PTR(mangled); return 0; } int verb_dump(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_strv_free_ char **patterns = NULL; int r; r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); pager_open(arg_pager_flags); r = mangle_patterns(strv_skip(argv, 1), &patterns); if (r < 0) return r; r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD); if (r < 0) return log_error_errno(r, "Unable to determine if bus connection supports fd passing: %m"); if (r > 0) r = patterns ? dump_patterns(bus, patterns) : dump(bus); if (r == 0) /* wasn't supported */ r = patterns ? dump_patterns_fallback(bus, patterns) : dump_fallback(bus); if (r < 0) return r; return EXIT_SUCCESS; }
4,971
33.054795
111
c
null
systemd-main/src/analyze/analyze-exit-status.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-exit-status.h" #include "exit-status.h" #include "format-table.h" int verb_exit_status(int argc, char *argv[], void *userdata) { _cleanup_(table_unrefp) Table *table = NULL; int r; table = table_new("name", "status", "class"); if (!table) return log_oom(); r = table_set_align_percent(table, table_get_cell(table, 0, 1), 100); if (r < 0) return log_error_errno(r, "Failed to right-align status: %m"); if (strv_isempty(strv_skip(argv, 1))) for (size_t i = 0; i < ELEMENTSOF(exit_status_mappings); i++) { if (!exit_status_mappings[i].name) continue; r = table_add_many(table, TABLE_STRING, exit_status_mappings[i].name, TABLE_INT, (int) i, TABLE_STRING, exit_status_class(i)); if (r < 0) return table_log_add_error(r); } else for (int i = 1; i < argc; i++) { int status; status = exit_status_from_string(argv[i]); if (status < 0) return log_error_errno(status, "Invalid exit status \"%s\".", argv[i]); assert(status >= 0 && (size_t) status < ELEMENTSOF(exit_status_mappings)); r = table_add_many(table, TABLE_STRING, exit_status_mappings[status].name ?: "-", TABLE_INT, status, TABLE_STRING, exit_status_class(status) ?: "-"); if (r < 0) return table_log_add_error(r); } pager_open(arg_pager_flags); r = table_print(table, NULL); if (r < 0) return r; return EXIT_SUCCESS; }
2,181
37.280702
103
c
null
systemd-main/src/analyze/analyze-fdstore.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze-fdstore.h" #include "analyze.h" #include "bus-error.h" #include "bus-locator.h" #include "fd-util.h" #include "format-table.h" static int dump_fdstore(sd_bus *bus, const char *arg) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; _cleanup_(table_unrefp) Table *table = NULL; _cleanup_free_ char *unit = NULL; int r; assert(bus); assert(arg); r = unit_name_mangle_with_suffix(arg, NULL, UNIT_NAME_MANGLE_GLOB, ".service", &unit); if (r < 0) return log_error_errno(r, "Failed to mangle name '%s': %m", arg); r = bus_call_method( bus, bus_systemd_mgr, "DumpUnitFileDescriptorStore", &error, &reply, "s", unit); if (r < 0) return log_error_errno(r, "Failed to call DumpUnitFileDescriptorStore: %s", bus_error_message(&error, r)); r = sd_bus_message_enter_container(reply, 'a', "(suuutuusu)"); if (r < 0) return bus_log_parse_error(r); table = table_new("fdname", "type", "devno", "inode", "rdevno", "path", "flags"); if (!table) return log_oom(); table_set_ersatz_string(table, TABLE_ERSATZ_DASH); (void) table_set_align_percent(table, TABLE_HEADER_CELL(3), 100); for (;;) { uint32_t mode, major, minor, rmajor, rminor, flags; const char *fdname, *path; uint64_t inode; r = sd_bus_message_read( reply, "(suuutuusu)", &fdname, &mode, &major, &minor, &inode, &rmajor, &rminor, &path, &flags); if (r < 0) return bus_log_parse_error(r); if (r == 0) break; r = table_add_many( table, TABLE_STRING, fdname, TABLE_MODE_INODE_TYPE, mode, TABLE_DEVNUM, makedev(major, minor), TABLE_UINT64, inode, TABLE_DEVNUM, makedev(rmajor, rminor), TABLE_PATH, path, TABLE_STRING, accmode_to_string(flags)); if (r < 0) return table_log_add_error(r); } r = sd_bus_message_exit_container(reply); if (r < 0) return r; if (FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF) && table_get_rows(table) <= 0) log_info("No file descriptors in fdstore of '%s'.", unit); else { r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, /* show_header= */true); if (r < 0) return log_error_errno(r, "Failed to output table: %m"); } return EXIT_SUCCESS; } int verb_fdstore(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; int r; r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); STRV_FOREACH(arg, strv_skip(argv, 1)) { r = dump_fdstore(bus, *arg); if (r < 0) return r; } return EXIT_SUCCESS; }
3,936
34.468468
114
c
null
systemd-main/src/analyze/analyze-inspect-elf.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-inspect-elf.h" #include "elf-util.h" #include "errno-util.h" #include "fd-util.h" #include "format-table.h" #include "format-util.h" #include "json.h" #include "path-util.h" #include "strv.h" static int analyze_elf(char **filenames, JsonFormatFlags json_flags) { int r; STRV_FOREACH(filename, filenames) { _cleanup_(json_variant_unrefp) JsonVariant *package_metadata = NULL; _cleanup_(table_unrefp) Table *t = NULL; _cleanup_free_ char *abspath = NULL; _cleanup_close_ int fd = -EBADF; r = path_make_absolute_cwd(*filename, &abspath); if (r < 0) return log_error_errno(r, "Could not make an absolute path out of \"%s\": %m", *filename); path_simplify(abspath); fd = RET_NERRNO(open(abspath, O_RDONLY|O_CLOEXEC)); if (fd < 0) return log_error_errno(fd, "Could not open \"%s\": %m", abspath); r = parse_elf_object(fd, abspath, /* fork_disable_dump= */false, NULL, &package_metadata); if (r < 0) return log_error_errno(r, "Parsing \"%s\" as ELF object failed: %m", abspath); t = table_new_vertical(); if (!t) return log_oom(); r = table_add_many( t, TABLE_FIELD, "path", TABLE_STRING, abspath); if (r < 0) return table_log_add_error(r); if (package_metadata) { JsonVariant *module_json; const char *module_name; JSON_VARIANT_OBJECT_FOREACH(module_name, module_json, package_metadata) { const char *field_name; JsonVariant *field; /* The ELF type and architecture are added as top-level objects, * since they are only parsed for the file itself, but the packaging * metadata is parsed recursively in core files, so there might be * multiple modules. */ if (STR_IN_SET(module_name, "elfType", "elfArchitecture")) { r = table_add_many( t, TABLE_FIELD, module_name, TABLE_STRING, json_variant_string(module_json)); if (r < 0) return table_log_add_error(r); continue; } /* path/elfType/elfArchitecture come first just once per file, * then we might have multiple modules, so add a separator between * them to make the output more readable. */ r = table_add_many(t, TABLE_EMPTY, TABLE_EMPTY); if (r < 0) return table_log_add_error(r); /* In case of core files the module name will be the executable, * but for binaries/libraries it's just the path, so don't print it * twice. */ if (!streq(abspath, module_name)) { r = table_add_many( t, TABLE_FIELD, "module name", TABLE_STRING, module_name); if (r < 0) return table_log_add_error(r); } JSON_VARIANT_OBJECT_FOREACH(field_name, field, module_json) if (json_variant_is_string(field)) { r = table_add_many( t, TABLE_FIELD, field_name, TABLE_STRING, json_variant_string(field)); if (r < 0) return table_log_add_error(r); } } } if (json_flags & JSON_FORMAT_OFF) { r = table_print(t, NULL); if (r < 0) return table_log_print_error(r); } else json_variant_dump(package_metadata, json_flags, stdout, NULL); } return 0; } int verb_elf_inspection(int argc, char *argv[], void *userdata) { pager_open(arg_pager_flags); return analyze_elf(strv_skip(argv, 1), arg_json_format_flags); }
5,501
46.025641
114
c
null
systemd-main/src/analyze/analyze-log-control.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-log-control.h" #include "verb-log-control.h" int verb_log_control(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; int r; assert(IN_SET(argc, 1, 2)); r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); r = verb_log_control_common(bus, "org.freedesktop.systemd1", argv[0], argc == 2 ? argv[1] : NULL); if (r < 0) return r; return EXIT_SUCCESS; }
621
26.043478
106
c
null
systemd-main/src/analyze/analyze-malloc.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "sd-bus.h" #include "analyze-malloc.h" #include "analyze.h" #include "bus-error.h" #include "bus-internal.h" static int dump_malloc_info(sd_bus *bus, char *service) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; int r; assert(bus); assert(service); r = sd_bus_call_method(bus, service, "/org/freedesktop/MemoryAllocation1", "org.freedesktop.MemoryAllocation1", "GetMallocInfo", &error, &reply, NULL); if (r < 0) return log_error_errno(r, "Failed to call GetMallocInfo on '%s': %s", service, bus_error_message(&error, r)); return dump_fd_reply(reply); } int verb_malloc(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; char **services = STRV_MAKE("org.freedesktop.systemd1"); int r; if (!strv_isempty(strv_skip(argv, 1))) { services = strv_skip(argv, 1); STRV_FOREACH(service, services) if (!service_name_is_valid(*service)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "D-Bus service name '%s' is not valid.", *service); } r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD); if (r < 0) return log_error_errno(r, "Unable to determine if bus connection supports fd passing: %m"); if (r == 0) return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unable to receive FDs over D-Bus."); pager_open(arg_pager_flags); STRV_FOREACH(service, services) { r = dump_malloc_info(bus, *service); if (r < 0) return r; } return EXIT_SUCCESS; }
2,221
33.71875
131
c
null
systemd-main/src/analyze/analyze-pcrs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-pcrs.h" #include "fileio.h" #include "format-table.h" #include "hexdecoct.h" #include "terminal-util.h" #include "tpm2-util.h" static int get_pcr_alg(const char **ret) { assert(ret); FOREACH_STRING(alg, "sha256", "sha1") { _cleanup_free_ char *p = NULL; if (asprintf(&p, "/sys/class/tpm/tpm0/pcr-%s/0", alg) < 0) return log_oom(); if (access(p, F_OK) < 0) { if (errno != ENOENT) return log_error_errno(errno, "Failed to determine whether %s exists: %m", p); } else { *ret = alg; return 1; } } log_notice("Kernel does not support reading PCR values."); *ret = NULL; return 0; } static int get_current_pcr(const char *alg, uint32_t pcr, void **ret, size_t *ret_size) { _cleanup_free_ char *p = NULL, *s = NULL; _cleanup_free_ void *buf = NULL; size_t ss = 0, bufsize = 0; int r; assert(alg); assert(ret); assert(ret_size); if (asprintf(&p, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32, alg, pcr) < 0) return log_oom(); r = read_virtual_file(p, 4096, &s, &ss); if (r < 0) return log_error_errno(r, "Failed to read '%s': %m", p); r = unhexmem(s, ss, &buf, &bufsize); if (r < 0) return log_error_errno(r, "Failed to decode hex PCR data '%s': %m", s); *ret = TAKE_PTR(buf); *ret_size = bufsize; return 0; } static int add_pcr_to_table(Table *table, const char *alg, uint32_t pcr) { _cleanup_free_ char *h = NULL; const char *color = NULL; int r; if (alg) { _cleanup_free_ void *buf = NULL; size_t bufsize = 0; r = get_current_pcr(alg, pcr, &buf, &bufsize); if (r < 0) return r; h = hexmem(buf, bufsize); if (!h) return log_oom(); /* Grey out PCRs that are not sensibly initialized */ if (memeqbyte(0, buf, bufsize) || memeqbyte(0xFFU, buf, bufsize)) color = ANSI_GREY; } r = table_add_many(table, TABLE_UINT32, pcr, TABLE_STRING, pcr_index_to_string(pcr), TABLE_STRING, h, TABLE_SET_COLOR, color); if (r < 0) return table_log_add_error(r); return 0; } int verb_pcrs(int argc, char *argv[], void *userdata) { _cleanup_(table_unrefp) Table *table = NULL; const char *alg = NULL; int r; if (tpm2_support() != TPM2_SUPPORT_FULL) log_notice("System lacks full TPM2 support, not showing PCR state."); else { r = get_pcr_alg(&alg); if (r < 0) return r; } table = table_new("nr", "name", alg); if (!table) return log_oom(); (void) table_set_align_percent(table, table_get_cell(table, 0, 0), 100); (void) table_set_ersatz_string(table, TABLE_ERSATZ_DASH); if (!alg) /* hide hash column if we couldn't acquire it */ (void) table_set_display(table, 0, 1); if (strv_isempty(strv_skip(argv, 1))) for (uint32_t pi = 0; pi < _PCR_INDEX_MAX_DEFINED; pi++) { r = add_pcr_to_table(table, alg, pi); if (r < 0) return r; } else { for (int i = 1; i < argc; i++) { int pi; pi = pcr_index_from_string(argv[i]); if (pi < 0) return log_error_errno(pi, "PCR index \"%s\" not known.", argv[i]); r = add_pcr_to_table(table, alg, pi); if (r < 0) return r; } (void) table_set_sort(table, (size_t) 0); } r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, /* show_header= */true); if (r < 0) return log_error_errno(r, "Failed to output table: %m"); return EXIT_SUCCESS; }
4,600
30.731034
110
c
null
systemd-main/src/analyze/analyze-service-watchdogs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-service-watchdogs.h" #include "bus-error.h" #include "bus-locator.h" #include "parse-util.h" int verb_service_watchdogs(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; int b, r; assert(IN_SET(argc, 1, 2)); assert(argv); r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); if (argc == 1) { /* get ServiceWatchdogs */ r = bus_get_property_trivial(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, 'b', &b); if (r < 0) return log_error_errno(r, "Failed to get service-watchdog state: %s", bus_error_message(&error, r)); printf("%s\n", yes_no(!!b)); } else { /* set ServiceWatchdogs */ b = parse_boolean(argv[1]); if (b < 0) return log_error_errno(b, "Failed to parse service-watchdogs argument: %m"); r = bus_set_property(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, "b", b); if (r < 0) return log_error_errno(r, "Failed to set service-watchdog state: %s", bus_error_message(&error, r)); } return EXIT_SUCCESS; }
1,488
34.452381
124
c
null
systemd-main/src/analyze/analyze-time-data.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <sd-bus.h> #include "time-util.h" typedef struct BootTimes { usec_t firmware_time; usec_t loader_time; usec_t kernel_time; usec_t kernel_done_time; usec_t initrd_time; usec_t userspace_time; usec_t finish_time; usec_t security_start_time; usec_t security_finish_time; usec_t generators_start_time; usec_t generators_finish_time; usec_t unitsload_start_time; usec_t unitsload_finish_time; usec_t initrd_security_start_time; usec_t initrd_security_finish_time; usec_t initrd_generators_start_time; usec_t initrd_generators_finish_time; usec_t initrd_unitsload_start_time; usec_t initrd_unitsload_finish_time; /* * If we're analyzing the user instance, all timestamps will be offset by its own start-up timestamp, * which may be arbitrarily big. With "plot", this causes arbitrarily wide output SVG files which * almost completely consist of empty space. Thus we cancel out this offset. * * This offset is subtracted from times above by acquire_boot_times(), but it still needs to be * subtracted from unit-specific timestamps (so it is stored here for reference). */ usec_t reverse_offset; } BootTimes; typedef struct UnitTimes { bool has_data; char *name; usec_t activating; usec_t activated; usec_t deactivated; usec_t deactivating; usec_t time; } UnitTimes; int acquire_boot_times(sd_bus *bus, bool require_finished, BootTimes **ret); int pretty_boot_time(sd_bus *bus, char **ret); UnitTimes* unit_times_free_array(UnitTimes *t); DEFINE_TRIVIAL_CLEANUP_FUNC(UnitTimes*, unit_times_free_array); int acquire_time_data(sd_bus *bus, bool require_finished, UnitTimes **out);
1,938
33.017544
109
h
null
systemd-main/src/analyze/analyze-time.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-time.h" #include "analyze-time-data.h" int verb_time(int argc, char *argv[], void *userdata) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_free_ char *buf = NULL; int r; r = acquire_bus(&bus, NULL); if (r < 0) return bus_log_connect_error(r, arg_transport); r = pretty_boot_time(bus, &buf); if (r < 0) return r; puts(buf); return EXIT_SUCCESS; }
565
23.608696
64
c
null
systemd-main/src/analyze/analyze-timespan.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-timespan.h" #include "calendarspec.h" #include "format-table.h" #include "glyph-util.h" #include "strv.h" #include "terminal-util.h" int verb_timespan(int argc, char *argv[], void *userdata) { STRV_FOREACH(input_timespan, strv_skip(argv, 1)) { _cleanup_(table_unrefp) Table *table = NULL; usec_t output_usecs; TableCell *cell; int r; r = parse_time(*input_timespan, &output_usecs, USEC_PER_SEC); if (r < 0) { log_error_errno(r, "Failed to parse time span '%s': %m", *input_timespan); time_parsing_hint(*input_timespan, /* calendar= */ true, /* timestamp= */ true, /* timespan= */ false); return r; } table = table_new_vertical(); if (!table) return log_oom(); assert_se(cell = table_get_cell(table, 0, 0)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; assert_se(cell = table_get_cell(table, 0, 1)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; r = table_add_many(table, TABLE_FIELD, "Original", TABLE_STRING, *input_timespan); if (r < 0) return table_log_add_error(r); r = table_add_cell_stringf_full(table, NULL, TABLE_FIELD, "%ss", special_glyph(SPECIAL_GLYPH_MU)); if (r < 0) return table_log_add_error(r); r = table_add_many(table, TABLE_UINT64, output_usecs, TABLE_FIELD, "Human", TABLE_TIMESPAN, output_usecs, TABLE_SET_COLOR, ansi_highlight()); if (r < 0) return table_log_add_error(r); r = table_print(table, NULL); if (r < 0) return r; if (input_timespan[1]) putchar('\n'); } return 0; }
2,433
35.328358
127
c
null
systemd-main/src/analyze/analyze-timestamp.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-timestamp.h" #include "format-table.h" #include "terminal-util.h" static int test_timestamp_one(const char *p) { _cleanup_(table_unrefp) Table *table = NULL; TableCell *cell; usec_t usec; int r; r = parse_timestamp(p, &usec); if (r < 0) { log_error_errno(r, "Failed to parse \"%s\": %m", p); time_parsing_hint(p, /* calendar= */ true, /* timestamp= */ false, /* timespan= */ true); return r; } table = table_new_vertical(); if (!table) return log_oom(); assert_se(cell = table_get_cell(table, 0, 0)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; assert_se(cell = table_get_cell(table, 0, 1)); r = table_set_ellipsize_percent(table, cell, 100); if (r < 0) return r; r = table_add_many(table, TABLE_FIELD, "Original form", TABLE_STRING, p, TABLE_FIELD, "Normalized form", TABLE_TIMESTAMP, usec, TABLE_SET_COLOR, ansi_highlight_blue()); if (r < 0) return table_log_add_error(r); if (!in_utc_timezone()) { r = table_add_many(table, TABLE_FIELD, "(in UTC)", TABLE_TIMESTAMP_UTC, usec); if (r < 0) return table_log_add_error(r); } r = table_add_cell(table, NULL, TABLE_FIELD, "UNIX seconds"); if (r < 0) return table_log_add_error(r); if (usec % USEC_PER_SEC == 0) r = table_add_cell_stringf(table, NULL, "@%"PRI_USEC, usec / USEC_PER_SEC); else r = table_add_cell_stringf(table, NULL, "@%"PRI_USEC".%06"PRI_USEC"", usec / USEC_PER_SEC, usec % USEC_PER_SEC); if (r < 0) return r; r = table_add_many(table, TABLE_FIELD, "From now", TABLE_TIMESTAMP_RELATIVE, usec); if (r < 0) return table_log_add_error(r); return table_print(table, NULL); } int verb_timestamp(int argc, char *argv[], void *userdata) { int r = 0; STRV_FOREACH(p, strv_skip(argv, 1)) { int k; k = test_timestamp_one(*p); if (r == 0 && k < 0) r = k; if (p[1]) putchar('\n'); } return r; }
2,875
30.604396
105
c
null
systemd-main/src/analyze/analyze-unit-files.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-unit-files.h" #include "path-lookup.h" #include "strv.h" static bool strv_fnmatch_strv_or_empty(char* const* patterns, char **strv, int flags) { STRV_FOREACH(s, strv) if (strv_fnmatch_or_empty(patterns, *s, flags)) return true; return false; } int verb_unit_files(int argc, char *argv[], void *userdata) { _cleanup_hashmap_free_ Hashmap *unit_ids = NULL, *unit_names = NULL; _cleanup_(lookup_paths_free) LookupPaths lp = {}; char **patterns = strv_skip(argv, 1); const char *k, *dst; char **v; int r; r = lookup_paths_init_or_warn(&lp, arg_runtime_scope, 0, NULL); if (r < 0) return r; r = unit_file_build_name_map(&lp, NULL, &unit_ids, &unit_names, NULL); if (r < 0) return log_error_errno(r, "unit_file_build_name_map() failed: %m"); HASHMAP_FOREACH_KEY(dst, k, unit_ids) { if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) && !strv_fnmatch_or_empty(patterns, dst, FNM_NOESCAPE)) continue; printf("ids: %s → %s\n", k, dst); } HASHMAP_FOREACH_KEY(v, k, unit_names) { if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) && !strv_fnmatch_strv_or_empty(patterns, v, FNM_NOESCAPE)) continue; _cleanup_free_ char *j = strv_join(v, ", "); printf("aliases: %s ← %s\n", k, j); } return EXIT_SUCCESS; }
1,676
31.882353
87
c
null
systemd-main/src/analyze/analyze-unit-paths.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-unit-paths.h" #include "path-lookup.h" #include "strv.h" int verb_unit_paths(int argc, char *argv[], void *userdata) { _cleanup_(lookup_paths_free) LookupPaths paths = {}; int r; r = lookup_paths_init_or_warn(&paths, arg_runtime_scope, 0, NULL); if (r < 0) return r; STRV_FOREACH(p, paths.search_path) puts(*p); return EXIT_SUCCESS; }
508
23.238095
74
c
null
systemd-main/src/analyze/analyze-verify-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdlib.h> #include "all-units.h" #include "alloc-util.h" #include "analyze-verify-util.h" #include "bus-error.h" #include "bus-util.h" #include "log.h" #include "manager.h" #include "pager.h" #include "path-util.h" #include "string-table.h" #include "strv.h" #include "unit-name.h" #include "unit-serialize.h" static void log_syntax_callback(const char *unit, int level, void *userdata) { Set **s = ASSERT_PTR(userdata); int r; assert(unit); if (level > LOG_WARNING) return; if (*s == POINTER_MAX) return; r = set_put_strdup(s, unit); if (r < 0) { set_free_free(*s); *s = POINTER_MAX; } } int verify_prepare_filename(const char *filename, char **ret) { _cleanup_free_ char *abspath = NULL, *name = NULL, *dir = NULL, *with_instance = NULL; char *c; int r; assert(filename); assert(ret); r = path_make_absolute_cwd(filename, &abspath); if (r < 0) return r; r = path_extract_filename(abspath, &name); if (r < 0) return r; if (!unit_name_is_valid(name, UNIT_NAME_ANY)) return -EINVAL; if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) { r = unit_name_replace_instance(name, "i", &with_instance); if (r < 0) return r; } r = path_extract_directory(abspath, &dir); if (r < 0) return r; c = path_join(dir, with_instance ?: name); if (!c) return -ENOMEM; *ret = c; return 0; } int verify_generate_path(char **ret, char **filenames) { _cleanup_strv_free_ char **ans = NULL; _cleanup_free_ char *joined = NULL; const char *old; int r; STRV_FOREACH(filename, filenames) { _cleanup_free_ char *a = NULL; char *t; r = path_make_absolute_cwd(*filename, &a); if (r < 0) return r; r = path_extract_directory(a, &t); if (r < 0) return r; r = strv_consume(&ans, t); if (r < 0) return r; } strv_uniq(ans); /* First, prepend our directories. Second, if some path was specified, use that, and * otherwise use the defaults. Any duplicates will be filtered out in path-lookup.c. * Treat explicit empty path to mean that nothing should be appended. */ old = getenv("SYSTEMD_UNIT_PATH"); if (!streq_ptr(old, "")) { if (!old) old = ":"; r = strv_extend(&ans, old); if (r < 0) return r; } joined = strv_join(ans, ":"); if (!joined) return -ENOMEM; *ret = TAKE_PTR(joined); return 0; } static int verify_socket(Unit *u) { Unit *service; int r; assert(u); if (u->type != UNIT_SOCKET) return 0; r = socket_load_service_unit(SOCKET(u), -1, &service); if (r < 0) return log_unit_error_errno(u, r, "service unit for the socket cannot be loaded: %m"); if (service->load_state != UNIT_LOADED) return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT), "service %s not loaded, socket cannot be started.", service->id); log_unit_debug(u, "using service unit %s.", service->id); return 0; } int verify_executable(Unit *u, const ExecCommand *exec, const char *root) { int r; if (!exec) return 0; if (exec->flags & EXEC_COMMAND_IGNORE_FAILURE) return 0; r = find_executable_full(exec->path, root, NULL, false, NULL, NULL); if (r < 0) return log_unit_error_errno(u, r, "Command %s is not executable: %m", exec->path); return 0; } static int verify_executables(Unit *u, const char *root) { ExecCommand *exec; int r = 0, k; unsigned i; assert(u); exec = u->type == UNIT_SOCKET ? SOCKET(u)->control_command : u->type == UNIT_MOUNT ? MOUNT(u)->control_command : u->type == UNIT_SWAP ? SWAP(u)->control_command : NULL; k = verify_executable(u, exec, root); if (k < 0 && r == 0) r = k; if (u->type == UNIT_SERVICE) for (i = 0; i < ELEMENTSOF(SERVICE(u)->exec_command); i++) { k = verify_executable(u, SERVICE(u)->exec_command[i], root); if (k < 0 && r == 0) r = k; } if (u->type == UNIT_SOCKET) for (i = 0; i < ELEMENTSOF(SOCKET(u)->exec_command); i++) { k = verify_executable(u, SOCKET(u)->exec_command[i], root); if (k < 0 && r == 0) r = k; } return r; } static int verify_documentation(Unit *u, bool check_man) { int r = 0, k; STRV_FOREACH(p, u->documentation) { log_unit_debug(u, "Found documentation item: %s", *p); if (check_man && startswith(*p, "man:")) { k = show_man_page(*p + 4, true); if (k != 0) { if (k < 0) log_unit_error_errno(u, k, "Can't show %s: %m", *p + 4); else { log_unit_error(u, "Command 'man %s' failed with code %d", *p + 4, k); k = -ENOEXEC; } if (r == 0) r = k; } } } /* Check remote URLs? */ return r; } static int verify_unit(Unit *u, bool check_man, const char *root) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; int r, k; assert(u); if (DEBUG_LOGGING) unit_dump(u, stdout, "\t"); log_unit_debug(u, "Creating %s/start job", u->id); r = manager_add_job(u->manager, JOB_START, u, JOB_REPLACE, NULL, &error, NULL); if (r < 0) log_unit_error_errno(u, r, "Failed to create %s/start: %s", u->id, bus_error_message(&error, r)); k = verify_socket(u); if (k < 0 && r == 0) r = k; k = verify_executables(u, root); if (k < 0 && r == 0) r = k; k = verify_documentation(u, check_man); if (k < 0 && r == 0) r = k; return r; } static void set_destroy_ignore_pointer_max(Set** s) { if (*s == POINTER_MAX) return; set_free_free(*s); } int verify_units( char **filenames, RuntimeScope scope, bool check_man, bool run_generators, RecursiveErrors recursive_errors, const char *root) { const ManagerTestRunFlags flags = MANAGER_TEST_RUN_MINIMAL | MANAGER_TEST_RUN_ENV_GENERATORS | (recursive_errors == RECURSIVE_ERRORS_NO) * MANAGER_TEST_RUN_IGNORE_DEPENDENCIES | run_generators * MANAGER_TEST_RUN_GENERATORS; _cleanup_(manager_freep) Manager *m = NULL; _cleanup_(set_destroy_ignore_pointer_max) Set *s = NULL; _unused_ _cleanup_(clear_log_syntax_callback) dummy_t dummy; Unit *units[strv_length(filenames)]; _cleanup_free_ char *var = NULL; int r, k, i, count = 0; if (strv_isempty(filenames)) return 0; /* Allow systemd-analyze to hook in a callback function so that it can get * all the required log data from the function itself without having to rely * on a global set variable for the same */ set_log_syntax_callback(log_syntax_callback, &s); /* set the path */ r = verify_generate_path(&var, filenames); if (r < 0) return log_error_errno(r, "Failed to generate unit load path: %m"); assert_se(set_unit_path(var) >= 0); r = manager_new(scope, flags, &m); if (r < 0) return log_error_errno(r, "Failed to initialize manager: %m"); log_debug("Starting manager..."); r = manager_startup(m, /* serialization= */ NULL, /* fds= */ NULL, root); if (r < 0) return r; manager_clear_jobs(m); log_debug("Loading remaining units from the command line..."); STRV_FOREACH(filename, filenames) { _cleanup_free_ char *prepared = NULL; log_debug("Handling %s...", *filename); k = verify_prepare_filename(*filename, &prepared); if (k < 0) { log_error_errno(k, "Failed to prepare filename %s: %m", *filename); if (r == 0) r = k; continue; } k = manager_load_startable_unit_or_warn(m, NULL, prepared, &units[count]); if (k < 0) { if (r == 0) r = k; continue; } count++; } for (i = 0; i < count; i++) { k = verify_unit(units[i], check_man, root); if (k < 0 && r == 0) r = k; } if (s == POINTER_MAX) return log_oom(); if (set_isempty(s) || r != 0) return r; /* If all previous verifications succeeded, then either the recursive parsing of all the * associated dependencies with RECURSIVE_ERRORS_YES or the parsing of the specified unit file * with RECURSIVE_ERRORS_NO must have yielded a syntax warning and hence, a non-empty set. */ if (IN_SET(recursive_errors, RECURSIVE_ERRORS_YES, RECURSIVE_ERRORS_NO)) return -ENOTRECOVERABLE; /* If all previous verifications succeeded, then the non-empty set could have resulted from * a syntax warning encountered during the recursive parsing of the specified unit file and * its direct dependencies. Hence, search for any of the filenames in the set and if found, * return a non-zero process exit status. */ if (recursive_errors == RECURSIVE_ERRORS_ONE) STRV_FOREACH(filename, filenames) if (set_contains(s, basename(*filename))) return -ENOTRECOVERABLE; return 0; } static const char* const recursive_errors_table[_RECURSIVE_ERRORS_MAX] = { [RECURSIVE_ERRORS_NO] = "no", [RECURSIVE_ERRORS_YES] = "yes", [RECURSIVE_ERRORS_ONE] = "one", }; DEFINE_STRING_TABLE_LOOKUP(recursive_errors, RecursiveErrors);
11,379
30.523546
113
c
null
systemd-main/src/analyze/analyze-verify.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "analyze.h" #include "analyze-verify.h" #include "analyze-verify-util.h" #include "copy.h" #include "rm-rf.h" #include "tmpfile-util.h" static int process_aliases(char *argv[], char *tempdir, char ***ret) { _cleanup_strv_free_ char **filenames = NULL; int r; assert(argv); assert(tempdir); assert(ret); STRV_FOREACH(filename, strv_skip(argv, 1)) { _cleanup_free_ char *src = NULL, *dst = NULL, *base = NULL; const char *parse_arg; parse_arg = *filename; r = extract_first_word(&parse_arg, &src, ":", EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_RETAIN_ESCAPE); if (r < 0) return r; if (!parse_arg) { r = strv_consume(&filenames, TAKE_PTR(src)); if (r < 0) return r; continue; } r = path_extract_filename(parse_arg, &base); if (r < 0) return r; dst = path_join(tempdir, base); if (!dst) return -ENOMEM; r = copy_file(src, dst, 0, 0644, COPY_REFLINK); if (r < 0) return r; r = strv_consume(&filenames, TAKE_PTR(dst)); if (r < 0) return r; } *ret = TAKE_PTR(filenames); return 0; } int verb_verify(int argc, char *argv[], void *userdata) { _cleanup_strv_free_ char **filenames = NULL; _cleanup_(rm_rf_physical_and_freep) char *tempdir = NULL; int r; r = mkdtemp_malloc("/tmp/systemd-analyze-XXXXXX", &tempdir); if (r < 0) return log_error_errno(r, "Failed to setup working directory: %m"); r = process_aliases(argv, tempdir, &filenames); if (r < 0) return log_error_errno(r, "Couldn't process aliases: %m"); return verify_units(filenames, arg_runtime_scope, arg_man, arg_generators, arg_recursive_errors, arg_root); }
2,217
30.239437
118
c
null
systemd-main/src/analyze/analyze.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "analyze-verify-util.h" #include "bus-util.h" #include "json.h" #include "pager.h" #include "time-util.h" #include "unit-file.h" typedef enum DotMode { DEP_ALL, DEP_ORDER, DEP_REQUIRE, } DotMode; extern DotMode arg_dot; extern char **arg_dot_from_patterns, **arg_dot_to_patterns; extern usec_t arg_fuzz; extern PagerFlags arg_pager_flags; extern BusTransport arg_transport; extern const char *arg_host; extern RuntimeScope arg_runtime_scope; extern RecursiveErrors arg_recursive_errors; extern bool arg_man; extern bool arg_generators; extern char *arg_root; extern char *arg_security_policy; extern bool arg_offline; extern unsigned arg_threshold; extern unsigned arg_iterations; extern usec_t arg_base_time; extern char *arg_unit; extern JsonFormatFlags arg_json_format_flags; extern bool arg_quiet; extern char *arg_profile; extern bool arg_legend; extern bool arg_table; extern ImagePolicy *arg_image_policy; int acquire_bus(sd_bus **bus, bool *use_full_bus); int bus_get_unit_property_strv(sd_bus *bus, const char *path, const char *property, char ***strv); void time_parsing_hint(const char *p, bool calendar, bool timestamp, bool timespan); int dump_fd_reply(sd_bus_message *message);
1,316
25.34
98
h
null
systemd-main/src/ask-password/ask-password.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <getopt.h> #include <stddef.h> #include <unistd.h> #include "ask-password-api.h" #include "build.h" #include "constants.h" #include "log.h" #include "macro.h" #include "main-func.h" #include "parse-argument.h" #include "pretty-print.h" #include "strv.h" #include "terminal-util.h" static const char *arg_icon = NULL; static const char *arg_id = NULL; /* identifier for 'ask-password' protocol */ static const char *arg_key_name = NULL; /* name in kernel keyring */ static const char *arg_credential_name = NULL; /* name in $CREDENTIALS_DIRECTORY directory */ static char *arg_message = NULL; static usec_t arg_timeout = DEFAULT_TIMEOUT_USEC; static bool arg_multiple = false; static bool arg_no_output = false; static AskPasswordFlags arg_flags = ASK_PASSWORD_PUSH_CACHE; static bool arg_newline = true; STATIC_DESTRUCTOR_REGISTER(arg_message, freep); static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-ask-password", "1", &link); if (r < 0) return log_oom(); printf("%1$s [OPTIONS...] MESSAGE\n\n" "%3$sQuery the user for a system passphrase, via the TTY or a UI agent.%4$s\n\n" " -h --help Show this help\n" " --icon=NAME Icon name\n" " --id=ID Query identifier (e.g. \"cryptsetup:/dev/sda5\")\n" " --keyname=NAME Kernel key name for caching passwords (e.g. \"cryptsetup\")\n" " --credential=NAME\n" " Credential name for ImportCredential=, LoadCredential= or\n" " SetCredential= credentials\n" " --timeout=SEC Timeout in seconds\n" " --echo=yes|no|masked\n" " Control whether to show password while typing (echo)\n" " -e --echo Equivalent to --echo=yes\n" " --emoji=yes|no|auto\n" " Show a lock and key emoji\n" " --no-tty Ask question via agent even on TTY\n" " --accept-cached Accept cached passwords\n" " --multiple List multiple passwords if available\n" " --no-output Do not print password to standard output\n" " -n Do not suffix password written to standard output with\n" " newline\n" "\nSee the %2$s for details.\n", program_invocation_short_name, link, ansi_highlight(), ansi_normal()); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_ICON = 0x100, ARG_TIMEOUT, ARG_EMOJI, ARG_NO_TTY, ARG_ACCEPT_CACHED, ARG_MULTIPLE, ARG_ID, ARG_KEYNAME, ARG_NO_OUTPUT, ARG_VERSION, ARG_CREDENTIAL, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "icon", required_argument, NULL, ARG_ICON }, { "timeout", required_argument, NULL, ARG_TIMEOUT }, { "echo", optional_argument, NULL, 'e' }, { "emoji", required_argument, NULL, ARG_EMOJI }, { "no-tty", no_argument, NULL, ARG_NO_TTY }, { "accept-cached", no_argument, NULL, ARG_ACCEPT_CACHED }, { "multiple", no_argument, NULL, ARG_MULTIPLE }, { "id", required_argument, NULL, ARG_ID }, { "keyname", required_argument, NULL, ARG_KEYNAME }, { "no-output", no_argument, NULL, ARG_NO_OUTPUT }, { "credential", required_argument, NULL, ARG_CREDENTIAL }, {} }; const char *emoji = NULL; int c, r; assert(argc >= 0); assert(argv); /* Note the asymmetry: the long option --echo= allows an optional argument, the short option does * not. */ /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long() * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */ optind = 0; while ((c = getopt_long(argc, argv, "+hen", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case ARG_ICON: arg_icon = optarg; break; case ARG_TIMEOUT: r = parse_sec(optarg, &arg_timeout); if (r < 0) return log_error_errno(r, "Failed to parse --timeout= parameter: %s", optarg); break; case 'e': if (!optarg) { /* Short option -e is used, or no argument to long option --echo= */ arg_flags |= ASK_PASSWORD_ECHO; arg_flags &= ~ASK_PASSWORD_SILENT; } else if (isempty(optarg) || streq(optarg, "masked")) /* Empty argument or explicit string "masked" for default behaviour. */ arg_flags &= ~(ASK_PASSWORD_ECHO|ASK_PASSWORD_SILENT); else { r = parse_boolean_argument("--echo=", optarg, NULL); if (r < 0) return r; SET_FLAG(arg_flags, ASK_PASSWORD_ECHO, r); SET_FLAG(arg_flags, ASK_PASSWORD_SILENT, !r); } break; case ARG_EMOJI: emoji = optarg; break; case ARG_NO_TTY: arg_flags |= ASK_PASSWORD_NO_TTY; break; case ARG_ACCEPT_CACHED: arg_flags |= ASK_PASSWORD_ACCEPT_CACHED; break; case ARG_MULTIPLE: arg_multiple = true; break; case ARG_ID: arg_id = optarg; break; case ARG_KEYNAME: arg_key_name = optarg; break; case ARG_NO_OUTPUT: arg_no_output = true; break; case ARG_CREDENTIAL: arg_credential_name = optarg; break; case 'n': arg_newline = false; break; case '?': return -EINVAL; default: assert_not_reached(); } if (isempty(emoji) || streq(emoji, "auto")) SET_FLAG(arg_flags, ASK_PASSWORD_HIDE_EMOJI, FLAGS_SET(arg_flags, ASK_PASSWORD_ECHO)); else { r = parse_boolean_argument("--emoji=", emoji, NULL); if (r < 0) return r; SET_FLAG(arg_flags, ASK_PASSWORD_HIDE_EMOJI, !r); } if (argc > optind) { arg_message = strv_join(argv + optind, " "); if (!arg_message) return log_oom(); } else if (FLAGS_SET(arg_flags, ASK_PASSWORD_ECHO)) { /* By default ask_password_auto() will query with the string "Password: ", which is not right * when full echo is on, since then it's unlikely a password. Let's hence default to a less * confusing string in that case. */ arg_message = strdup("Input:"); if (!arg_message) return log_oom(); } return 1; } static int run(int argc, char *argv[]) { _cleanup_strv_free_erase_ char **l = NULL; usec_t timeout; int r; log_show_color(true); log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; if (arg_timeout > 0) timeout = usec_add(now(CLOCK_MONOTONIC), arg_timeout); else timeout = 0; r = ask_password_auto(arg_message, arg_icon, arg_id, arg_key_name, arg_credential_name ?: "password", timeout, arg_flags, &l); if (r < 0) return log_error_errno(r, "Failed to query password: %m"); STRV_FOREACH(p, l) { if (!arg_no_output) { if (arg_newline) puts(*p); else fputs(*p, stdout); } fflush(stdout); if (!arg_multiple) break; } return 0; } DEFINE_MAIN_FUNCTION(run);
9,731
35.863636
134
c
null
systemd-main/src/basic/MurmurHash2.c
/* SPDX-License-Identifier: LicenseRef-murmurhash2-public-domain */ //----------------------------------------------------------------------------- // MurmurHash2 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. #include "MurmurHash2.h" #if __GNUC__ >= 7 _Pragma("GCC diagnostic ignored \"-Wimplicit-fallthrough\"") #endif //----------------------------------------------------------------------------- // Platform-specific functions and macros // Microsoft Visual Studio #if defined(_MSC_VER) #define BIG_CONSTANT(x) (x) // Other compilers #else // defined(_MSC_VER) #define BIG_CONSTANT(x) (x##LLU) #endif // !defined(_MSC_VER) //----------------------------------------------------------------------------- uint32_t MurmurHash2 ( const void * key, int len, uint32_t seed ) { // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. const uint32_t m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value uint32_t h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char * data = (const unsigned char *)key; while (len >= 4) { uint32_t k = *(uint32_t*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; /* fall through */ case 2: h ^= data[1] << 8; /* fall through */ case 1: h ^= data[0]; /* fall through */ h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; }
2,112
21.967391
79
c
null
systemd-main/src/basic/MurmurHash2.h
/* SPDX-License-Identifier: LicenseRef-murmurhash2-public-domain */ //----------------------------------------------------------------------------- // MurmurHash2 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. #pragma once //----------------------------------------------------------------------------- // Platform-specific functions and macros // Microsoft Visual Studio #if defined(_MSC_VER) typedef unsigned char uint8_t; typedef unsigned long uint32_t; typedef unsigned __int64 uint64_t; // Other compilers #else // defined(_MSC_VER) #include <stdint.h> #endif // !defined(_MSC_VER) //----------------------------------------------------------------------------- uint32_t MurmurHash2 ( const void * key, int len, uint32_t seed ); //-----------------------------------------------------------------------------
922
27.84375
79
h
null
systemd-main/src/basic/af-list.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <string.h> #include <sys/socket.h> #include "af-list.h" #include "macro.h" static const struct af_name* lookup_af(register const char *str, register GPERF_LEN_TYPE len); #include "af-from-name.h" #include "af-to-name.h" const char *af_to_name(int id) { if (id <= 0) return NULL; if ((size_t) id >= ELEMENTSOF(af_names)) return NULL; return af_names[id]; } int af_from_name(const char *name) { const struct af_name *sc; assert(name); sc = lookup_af(name, strlen(name)); if (!sc) return -EINVAL; return sc->id; } int af_max(void) { return ELEMENTSOF(af_names); } const char *af_to_ipv4_ipv6(int id) { /* Pretty often we want to map the address family to the typically used protocol name for IPv4 + * IPv6. Let's add special helpers for that. */ return id == AF_INET ? "ipv4" : id == AF_INET6 ? "ipv6" : NULL; } int af_from_ipv4_ipv6(const char *af) { return streq_ptr(af, "ipv4") ? AF_INET : streq_ptr(af, "ipv6") ? AF_INET6 : AF_UNSPEC; }
1,215
21.943396
104
c
null
systemd-main/src/basic/alloc-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <malloc.h> #include <stdint.h> #include <string.h> #include "alloc-util.h" #include "macro.h" #include "memory-util.h" void* memdup(const void *p, size_t l) { void *ret; assert(l == 0 || p); ret = malloc(l ?: 1); if (!ret) return NULL; return memcpy_safe(ret, p, l); } void* memdup_suffix0(const void *p, size_t l) { void *ret; assert(l == 0 || p); /* The same as memdup() but place a safety NUL byte after the allocated memory */ if (_unlikely_(l == SIZE_MAX)) /* prevent overflow */ return NULL; ret = malloc(l + 1); if (!ret) return NULL; ((uint8_t*) ret)[l] = 0; return memcpy_safe(ret, p, l); } void* greedy_realloc( void **p, size_t need, size_t size) { size_t a, newalloc; void *q; assert(p); /* We use malloc_usable_size() for determining the current allocated size. On all systems we care * about this should be safe to rely on. Should there ever arise the need to avoid relying on this we * can instead locally fall back to realloc() on every call, rounded up to the next exponent of 2 or * so. */ if (*p && (size == 0 || (MALLOC_SIZEOF_SAFE(*p) / size >= need))) return *p; if (_unlikely_(need > SIZE_MAX/2)) /* Overflow check */ return NULL; newalloc = need * 2; if (size_multiply_overflow(newalloc, size)) return NULL; a = newalloc * size; if (a < 64) /* Allocate at least 64 bytes */ a = 64; q = realloc(*p, a); if (!q) return NULL; return *p = q; } void* greedy_realloc0( void **p, size_t need, size_t size) { size_t before, after; uint8_t *q; assert(p); before = MALLOC_SIZEOF_SAFE(*p); /* malloc_usable_size() will return 0 on NULL input, as per docs */ q = greedy_realloc(p, need, size); if (!q) return NULL; after = MALLOC_SIZEOF_SAFE(q); if (size == 0) /* avoid division by zero */ before = 0; else before = (before / size) * size; /* Round down */ if (after > before) memzero(q + before, after - before); return q; } void* greedy_realloc_append( void **p, size_t *n_p, const void *from, size_t n_from, size_t size) { uint8_t *q; assert(p); assert(n_p); assert(from || n_from == 0); if (n_from > SIZE_MAX - *n_p) return NULL; q = greedy_realloc(p, *n_p + n_from, size); if (!q) return NULL; memcpy_safe(q + *n_p * size, from, n_from * size); *n_p += n_from; return q; } void *expand_to_usable(void *ptr, size_t newsize _unused_) { return ptr; }
3,174
22.345588
109
c
null
systemd-main/src/basic/architecture.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/utsname.h> #include "architecture.h" #include "macro.h" #include "string-table.h" #include "string-util.h" Architecture uname_architecture(void) { /* Return a sanitized enum identifying the architecture we are running on. This * is based on uname(), and the user may hence control what this returns by using * personality(). This puts the user in control on systems that can run binaries * of multiple architectures. * * We do not translate the string returned by uname() 1:1. Instead we try to * clean it up and break down the confusion on x86 and arm in particular. * * We try to distinguish CPUs, not CPU features, i.e. actual architectures that * have genuinely different code. */ static const struct { const char *machine; Architecture arch; } arch_map[] = { #if defined(__aarch64__) || defined(__arm__) { "aarch64", ARCHITECTURE_ARM64 }, { "aarch64_be", ARCHITECTURE_ARM64_BE }, { "armv8l", ARCHITECTURE_ARM }, { "armv8b", ARCHITECTURE_ARM_BE }, { "armv7ml", ARCHITECTURE_ARM }, { "armv7mb", ARCHITECTURE_ARM_BE }, { "armv7l", ARCHITECTURE_ARM }, { "armv7b", ARCHITECTURE_ARM_BE }, { "armv6l", ARCHITECTURE_ARM }, { "armv6b", ARCHITECTURE_ARM_BE }, { "armv5tl", ARCHITECTURE_ARM }, { "armv5tel", ARCHITECTURE_ARM }, { "armv5tejl", ARCHITECTURE_ARM }, { "armv5tejb", ARCHITECTURE_ARM_BE }, { "armv5teb", ARCHITECTURE_ARM_BE }, { "armv5tb", ARCHITECTURE_ARM_BE }, { "armv4tl", ARCHITECTURE_ARM }, { "armv4tb", ARCHITECTURE_ARM_BE }, { "armv4l", ARCHITECTURE_ARM }, { "armv4b", ARCHITECTURE_ARM_BE }, #elif defined(__alpha__) { "alpha" , ARCHITECTURE_ALPHA }, #elif defined(__arc__) { "arc", ARCHITECTURE_ARC }, { "arceb", ARCHITECTURE_ARC_BE }, #elif defined(__cris__) { "crisv32", ARCHITECTURE_CRIS }, #elif defined(__i386__) || defined(__x86_64__) { "x86_64", ARCHITECTURE_X86_64 }, { "i686", ARCHITECTURE_X86 }, { "i586", ARCHITECTURE_X86 }, { "i486", ARCHITECTURE_X86 }, { "i386", ARCHITECTURE_X86 }, #elif defined(__ia64__) { "ia64", ARCHITECTURE_IA64 }, #elif defined(__hppa__) || defined(__hppa64__) { "parisc64", ARCHITECTURE_PARISC64 }, { "parisc", ARCHITECTURE_PARISC }, #elif defined(__loongarch64) { "loongarch64", ARCHITECTURE_LOONGARCH64 }, #elif defined(__m68k__) { "m68k", ARCHITECTURE_M68K }, #elif defined(__mips__) || defined(__mips64__) { "mips64", ARCHITECTURE_MIPS64 }, { "mips", ARCHITECTURE_MIPS }, #elif defined(__nios2__) { "nios2", ARCHITECTURE_NIOS2 }, #elif defined(__powerpc__) || defined(__powerpc64__) { "ppc64le", ARCHITECTURE_PPC64_LE }, { "ppc64", ARCHITECTURE_PPC64 }, { "ppcle", ARCHITECTURE_PPC_LE }, { "ppc", ARCHITECTURE_PPC }, #elif defined(__riscv) { "riscv64", ARCHITECTURE_RISCV64 }, { "riscv32", ARCHITECTURE_RISCV32 }, # if __SIZEOF_POINTER__ == 4 { "riscv", ARCHITECTURE_RISCV32 }, # elif __SIZEOF_POINTER__ == 8 { "riscv", ARCHITECTURE_RISCV64 }, # endif #elif defined(__s390__) || defined(__s390x__) { "s390x", ARCHITECTURE_S390X }, { "s390", ARCHITECTURE_S390 }, #elif defined(__sh__) || defined(__sh64__) { "sh5", ARCHITECTURE_SH64 }, { "sh4a", ARCHITECTURE_SH }, { "sh4", ARCHITECTURE_SH }, { "sh3", ARCHITECTURE_SH }, { "sh2a", ARCHITECTURE_SH }, { "sh2", ARCHITECTURE_SH }, #elif defined(__sparc__) { "sparc64", ARCHITECTURE_SPARC64 }, { "sparc", ARCHITECTURE_SPARC }, #elif defined(__tilegx__) { "tilegx", ARCHITECTURE_TILEGX }, #else # error "Please register your architecture here!" #endif }; static Architecture cached = _ARCHITECTURE_INVALID; struct utsname u; if (cached != _ARCHITECTURE_INVALID) return cached; assert_se(uname(&u) >= 0); for (size_t i = 0; i < ELEMENTSOF(arch_map); i++) if (streq(arch_map[i].machine, u.machine)) return cached = arch_map[i].arch; assert_not_reached(); return _ARCHITECTURE_INVALID; } /* Maintain same order as in the table above. */ static const char *const architecture_table[_ARCHITECTURE_MAX] = { [ARCHITECTURE_ARM64] = "arm64", [ARCHITECTURE_ARM64_BE] = "arm64-be", [ARCHITECTURE_ARM] = "arm", [ARCHITECTURE_ARM_BE] = "arm-be", [ARCHITECTURE_ALPHA] = "alpha", [ARCHITECTURE_ARC] = "arc", [ARCHITECTURE_ARC_BE] = "arc-be", [ARCHITECTURE_CRIS] = "cris", [ARCHITECTURE_X86_64] = "x86-64", [ARCHITECTURE_X86] = "x86", [ARCHITECTURE_IA64] = "ia64", [ARCHITECTURE_LOONGARCH64] = "loongarch64", [ARCHITECTURE_M68K] = "m68k", [ARCHITECTURE_MIPS64_LE] = "mips64-le", [ARCHITECTURE_MIPS64] = "mips64", [ARCHITECTURE_MIPS_LE] = "mips-le", [ARCHITECTURE_MIPS] = "mips", [ARCHITECTURE_NIOS2] = "nios2", [ARCHITECTURE_PARISC64] = "parisc64", [ARCHITECTURE_PARISC] = "parisc", [ARCHITECTURE_PPC64_LE] = "ppc64-le", [ARCHITECTURE_PPC64] = "ppc64", [ARCHITECTURE_PPC] = "ppc", [ARCHITECTURE_PPC_LE] = "ppc-le", [ARCHITECTURE_RISCV32] = "riscv32", [ARCHITECTURE_RISCV64] = "riscv64", [ARCHITECTURE_S390X] = "s390x", [ARCHITECTURE_S390] = "s390", [ARCHITECTURE_SH64] = "sh64", [ARCHITECTURE_SH] = "sh", [ARCHITECTURE_SPARC64] = "sparc64", [ARCHITECTURE_SPARC] = "sparc", [ARCHITECTURE_TILEGX] = "tilegx", }; DEFINE_STRING_TABLE_LOOKUP(architecture, Architecture);
7,063
38.463687
89
c
null
systemd-main/src/basic/architecture.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <endian.h> #include "macro.h" /* A cleaned up architecture definition. We don't want to get lost in * processor features, models, generations or even ABIs. Hence we * focus on general family, and distinguish word width and endianness. */ typedef enum { ARCHITECTURE_ALPHA, ARCHITECTURE_ARC, ARCHITECTURE_ARC_BE, ARCHITECTURE_ARM, ARCHITECTURE_ARM64, ARCHITECTURE_ARM64_BE, ARCHITECTURE_ARM_BE, ARCHITECTURE_CRIS, ARCHITECTURE_IA64, ARCHITECTURE_LOONGARCH64, ARCHITECTURE_M68K, ARCHITECTURE_MIPS, ARCHITECTURE_MIPS64, ARCHITECTURE_MIPS64_LE, ARCHITECTURE_MIPS_LE, ARCHITECTURE_NIOS2, ARCHITECTURE_PARISC, ARCHITECTURE_PARISC64, ARCHITECTURE_PPC, ARCHITECTURE_PPC64, ARCHITECTURE_PPC64_LE, ARCHITECTURE_PPC_LE, ARCHITECTURE_RISCV32, ARCHITECTURE_RISCV64, ARCHITECTURE_S390, ARCHITECTURE_S390X, ARCHITECTURE_SH, ARCHITECTURE_SH64, ARCHITECTURE_SPARC, ARCHITECTURE_SPARC64, ARCHITECTURE_TILEGX, ARCHITECTURE_X86, ARCHITECTURE_X86_64, _ARCHITECTURE_MAX, _ARCHITECTURE_INVALID = -EINVAL, } Architecture; Architecture uname_architecture(void); /* * LIB_ARCH_TUPLE should resolve to the local library path * architecture tuple systemd is built for, according to the Debian * tuple list: * * https://wiki.debian.org/Multiarch/Tuples * * This is used in library search paths that should understand * Debian's paths on all distributions. */ #if defined(__x86_64__) # define native_architecture() ARCHITECTURE_X86_64 # if defined(__ILP32__) # define LIB_ARCH_TUPLE "x86_64-linux-gnux32" # else # define LIB_ARCH_TUPLE "x86_64-linux-gnu" # endif # define ARCHITECTURE_SECONDARY ARCHITECTURE_X86 #elif defined(__i386__) # define native_architecture() ARCHITECTURE_X86 # define LIB_ARCH_TUPLE "i386-linux-gnu" #elif defined(__powerpc64__) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_PPC64 # define LIB_ARCH_TUPLE "ppc64-linux-gnu" # define ARCHITECTURE_SECONDARY ARCHITECTURE_PPC # else # define native_architecture() ARCHITECTURE_PPC64_LE # define LIB_ARCH_TUPLE "powerpc64le-linux-gnu" # define ARCHITECTURE_SECONDARY ARCHITECTURE_PPC_LE # endif #elif defined(__powerpc__) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_PPC # if defined(__NO_FPRS__) # define LIB_ARCH_TUPLE "powerpc-linux-gnuspe" # else # define LIB_ARCH_TUPLE "powerpc-linux-gnu" # endif # else # define native_architecture() ARCHITECTURE_PPC_LE # error "Missing LIB_ARCH_TUPLE for PPCLE" # endif #elif defined(__ia64__) # define native_architecture() ARCHITECTURE_IA64 # define LIB_ARCH_TUPLE "ia64-linux-gnu" #elif defined(__hppa64__) # define native_architecture() ARCHITECTURE_PARISC64 # error "Missing LIB_ARCH_TUPLE for HPPA64" #elif defined(__hppa__) # define native_architecture() ARCHITECTURE_PARISC # define LIB_ARCH_TUPLE "hppa‑linux‑gnu" #elif defined(__s390x__) # define native_architecture() ARCHITECTURE_S390X # define LIB_ARCH_TUPLE "s390x-linux-gnu" # define ARCHITECTURE_SECONDARY ARCHITECTURE_S390 #elif defined(__s390__) # define native_architecture() ARCHITECTURE_S390 # define LIB_ARCH_TUPLE "s390-linux-gnu" #elif defined(__sparc__) && defined (__arch64__) # define native_architecture() ARCHITECTURE_SPARC64 # define LIB_ARCH_TUPLE "sparc64-linux-gnu" #elif defined(__sparc__) # define native_architecture() ARCHITECTURE_SPARC # define LIB_ARCH_TUPLE "sparc-linux-gnu" #elif defined(__mips64) && defined(__LP64__) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_MIPS64 # define LIB_ARCH_TUPLE "mips64-linux-gnuabi64" # else # define native_architecture() ARCHITECTURE_MIPS64_LE # define LIB_ARCH_TUPLE "mips64el-linux-gnuabi64" # endif #elif defined(__mips64) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_MIPS64 # define LIB_ARCH_TUPLE "mips64-linux-gnuabin32" # else # define native_architecture() ARCHITECTURE_MIPS64_LE # define LIB_ARCH_TUPLE "mips64el-linux-gnuabin32" # endif #elif defined(__mips__) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_MIPS # define LIB_ARCH_TUPLE "mips-linux-gnu" # else # define native_architecture() ARCHITECTURE_MIPS_LE # define LIB_ARCH_TUPLE "mipsel-linux-gnu" # endif #elif defined(__alpha__) # define native_architecture() ARCHITECTURE_ALPHA # define LIB_ARCH_TUPLE "alpha-linux-gnu" #elif defined(__aarch64__) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_ARM64_BE # define LIB_ARCH_TUPLE "aarch64_be-linux-gnu" # else # define native_architecture() ARCHITECTURE_ARM64 # define LIB_ARCH_TUPLE "aarch64-linux-gnu" # define ARCHITECTURE_SECONDARY ARCHITECTURE_ARM # endif #elif defined(__arm__) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_ARM_BE # if defined(__ARM_EABI__) # if defined(__ARM_PCS_VFP) # define LIB_ARCH_TUPLE "armeb-linux-gnueabihf" # else # define LIB_ARCH_TUPLE "armeb-linux-gnueabi" # endif # else # define LIB_ARCH_TUPLE "armeb-linux-gnu" # endif # else # define native_architecture() ARCHITECTURE_ARM # if defined(__ARM_EABI__) # if defined(__ARM_PCS_VFP) # define LIB_ARCH_TUPLE "arm-linux-gnueabihf" # else # define LIB_ARCH_TUPLE "arm-linux-gnueabi" # endif # else # define LIB_ARCH_TUPLE "arm-linux-gnu" # endif # endif #elif defined(__sh64__) # define native_architecture() ARCHITECTURE_SH64 # error "Missing LIB_ARCH_TUPLE for SH64" #elif defined(__sh__) # define native_architecture() ARCHITECTURE_SH # if defined(__SH1__) # define LIB_ARCH_TUPLE "sh1-linux-gnu" # elif defined(__SH2__) # define LIB_ARCH_TUPLE "sh2-linux-gnu" # elif defined(__SH2A__) # define LIB_ARCH_TUPLE "sh2a-linux-gnu" # elif defined(__SH2E__) # define LIB_ARCH_TUPLE "sh2e-linux-gnu" # elif defined(__SH3__) # define LIB_ARCH_TUPLE "sh3-linux-gnu" # elif defined(__SH3E__) # define LIB_ARCH_TUPLE "sh3e-linux-gnu" # elif defined(__SH4__) && !defined(__SH4A__) # define LIB_ARCH_TUPLE "sh4-linux-gnu" # elif defined(__SH4A__) # define LIB_ARCH_TUPLE "sh4a-linux-gnu" # endif #elif defined(__loongarch_lp64) # define native_architecture() ARCHITECTURE_LOONGARCH64 # if defined(__loongarch_double_float) # define LIB_ARCH_TUPLE "loongarch64-linux-gnu" # elif defined(__loongarch_single_float) # define LIB_ARCH_TUPLE "loongarch64-linux-gnuf32" # elif defined(__loongarch_soft_float) # define LIB_ARCH_TUPLE "loongarch64-linux-gnusf" # else # error "Unrecognized loongarch architecture variant" # endif #elif defined(__m68k__) # define native_architecture() ARCHITECTURE_M68K # define LIB_ARCH_TUPLE "m68k-linux-gnu" #elif defined(__tilegx__) # define native_architecture() ARCHITECTURE_TILEGX # define LIB_ARCH_TUPLE "tilegx-linux-gnu" #elif defined(__cris__) # define native_architecture() ARCHITECTURE_CRIS # error "Missing LIB_ARCH_TUPLE for CRIS" #elif defined(__nios2__) # define native_architecture() ARCHITECTURE_NIOS2 # define LIB_ARCH_TUPLE "nios2-linux-gnu" #elif defined(__riscv) # if __SIZEOF_POINTER__ == 4 # define native_architecture() ARCHITECTURE_RISCV32 # define LIB_ARCH_TUPLE "riscv32-linux-gnu" # elif __SIZEOF_POINTER__ == 8 # define native_architecture() ARCHITECTURE_RISCV64 # define LIB_ARCH_TUPLE "riscv64-linux-gnu" # else # error "Unrecognized riscv architecture variant" # endif #elif defined(__arc__) # if __BYTE_ORDER == __BIG_ENDIAN # define native_architecture() ARCHITECTURE_ARC_BE # define LIB_ARCH_TUPLE "arceb-linux" # else # define native_architecture() ARCHITECTURE_ARC # define LIB_ARCH_TUPLE "arc-linux" # endif #else # error "Please register your architecture here!" #endif const char *architecture_to_string(Architecture a) _const_; Architecture architecture_from_string(const char *s) _pure_;
8,289
32.562753
73
h
null
systemd-main/src/basic/argv-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sched.h> #include <sys/mman.h> #include <sys/prctl.h> #include <unistd.h> #include "argv-util.h" #include "capability-util.h" #include "errno-util.h" #include "missing_sched.h" #include "parse-util.h" #include "path-util.h" #include "process-util.h" #include "string-util.h" #include "strv.h" int saved_argc = 0; char **saved_argv = NULL; bool invoked_as(char *argv[], const char *token) { if (!argv || isempty(argv[0])) return false; if (isempty(token)) return false; return strstr(last_path_component(argv[0]), token); } bool invoked_by_systemd(void) { int r; /* If the process is directly executed by PID1 (e.g. ExecStart= or generator), systemd-importd, * or systemd-homed, then $SYSTEMD_EXEC_PID= is set, and read the command line. */ const char *e = getenv("SYSTEMD_EXEC_PID"); if (!e) return false; if (streq(e, "*")) /* For testing. */ return true; pid_t p; r = parse_pid(e, &p); if (r < 0) { /* We know that systemd sets the variable correctly. Something else must have set it. */ log_debug_errno(r, "Failed to parse \"SYSTEMD_EXEC_PID=%s\", ignoring: %m", e); return false; } return getpid_cached() == p; } bool argv_looks_like_help(int argc, char **argv) { char **l; /* Scans the command line for indications the user asks for help. This is supposed to be called by * tools that do not implement getopt() style command line parsing because they are not primarily * user-facing. Detects four ways of asking for help: * * 1. Passing zero arguments * 2. Passing "help" as first argument * 3. Passing --help as any argument * 4. Passing -h as any argument */ if (argc <= 1) return true; if (streq_ptr(argv[1], "help")) return true; l = strv_skip(argv, 1); return strv_contains(l, "--help") || strv_contains(l, "-h"); } static int update_argv(const char name[], size_t l) { static int can_do = -1; int r; if (can_do == 0) return 0; can_do = false; /* We'll set it to true only if the whole process works */ /* Calling prctl() with PR_SET_MM_ARG_{START,END} requires CAP_SYS_RESOURCE so let's use this as quick bypass * check, to avoid calling mmap() should PR_SET_MM_ARG_{START,END} fail with EPERM later on anyway. */ r = have_effective_cap(CAP_SYS_RESOURCE); if (r < 0) return log_debug_errno(r, "Failed to check if we have enough privileges: %m"); if (r == 0) return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Skipping PR_SET_MM, as we don't have privileges."); static size_t mm_size = 0; static char *mm = NULL; if (mm_size < l+1) { size_t nn_size; char *nn; nn_size = PAGE_ALIGN(l+1); nn = mmap(NULL, nn_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (nn == MAP_FAILED) return log_debug_errno(errno, "mmap() failed: %m"); strncpy(nn, name, nn_size); /* Now, let's tell the kernel about this new memory */ if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) { if (ERRNO_IS_PRIVILEGE(errno)) return log_debug_errno(errno, "PR_SET_MM_ARG_START failed: %m"); /* HACK: prctl() API is kind of dumb on this point. The existing end address may already be * below the desired start address, in which case the kernel may have kicked this back due * to a range-check failure (see linux/kernel/sys.c:validate_prctl_map() to see this in * action). The proper solution would be to have a prctl() API that could set both start+end * simultaneously, or at least let us query the existing address to anticipate this condition * and respond accordingly. For now, we can only guess at the cause of this failure and try * a workaround--which will briefly expand the arg space to something potentially huge before * resizing it to what we want. */ log_debug_errno(errno, "PR_SET_MM_ARG_START failed, attempting PR_SET_MM_ARG_END hack: %m"); if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) { r = log_debug_errno(errno, "PR_SET_MM_ARG_END hack failed, proceeding without: %m"); (void) munmap(nn, nn_size); return r; } if (prctl(PR_SET_MM, PR_SET_MM_ARG_START, (unsigned long) nn, 0, 0) < 0) return log_debug_errno(errno, "PR_SET_MM_ARG_START still failed, proceeding without: %m"); } else { /* And update the end pointer to the new end, too. If this fails, we don't really know what * to do, it's pretty unlikely that we can rollback, hence we'll just accept the failure, * and continue. */ if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) nn + l + 1, 0, 0) < 0) log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m"); } if (mm) (void) munmap(mm, mm_size); mm = nn; mm_size = nn_size; } else { strncpy(mm, name, mm_size); /* Update the end pointer, continuing regardless of any failure. */ if (prctl(PR_SET_MM, PR_SET_MM_ARG_END, (unsigned long) mm + l + 1, 0, 0) < 0) log_debug_errno(errno, "PR_SET_MM_ARG_END failed, proceeding without: %m"); } can_do = true; return 0; } int rename_process(const char name[]) { bool truncated = false; /* This is a like a poor man's setproctitle(). It changes the comm field, argv[0], and also the glibc's * internally used name of the process. For the first one a limit of 16 chars applies; to the second one in * many cases one of 10 (i.e. length of "/sbin/init") — however if we have CAP_SYS_RESOURCES it is unbounded; * to the third one 7 (i.e. the length of "systemd". If you pass a longer string it will likely be * truncated. * * Returns 0 if a name was set but truncated, > 0 if it was set but not truncated. */ if (isempty(name)) return -EINVAL; /* let's not confuse users unnecessarily with an empty name */ if (!is_main_thread()) return -EPERM; /* Let's not allow setting the process name from other threads than the main one, as we * cache things without locking, and we make assumptions that PR_SET_NAME sets the * process name that isn't correct on any other threads */ size_t l = strlen(name); /* First step, change the comm field. The main thread's comm is identical to the process comm. This means we * can use PR_SET_NAME, which sets the thread name for the calling thread. */ if (prctl(PR_SET_NAME, name) < 0) log_debug_errno(errno, "PR_SET_NAME failed: %m"); if (l >= TASK_COMM_LEN) /* Linux userspace process names can be 15 chars at max */ truncated = true; /* Second step, change glibc's ID of the process name. */ if (program_invocation_name) { size_t k; k = strlen(program_invocation_name); strncpy(program_invocation_name, name, k); if (l > k) truncated = true; /* Also update the short name. */ char *p = strrchr(program_invocation_name, '/'); program_invocation_short_name = p ? p + 1 : program_invocation_name; } /* Third step, completely replace the argv[] array the kernel maintains for us. This requires privileges, but * has the advantage that the argv[] array is exactly what we want it to be, and not filled up with zeros at * the end. This is the best option for changing /proc/self/cmdline. */ (void) update_argv(name, l); /* Fourth step: in all cases we'll also update the original argv[], so that our own code gets it right too if * it still looks here */ if (saved_argc > 0) { if (saved_argv[0]) { size_t k; k = strlen(saved_argv[0]); strncpy(saved_argv[0], name, k); if (l > k) truncated = true; } for (int i = 1; i < saved_argc; i++) { if (!saved_argv[i]) break; memzero(saved_argv[i], strlen(saved_argv[i])); } } return !truncated; }
9,630
41.241228
122
c
null
systemd-main/src/basic/argv-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "macro.h" extern int saved_argc; extern char **saved_argv; static inline void save_argc_argv(int argc, char **argv) { /* Protect against CVE-2021-4034 style attacks */ assert_se(argc > 0); assert_se(argv); assert_se(argv[0]); saved_argc = argc; saved_argv = argv; } bool invoked_as(char *argv[], const char *token); bool invoked_by_systemd(void); bool argv_looks_like_help(int argc, char **argv); int rename_process(const char name[]);
583
21.461538
58
h
null
systemd-main/src/basic/arphrd-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <netinet/in.h> #include <linux/if_arp.h> #include <linux/if_infiniband.h> #include <string.h> #include "arphrd-util.h" #include "macro.h" static const struct arphrd_name* lookup_arphrd(register const char *str, register GPERF_LEN_TYPE len); #include "arphrd-from-name.h" #include "arphrd-to-name.h" int arphrd_from_name(const char *name) { const struct arphrd_name *sc; assert(name); sc = lookup_arphrd(name, strlen(name)); if (!sc) return -EINVAL; return sc->id; } size_t arphrd_to_hw_addr_len(uint16_t arphrd) { switch (arphrd) { case ARPHRD_ETHER: return ETH_ALEN; case ARPHRD_INFINIBAND: return INFINIBAND_ALEN; case ARPHRD_TUNNEL: case ARPHRD_SIT: case ARPHRD_IPGRE: return sizeof(struct in_addr); case ARPHRD_TUNNEL6: case ARPHRD_IP6GRE: return sizeof(struct in6_addr); default: return 0; } }
1,101
22.956522
102
c
null
systemd-main/src/basic/audit-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <linux/audit.h> #include <linux/netlink.h> #include <stdio.h> #include <sys/socket.h> #include "alloc-util.h" #include "audit-util.h" #include "fd-util.h" #include "fileio.h" #include "io-util.h" #include "macro.h" #include "parse-util.h" #include "process-util.h" #include "socket-util.h" #include "user-util.h" int audit_session_from_pid(pid_t pid, uint32_t *id) { _cleanup_free_ char *s = NULL; const char *p; uint32_t u; int r; assert(id); /* We don't convert ENOENT to ESRCH here, since we can't * really distinguish between "audit is not available in the * kernel" and "the process does not exist", both which will * result in ENOENT. */ p = procfs_file_alloca(pid, "sessionid"); r = read_one_line_file(p, &s); if (r < 0) return r; r = safe_atou32(s, &u); if (r < 0) return r; if (!audit_session_is_valid(u)) return -ENODATA; *id = u; return 0; } int audit_loginuid_from_pid(pid_t pid, uid_t *uid) { _cleanup_free_ char *s = NULL; const char *p; uid_t u; int r; assert(uid); p = procfs_file_alloca(pid, "loginuid"); r = read_one_line_file(p, &s); if (r < 0) return r; r = parse_uid(s, &u); if (r == -ENXIO) /* the UID was -1 */ return -ENODATA; if (r < 0) return r; *uid = u; return 0; } static int try_audit_request(int fd) { struct iovec iov; struct msghdr mh; ssize_t n; assert(fd >= 0); struct { struct nlmsghdr hdr; struct nlmsgerr err; } _packed_ msg = { .hdr.nlmsg_len = NLMSG_LENGTH(0), .hdr.nlmsg_type = AUDIT_GET_FEATURE, .hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK, }; iov = IOVEC_MAKE(&msg, msg.hdr.nlmsg_len); mh = (struct msghdr) { .msg_iov = &iov, .msg_iovlen = 1, }; if (sendmsg(fd, &mh, MSG_NOSIGNAL) < 0) return -errno; iov.iov_len = sizeof(msg); n = recvmsg_safe(fd, &mh, 0); if (n < 0) return -errno; if (n != NLMSG_LENGTH(sizeof(struct nlmsgerr))) return -EIO; if (msg.hdr.nlmsg_type != NLMSG_ERROR) return -EINVAL; return msg.err.error; } bool use_audit(void) { static int cached_use = -1; int r; if (cached_use < 0) { int fd; fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_AUDIT); if (fd < 0) { cached_use = !IN_SET(errno, EAFNOSUPPORT, EPROTONOSUPPORT, EPERM); if (!cached_use) log_debug_errno(errno, "Won't talk to audit: %m"); } else { /* If we try and use the audit fd but get -ECONNREFUSED, it is because * we are not in the initial user namespace, and the kernel does not * have support for audit outside of the initial user namespace * (see https://elixir.bootlin.com/linux/latest/C/ident/audit_netlink_ok). * * If we receive any other error, do not disable audit because we are not * sure that the error indicates that audit will not work in general. */ r = try_audit_request(fd); if (r < 0) { cached_use = r != -ECONNREFUSED; log_debug_errno(r, cached_use ? "Failed to make request on audit fd, ignoring: %m" : "Won't talk to audit: %m"); } else cached_use = true; safe_close(fd); } } return cached_use; }
4,292
28.204082
103
c
null
systemd-main/src/basic/bitfield.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "macro.h" /* Bit index (0-based) to mask of specified type. Assertion failure if index is out of range. */ #define _INDEX_TO_MASK(type, i, uniq) \ ({ \ int UNIQ_T(_i, uniq) = (i); \ assert(UNIQ_T(_i, uniq) < (int)sizeof(type) * 8); \ ((type)1) << UNIQ_T(_i, uniq); \ }) #define INDEX_TO_MASK(type, i) \ ({ \ assert_cc(sizeof(type) <= sizeof(unsigned long long)); \ assert_cc(__builtin_choose_expr(__builtin_constant_p(i), i, 0) < (int)(sizeof(type) * 8)); \ __builtin_choose_expr(__builtin_constant_p(i), \ ((type)1) << (i), \ _INDEX_TO_MASK(type, i, UNIQ)); \ }) /* Builds a mask of specified type with multiple bits set. Note the result will not be constant, even if all * indexes are constant. */ #define INDEXES_TO_MASK(type, ...) \ UNIQ_INDEXES_TO_MASK(type, UNIQ, ##__VA_ARGS__) #define UNIQ_INDEXES_TO_MASK(type, uniq, ...) \ ({ \ typeof(type) UNIQ_T(_mask, uniq) = (type)0; \ int UNIQ_T(_i, uniq); \ VA_ARGS_FOREACH(UNIQ_T(_i, uniq), ##__VA_ARGS__) \ UNIQ_T(_mask, uniq) |= INDEX_TO_MASK(type, UNIQ_T(_i, uniq)); \ UNIQ_T(_mask, uniq); \ }) /* Same as the FLAG macros, but accept a 0-based bit index instead of a mask. Results in assertion failure if * index is out of range for the type. */ #define SET_BIT(bits, i) SET_FLAG(bits, INDEX_TO_MASK(typeof(bits), i), true) #define CLEAR_BIT(bits, i) SET_FLAG(bits, INDEX_TO_MASK(typeof(bits), i), false) #define BIT_SET(bits, i) FLAGS_SET(bits, INDEX_TO_MASK(typeof(bits), i)) /* As above, but accepts multiple indexes. Note the result will not be constant, even if all indexes are * constant. */ #define SET_BITS(bits, ...) SET_FLAG(bits, INDEXES_TO_MASK(typeof(bits), ##__VA_ARGS__), true) #define CLEAR_BITS(bits, ...) SET_FLAG(bits, INDEXES_TO_MASK(typeof(bits), ##__VA_ARGS__), false) #define BITS_SET(bits, ...) FLAGS_SET(bits, INDEXES_TO_MASK(typeof(bits), ##__VA_ARGS__)) /* Iterate through each set bit. Index is 0-based and type int. */ #define BIT_FOREACH(index, bits) _BIT_FOREACH(index, bits, UNIQ) #define _BIT_FOREACH(index, bits, uniq) \ for (int UNIQ_T(_last, uniq) = -1, index; \ (index = BIT_NEXT_SET(bits, UNIQ_T(_last, uniq))) >= 0; \ UNIQ_T(_last, uniq) = index) /* Find the next set bit after 0-based index 'prev'. Result is 0-based index of next set bit, or -1 if no * more bits are set. */ #define BIT_FIRST_SET(bits) BIT_NEXT_SET(bits, -1) #define BIT_NEXT_SET(bits, prev) \ UNIQ_BIT_NEXT_SET(bits, prev, UNIQ) #define UNIQ_BIT_NEXT_SET(bits, prev, uniq) \ ({ \ typeof(bits) UNIQ_T(_bits, uniq) = (bits); \ int UNIQ_T(_prev, uniq) = (prev); \ int UNIQ_T(_next, uniq); \ _BIT_NEXT_SET(UNIQ_T(_bits, uniq), \ UNIQ_T(_prev, uniq), \ UNIQ_T(_next, uniq)); \ }) #define _BIT_NEXT_SET(bits, prev, next) \ ((int)(prev + 1) == (int)sizeof(bits) * 8 \ ? -1 /* Prev index was msb. */ \ : ((next = __builtin_ffsll(((unsigned long long)(bits)) >> (prev + 1))) == 0 \ ? -1 /* No more bits set. */ \ : prev + next))
4,415
58.675676
109
h
null
systemd-main/src/basic/bus-label.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdlib.h> #include "alloc-util.h" #include "bus-label.h" #include "hexdecoct.h" #include "macro.h" char *bus_label_escape(const char *s) { char *r, *t; const char *f; assert_return(s, NULL); /* Escapes all chars that D-Bus' object path cannot deal * with. Can be reversed with bus_path_unescape(). We special * case the empty string. */ if (*s == 0) return strdup("_"); r = new(char, strlen(s)*3 + 1); if (!r) return NULL; for (f = s, t = r; *f; f++) { /* Escape everything that is not a-zA-Z0-9. We also escape 0-9 if it's the first character */ if (!ascii_isalpha(*f) && !(f > s && ascii_isdigit(*f))) { *(t++) = '_'; *(t++) = hexchar(*f >> 4); *(t++) = hexchar(*f); } else *(t++) = *f; } *t = 0; return r; } char *bus_label_unescape_n(const char *f, size_t l) { char *r, *t; size_t i; assert_return(f, NULL); /* Special case for the empty string */ if (l == 1 && *f == '_') return strdup(""); r = new(char, l + 1); if (!r) return NULL; for (i = 0, t = r; i < l; ++i) { if (f[i] == '_') { int a, b; if (l - i < 3 || (a = unhexchar(f[i + 1])) < 0 || (b = unhexchar(f[i + 2])) < 0) { /* Invalid escape code, let's take it literal then */ *(t++) = '_'; } else { *(t++) = (char) ((a << 4) | b); i += 2; } } else *(t++) = f[i]; } *t = 0; return r; }
2,084
25.0625
109
c
null
systemd-main/src/basic/cap-list.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> /* Space for capability_to_string() in case we write out a numeric capability because we don't know the name * for it. "0x3e" is the largest string we might output, in both sensese of the word "largest": two chars for * "0x", two bytes for the hex value, and one trailing NUL byte. */ #define CAPABILITY_TO_STRING_MAX (2 + 2 + 1) const char *capability_to_name(int id); const char *capability_to_string(int id, char buf[static CAPABILITY_TO_STRING_MAX]); #define CAPABILITY_TO_STRING(id) capability_to_string(id, (char[CAPABILITY_TO_STRING_MAX]) {}) int capability_from_name(const char *name); int capability_list_length(void); int capability_set_to_string(uint64_t set, char **ret); int capability_set_to_string_negative(uint64_t set, char **ret); int capability_set_to_strv(uint64_t set, char ***ret); int capability_set_from_string(const char *s, uint64_t *ret);
957
42.545455
109
h
null
systemd-main/src/basic/capability-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <sys/prctl.h> #include <unistd.h> #include "alloc-util.h" #include "capability-util.h" #include "cap-list.h" #include "fileio.h" #include "log.h" #include "logarithm.h" #include "macro.h" #include "missing_prctl.h" #include "missing_threads.h" #include "parse-util.h" #include "user-util.h" int have_effective_cap(int value) { _cleanup_cap_free_ cap_t cap = NULL; cap_flag_value_t fv; cap = cap_get_proc(); if (!cap) return -errno; if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0) return -errno; return fv == CAP_SET; } unsigned cap_last_cap(void) { static thread_local unsigned saved; static thread_local bool valid = false; _cleanup_free_ char *content = NULL; unsigned long p = 0; int r; if (valid) return saved; /* available since linux-3.2 */ r = read_one_line_file("/proc/sys/kernel/cap_last_cap", &content); if (r >= 0) { r = safe_atolu(content, &p); if (r >= 0) { if (p > CAP_LIMIT) /* Safety for the future: if one day the kernel learns more than * 64 caps, then we are in trouble (since we, as much userspace * and kernel space store capability masks in uint64_t types). We * also want to use UINT64_MAX as marker for "unset". Hence let's * hence protect ourselves against that and always cap at 62 for * now. */ p = CAP_LIMIT; saved = p; valid = true; return p; } } /* fall back to syscall-probing for pre linux-3.2 */ p = (unsigned long) MIN(CAP_LAST_CAP, CAP_LIMIT); if (prctl(PR_CAPBSET_READ, p) < 0) { /* Hmm, look downwards, until we find one that works */ for (p--; p > 0; p--) if (prctl(PR_CAPBSET_READ, p) >= 0) break; } else { /* Hmm, look upwards, until we find one that doesn't work */ for (; p < CAP_LIMIT; p++) if (prctl(PR_CAPBSET_READ, p+1) < 0) break; } saved = p; valid = true; return p; } int capability_update_inherited_set(cap_t caps, uint64_t set) { /* Add capabilities in the set to the inherited caps, drops capabilities not in the set. * Do not apply them yet. */ for (unsigned i = 0; i <= cap_last_cap(); i++) { cap_flag_value_t flag = set & (UINT64_C(1) << i) ? CAP_SET : CAP_CLEAR; cap_value_t v; v = (cap_value_t) i; if (cap_set_flag(caps, CAP_INHERITABLE, 1, &v, flag) < 0) return -errno; } return 0; } int capability_ambient_set_apply(uint64_t set, bool also_inherit) { _cleanup_cap_free_ cap_t caps = NULL; int r; /* Remove capabilities requested in ambient set, but not in the bounding set */ for (unsigned i = 0; i <= cap_last_cap(); i++) { if (set == 0) break; if (FLAGS_SET(set, (UINT64_C(1) << i)) && prctl(PR_CAPBSET_READ, i) != 1) { log_debug("Ambient capability %s requested but missing from bounding set," " suppressing automatically.", capability_to_name(i)); set &= ~(UINT64_C(1) << i); } } /* Add the capabilities to the ambient set (an possibly also the inheritable set) */ /* Check that we can use PR_CAP_AMBIENT or quit early. */ if (!ambient_capabilities_supported()) return (set & all_capabilities()) == 0 ? 0 : -EOPNOTSUPP; /* if actually no ambient caps are to be set, be silent, * otherwise fail recognizably */ if (also_inherit) { caps = cap_get_proc(); if (!caps) return -errno; r = capability_update_inherited_set(caps, set); if (r < 0) return -errno; if (cap_set_proc(caps) < 0) return -errno; } for (unsigned i = 0; i <= cap_last_cap(); i++) { if (set & (UINT64_C(1) << i)) { /* Add the capability to the ambient set. */ if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0) < 0) return -errno; } else { /* Drop the capability so we don't inherit capabilities we didn't ask for. */ r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, i, 0, 0); if (r < 0) return -errno; if (r) if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_LOWER, i, 0, 0) < 0) return -errno; } } return 0; } int capability_gain_cap_setpcap(cap_t *ret_before_caps) { _cleanup_cap_free_ cap_t caps = NULL; cap_flag_value_t fv; caps = cap_get_proc(); if (!caps) return -errno; if (cap_get_flag(caps, CAP_SETPCAP, CAP_EFFECTIVE, &fv) < 0) return -errno; if (fv != CAP_SET) { _cleanup_cap_free_ cap_t temp_cap = NULL; static const cap_value_t v = CAP_SETPCAP; temp_cap = cap_dup(caps); if (!temp_cap) return -errno; if (cap_set_flag(temp_cap, CAP_EFFECTIVE, 1, &v, CAP_SET) < 0) return -errno; if (cap_set_proc(temp_cap) < 0) log_debug_errno(errno, "Can't acquire effective CAP_SETPCAP bit, ignoring: %m"); /* If we didn't manage to acquire the CAP_SETPCAP bit, we continue anyway, after all this just means * we'll fail later, when we actually intend to drop some capabilities or try to set securebits. */ } if (ret_before_caps) /* Return the capabilities as they have been before setting CAP_SETPCAP */ *ret_before_caps = TAKE_PTR(caps); return 0; } int capability_bounding_set_drop(uint64_t keep, bool right_now) { _cleanup_cap_free_ cap_t before_cap = NULL, after_cap = NULL; int r; /* If we are run as PID 1 we will lack CAP_SETPCAP by default * in the effective set (yes, the kernel drops that when * executing init!), so get it back temporarily so that we can * call PR_CAPBSET_DROP. */ r = capability_gain_cap_setpcap(&before_cap); if (r < 0) return r; after_cap = cap_dup(before_cap); if (!after_cap) return -errno; for (unsigned i = 0; i <= cap_last_cap(); i++) { cap_value_t v; if ((keep & (UINT64_C(1) << i))) continue; /* Drop it from the bounding set */ if (prctl(PR_CAPBSET_DROP, i) < 0) { r = -errno; /* If dropping the capability failed, let's see if we didn't have it in the first place. If so, * continue anyway, as dropping a capability we didn't have in the first place doesn't really * matter anyway. */ if (prctl(PR_CAPBSET_READ, i) != 0) goto finish; } v = (cap_value_t) i; /* Also drop it from the inheritable set, so * that anything we exec() loses the * capability for good. */ if (cap_set_flag(after_cap, CAP_INHERITABLE, 1, &v, CAP_CLEAR) < 0) { r = -errno; goto finish; } /* If we shall apply this right now drop it * also from our own capability sets. */ if (right_now) { if (cap_set_flag(after_cap, CAP_PERMITTED, 1, &v, CAP_CLEAR) < 0 || cap_set_flag(after_cap, CAP_EFFECTIVE, 1, &v, CAP_CLEAR) < 0) { r = -errno; goto finish; } } } r = 0; finish: if (cap_set_proc(after_cap) < 0) { /* If there are no actual changes anyway then let's ignore this error. */ if (cap_compare(before_cap, after_cap) != 0) r = -errno; } return r; } static int drop_from_file(const char *fn, uint64_t keep) { _cleanup_free_ char *p = NULL; uint64_t current, after; uint32_t hi, lo; int r, k; r = read_one_line_file(fn, &p); if (r < 0) return r; k = sscanf(p, "%" PRIu32 " %" PRIu32, &lo, &hi); if (k != 2) return -EIO; current = (uint64_t) lo | ((uint64_t) hi << 32); after = current & keep; if (current == after) return 0; lo = after & UINT32_MAX; hi = (after >> 32) & UINT32_MAX; return write_string_filef(fn, 0, "%" PRIu32 " %" PRIu32, lo, hi); } int capability_bounding_set_drop_usermode(uint64_t keep) { int r; r = drop_from_file("/proc/sys/kernel/usermodehelper/inheritable", keep); if (r < 0) return r; r = drop_from_file("/proc/sys/kernel/usermodehelper/bset", keep); if (r < 0) return r; return r; } int drop_privileges(uid_t uid, gid_t gid, uint64_t keep_capabilities) { int r; /* Unfortunately we cannot leave privilege dropping to PID 1 here, since we want to run as user but * want to keep some capabilities. Since file capabilities have been introduced this cannot be done * across exec() anymore, unless our binary has the capability configured in the file system, which * we want to avoid. */ if (setresgid(gid, gid, gid) < 0) return log_error_errno(errno, "Failed to change group ID: %m"); r = maybe_setgroups(0, NULL); if (r < 0) return log_error_errno(r, "Failed to drop auxiliary groups list: %m"); /* Ensure we keep the permitted caps across the setresuid(). Note that we do this even if we actually * don't want to keep any capabilities, since we want to be able to drop them from the bounding set * too, and we can only do that if we have capabilities. */ if (prctl(PR_SET_KEEPCAPS, 1) < 0) return log_error_errno(errno, "Failed to enable keep capabilities flag: %m"); if (setresuid(uid, uid, uid) < 0) return log_error_errno(errno, "Failed to change user ID: %m"); if (prctl(PR_SET_KEEPCAPS, 0) < 0) return log_error_errno(errno, "Failed to disable keep capabilities flag: %m"); /* Drop all caps from the bounding set (as well as the inheritable/permitted/effective sets), except * the ones we want to keep */ r = capability_bounding_set_drop(keep_capabilities, true); if (r < 0) return log_error_errno(r, "Failed to drop capabilities: %m"); /* Now upgrade the permitted caps we still kept to effective caps */ if (keep_capabilities != 0) { cap_value_t bits[log2u64(keep_capabilities) + 1]; _cleanup_cap_free_ cap_t d = NULL; unsigned i, j = 0; d = cap_init(); if (!d) return log_oom(); for (i = 0; i < ELEMENTSOF(bits); i++) if (keep_capabilities & (1ULL << i)) bits[j++] = i; /* use enough bits */ assert(i == 64 || (keep_capabilities >> i) == 0); /* don't use too many bits */ assert(keep_capabilities & (UINT64_C(1) << (i - 1))); if (cap_set_flag(d, CAP_EFFECTIVE, j, bits, CAP_SET) < 0 || cap_set_flag(d, CAP_PERMITTED, j, bits, CAP_SET) < 0) return log_error_errno(errno, "Failed to enable capabilities bits: %m"); if (cap_set_proc(d) < 0) return log_error_errno(errno, "Failed to increase capabilities: %m"); } return 0; } int drop_capability(cap_value_t cv) { _cleanup_cap_free_ cap_t tmp_cap = NULL; tmp_cap = cap_get_proc(); if (!tmp_cap) return -errno; if ((cap_set_flag(tmp_cap, CAP_INHERITABLE, 1, &cv, CAP_CLEAR) < 0) || (cap_set_flag(tmp_cap, CAP_PERMITTED, 1, &cv, CAP_CLEAR) < 0) || (cap_set_flag(tmp_cap, CAP_EFFECTIVE, 1, &cv, CAP_CLEAR) < 0)) return -errno; if (cap_set_proc(tmp_cap) < 0) return -errno; return 0; } bool ambient_capabilities_supported(void) { static int cache = -1; if (cache >= 0) return cache; /* If PR_CAP_AMBIENT returns something valid, or an unexpected error code we assume that ambient caps are * available. */ cache = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_KILL, 0, 0) >= 0 || !IN_SET(errno, EINVAL, EOPNOTSUPP, ENOSYS); return cache; } bool capability_quintet_mangle(CapabilityQuintet *q) { uint64_t combined, drop = 0; bool ambient_supported; assert(q); combined = q->effective | q->bounding | q->inheritable | q->permitted; ambient_supported = q->ambient != CAP_MASK_UNSET; if (ambient_supported) combined |= q->ambient; for (unsigned i = 0; i <= cap_last_cap(); i++) { unsigned long bit = UINT64_C(1) << i; if (!FLAGS_SET(combined, bit)) continue; if (prctl(PR_CAPBSET_READ, i) > 0) continue; drop |= bit; log_debug("Not in the current bounding set: %s", capability_to_name(i)); } q->effective &= ~drop; q->bounding &= ~drop; q->inheritable &= ~drop; q->permitted &= ~drop; if (ambient_supported) q->ambient &= ~drop; return drop != 0; /* Let the caller know we changed something */ } int capability_quintet_enforce(const CapabilityQuintet *q) { _cleanup_cap_free_ cap_t c = NULL, modified = NULL; int r; if (q->ambient != CAP_MASK_UNSET) { bool changed = false; c = cap_get_proc(); if (!c) return -errno; /* In order to raise the ambient caps set we first need to raise the matching * inheritable + permitted cap */ for (unsigned i = 0; i <= cap_last_cap(); i++) { uint64_t m = UINT64_C(1) << i; cap_value_t cv = (cap_value_t) i; cap_flag_value_t old_value_inheritable, old_value_permitted; if ((q->ambient & m) == 0) continue; if (cap_get_flag(c, cv, CAP_INHERITABLE, &old_value_inheritable) < 0) return -errno; if (cap_get_flag(c, cv, CAP_PERMITTED, &old_value_permitted) < 0) return -errno; if (old_value_inheritable == CAP_SET && old_value_permitted == CAP_SET) continue; if (cap_set_flag(c, CAP_INHERITABLE, 1, &cv, CAP_SET) < 0) return -errno; if (cap_set_flag(c, CAP_PERMITTED, 1, &cv, CAP_SET) < 0) return -errno; changed = true; } if (changed) if (cap_set_proc(c) < 0) return -errno; r = capability_ambient_set_apply(q->ambient, false); if (r < 0) return r; } if (q->inheritable != CAP_MASK_UNSET || q->permitted != CAP_MASK_UNSET || q->effective != CAP_MASK_UNSET) { bool changed = false; if (!c) { c = cap_get_proc(); if (!c) return -errno; } for (unsigned i = 0; i <= cap_last_cap(); i++) { uint64_t m = UINT64_C(1) << i; cap_value_t cv = (cap_value_t) i; if (q->inheritable != CAP_MASK_UNSET) { cap_flag_value_t old_value, new_value; if (cap_get_flag(c, cv, CAP_INHERITABLE, &old_value) < 0) { if (errno == EINVAL) /* If the kernel knows more caps than this * version of libcap, then this will return * EINVAL. In that case, simply ignore it, * pretend it doesn't exist. */ continue; return -errno; } new_value = (q->inheritable & m) ? CAP_SET : CAP_CLEAR; if (old_value != new_value) { changed = true; if (cap_set_flag(c, CAP_INHERITABLE, 1, &cv, new_value) < 0) return -errno; } } if (q->permitted != CAP_MASK_UNSET) { cap_flag_value_t old_value, new_value; if (cap_get_flag(c, cv, CAP_PERMITTED, &old_value) < 0) { if (errno == EINVAL) continue; return -errno; } new_value = (q->permitted & m) ? CAP_SET : CAP_CLEAR; if (old_value != new_value) { changed = true; if (cap_set_flag(c, CAP_PERMITTED, 1, &cv, new_value) < 0) return -errno; } } if (q->effective != CAP_MASK_UNSET) { cap_flag_value_t old_value, new_value; if (cap_get_flag(c, cv, CAP_EFFECTIVE, &old_value) < 0) { if (errno == EINVAL) continue; return -errno; } new_value = (q->effective & m) ? CAP_SET : CAP_CLEAR; if (old_value != new_value) { changed = true; if (cap_set_flag(c, CAP_EFFECTIVE, 1, &cv, new_value) < 0) return -errno; } } } if (changed) { /* In order to change the bounding caps, we need to keep CAP_SETPCAP for a bit * longer. Let's add it to our list hence for now. */ if (q->bounding != CAP_MASK_UNSET) { cap_value_t cv = CAP_SETPCAP; modified = cap_dup(c); if (!modified) return -ENOMEM; if (cap_set_flag(modified, CAP_PERMITTED, 1, &cv, CAP_SET) < 0) return -errno; if (cap_set_flag(modified, CAP_EFFECTIVE, 1, &cv, CAP_SET) < 0) return -errno; if (cap_compare(modified, c) == 0) { /* No change? then drop this nonsense again */ cap_free(modified); modified = NULL; } } /* Now, let's enforce the caps for the first time. Note that this is where we acquire * caps in any of the sets we currently don't have. We have to do this before * dropping the bounding caps below, since at that point we can never acquire new * caps in inherited/permitted/effective anymore, but only lose them. */ if (cap_set_proc(modified ?: c) < 0) return -errno; } } if (q->bounding != CAP_MASK_UNSET) { r = capability_bounding_set_drop(q->bounding, false); if (r < 0) return r; } /* If needed, let's now set the caps again, this time in the final version, which differs from what * we have already set only in the CAP_SETPCAP bit, which we needed for dropping the bounding * bits. This call only undoes bits and doesn't acquire any which means the bounding caps don't * matter. */ if (modified) if (cap_set_proc(c) < 0) return -errno; return 0; } int capability_get_ambient(uint64_t *ret) { uint64_t a = 0; int r; assert(ret); if (!ambient_capabilities_supported()) { *ret = 0; return 0; } for (unsigned i = 0; i <= cap_last_cap(); i++) { r = prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, i, 0, 0); if (r < 0) return -errno; if (r) a |= UINT64_C(1) << i; } *ret = a; return 1; }
23,349
35.829653
119
c
null
systemd-main/src/basic/capability-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <stdint.h> #include <sys/capability.h> #include <sys/types.h> #include "macro.h" #include "missing_capability.h" /* Special marker used when storing a capabilities mask as "unset" */ #define CAP_MASK_UNSET UINT64_MAX /* All possible capabilities bits on */ #define CAP_MASK_ALL UINT64_C(0x7fffffffffffffff) /* The largest capability we can deal with, given we want to be able to store cap masks in uint64_t but still * be able to use UINT64_MAX as indicator for "not set". The latter makes capability 63 unavailable. */ #define CAP_LIMIT 62 unsigned cap_last_cap(void); int have_effective_cap(int value); int capability_gain_cap_setpcap(cap_t *return_caps); int capability_bounding_set_drop(uint64_t keep, bool right_now); int capability_bounding_set_drop_usermode(uint64_t keep); int capability_ambient_set_apply(uint64_t set, bool also_inherit); int capability_update_inherited_set(cap_t caps, uint64_t ambient_set); int drop_privileges(uid_t uid, gid_t gid, uint64_t keep_capabilities); int drop_capability(cap_value_t cv); DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(cap_t, cap_free, NULL); #define _cleanup_cap_free_ _cleanup_(cap_freep) static inline void cap_free_charpp(char **p) { if (*p) cap_free(*p); } #define _cleanup_cap_free_charp_ _cleanup_(cap_free_charpp) static inline uint64_t all_capabilities(void) { return UINT64_MAX >> (63 - cap_last_cap()); } static inline bool cap_test_all(uint64_t caps) { return FLAGS_SET(caps, all_capabilities()); } bool ambient_capabilities_supported(void); /* Identical to linux/capability.h's CAP_TO_MASK(), but uses an unsigned 1U instead of a signed 1 for shifting left, in * order to avoid complaints about shifting a signed int left by 31 bits, which would make it negative. */ #define CAP_TO_MASK_CORRECTED(x) (1U << ((x) & 31U)) typedef struct CapabilityQuintet { /* Stores all five types of capabilities in one go. Note that we use UINT64_MAX for unset here. This hence * needs to be updated as soon as Linux learns more than 63 caps. */ uint64_t effective; uint64_t bounding; uint64_t inheritable; uint64_t permitted; uint64_t ambient; } CapabilityQuintet; assert_cc(CAP_LAST_CAP < 64); #define CAPABILITY_QUINTET_NULL { CAP_MASK_UNSET, CAP_MASK_UNSET, CAP_MASK_UNSET, CAP_MASK_UNSET, CAP_MASK_UNSET } static inline bool capability_quintet_is_set(const CapabilityQuintet *q) { return q->effective != CAP_MASK_UNSET || q->bounding != CAP_MASK_UNSET || q->inheritable != CAP_MASK_UNSET || q->permitted != CAP_MASK_UNSET || q->ambient != CAP_MASK_UNSET; } /* Mangles the specified caps quintet taking the current bounding set into account: * drops all caps from all five sets if our bounding set doesn't allow them. * Returns true if the quintet was modified. */ bool capability_quintet_mangle(CapabilityQuintet *q); int capability_quintet_enforce(const CapabilityQuintet *q); int capability_get_ambient(uint64_t *ret);
3,151
34.818182
119
h
null
systemd-main/src/basic/chattr-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <linux/fs.h> #include "chattr-util.h" #include "errno-util.h" #include "fd-util.h" #include "fs-util.h" #include "macro.h" #include "string-util.h" int chattr_full( int dir_fd, const char *path, unsigned value, unsigned mask, unsigned *ret_previous, unsigned *ret_final, ChattrApplyFlags flags) { _cleanup_close_ int fd = -EBADF; unsigned old_attr, new_attr; int set_flags_errno = 0; struct stat st; assert(dir_fd >= 0 || dir_fd == AT_FDCWD); fd = xopenat(dir_fd, path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, /* xopen_flags = */ 0, /* mode = */ 0); if (fd < 0) return -errno; if (fstat(fd, &st) < 0) return -errno; /* Explicitly check whether this is a regular file or directory. If it is anything else (such * as a device node or fifo), then the ioctl will not hit the file systems but possibly * drivers, where the ioctl might have different effects. Notably, DRM is using the same * ioctl() number. */ if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode)) return -ENOTTY; if (mask == 0 && !ret_previous && !ret_final) return 0; if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0) return -errno; new_attr = (old_attr & ~mask) | (value & mask); if (new_attr == old_attr) { if (ret_previous) *ret_previous = old_attr; if (ret_final) *ret_final = old_attr; return 0; } if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) >= 0) { unsigned attr; /* Some filesystems (BTRFS) silently fail when a flag cannot be set. Let's make sure our * changes actually went through by querying the flags again and verifying they're equal to * the flags we tried to configure. */ if (ioctl(fd, FS_IOC_GETFLAGS, &attr) < 0) return -errno; if (new_attr == attr) { if (ret_previous) *ret_previous = old_attr; if (ret_final) *ret_final = new_attr; return 1; } /* Trigger the fallback logic. */ errno = EINVAL; } if ((errno != EINVAL && !ERRNO_IS_NOT_SUPPORTED(errno)) || !FLAGS_SET(flags, CHATTR_FALLBACK_BITWISE)) return -errno; /* When -EINVAL is returned, we assume that incompatible attributes are simultaneously * specified. E.g., compress(c) and nocow(C) attributes cannot be set to files on btrfs. * As a fallback, let's try to set attributes one by one. * * Also, when we get EOPNOTSUPP (or a similar error code) we assume a flag might just not be * supported, and we can ignore it too */ unsigned current_attr = old_attr; for (unsigned i = 0; i < sizeof(unsigned) * 8; i++) { unsigned new_one, mask_one = 1u << i; if (!FLAGS_SET(mask, mask_one)) continue; new_one = UPDATE_FLAG(current_attr, mask_one, FLAGS_SET(value, mask_one)); if (new_one == current_attr) continue; if (ioctl(fd, FS_IOC_SETFLAGS, &new_one) < 0) { if (errno != EINVAL && !ERRNO_IS_NOT_SUPPORTED(errno)) return -errno; log_full_errno(FLAGS_SET(flags, CHATTR_WARN_UNSUPPORTED_FLAGS) ? LOG_WARNING : LOG_DEBUG, errno, "Unable to set file attribute 0x%x on %s, ignoring: %m", mask_one, strna(path)); /* Ensures that we record whether only EOPNOTSUPP&friends are encountered, or if a more serious * error (thus worth logging at a different level, etc) was seen too. */ if (set_flags_errno == 0 || !ERRNO_IS_NOT_SUPPORTED(errno)) set_flags_errno = -errno; continue; } if (ioctl(fd, FS_IOC_GETFLAGS, &current_attr) < 0) return -errno; } if (ret_previous) *ret_previous = old_attr; if (ret_final) *ret_final = current_attr; /* -ENOANO indicates that some attributes cannot be set. ERRNO_IS_NOT_SUPPORTED indicates that all * encountered failures were due to flags not supported by the FS, so return a specific error in * that case, so callers can handle it properly (e.g.: tmpfiles.d can use debug level logging). */ return current_attr == new_attr ? 1 : ERRNO_IS_NOT_SUPPORTED(set_flags_errno) ? set_flags_errno : -ENOANO; } int read_attr_fd(int fd, unsigned *ret) { struct stat st; assert(fd >= 0); if (fstat(fd, &st) < 0) return -errno; if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode)) return -ENOTTY; return RET_NERRNO(ioctl(fd, FS_IOC_GETFLAGS, ret)); } int read_attr_path(const char *p, unsigned *ret) { _cleanup_close_ int fd = -EBADF; assert(p); assert(ret); fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW); if (fd < 0) return -errno; return read_attr_fd(fd, ret); }
5,835
34.803681
119
c
null
systemd-main/src/basic/compress.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <errno.h> #include <stdbool.h> #include <stdint.h> #include <unistd.h> typedef enum Compression { COMPRESSION_NONE, COMPRESSION_XZ, COMPRESSION_LZ4, COMPRESSION_ZSTD, _COMPRESSION_MAX, _COMPRESSION_INVALID = -EINVAL, } Compression; const char* compression_to_string(Compression compression); Compression compression_from_string(const char *compression); bool compression_supported(Compression c); int compress_blob_xz(const void *src, uint64_t src_size, void *dst, size_t dst_alloc_size, size_t *dst_size); int compress_blob_lz4(const void *src, uint64_t src_size, void *dst, size_t dst_alloc_size, size_t *dst_size); int compress_blob_zstd(const void *src, uint64_t src_size, void *dst, size_t dst_alloc_size, size_t *dst_size); int decompress_blob_xz(const void *src, uint64_t src_size, void **dst, size_t* dst_size, size_t dst_max); int decompress_blob_lz4(const void *src, uint64_t src_size, void **dst, size_t* dst_size, size_t dst_max); int decompress_blob_zstd(const void *src, uint64_t src_size, void **dst, size_t* dst_size, size_t dst_max); int decompress_blob(Compression compression, const void *src, uint64_t src_size, void **dst, size_t* dst_size, size_t dst_max); int decompress_startswith_xz(const void *src, uint64_t src_size, void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); int decompress_startswith_lz4(const void *src, uint64_t src_size, void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); int decompress_startswith_zstd(const void *src, uint64_t src_size, void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); int decompress_startswith(Compression compression, const void *src, uint64_t src_size, void **buffer, const void *prefix, size_t prefix_len, uint8_t extra); int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size); int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size); int compress_stream_zstd(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size); int decompress_stream_xz(int fdf, int fdt, uint64_t max_size); int decompress_stream_lz4(int fdf, int fdt, uint64_t max_size); int decompress_stream_zstd(int fdf, int fdt, uint64_t max_size); static inline int compress_blob( Compression compression, const void *src, uint64_t src_size, void *dst, size_t dst_alloc_size, size_t *dst_size) { switch (compression) { case COMPRESSION_ZSTD: return compress_blob_zstd(src, src_size, dst, dst_alloc_size, dst_size); case COMPRESSION_LZ4: return compress_blob_lz4(src, src_size, dst, dst_alloc_size, dst_size); case COMPRESSION_XZ: return compress_blob_xz(src, src_size, dst, dst_alloc_size, dst_size); default: return -EOPNOTSUPP; } } static inline int compress_stream(int fdf, int fdt, uint64_t max_bytes, uint64_t *ret_uncompressed_size) { switch (DEFAULT_COMPRESSION) { case COMPRESSION_ZSTD: return compress_stream_zstd(fdf, fdt, max_bytes, ret_uncompressed_size); case COMPRESSION_LZ4: return compress_stream_lz4(fdf, fdt, max_bytes, ret_uncompressed_size); case COMPRESSION_XZ: return compress_stream_xz(fdf, fdt, max_bytes, ret_uncompressed_size); default: return -EOPNOTSUPP; } } static inline const char* default_compression_extension(void) { switch (DEFAULT_COMPRESSION) { case COMPRESSION_ZSTD: return ".zst"; case COMPRESSION_LZ4: return ".lz4"; case COMPRESSION_XZ: return ".xz"; default: return ""; } } int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes);
4,543
40.309091
106
h
null
systemd-main/src/basic/conf-files.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "macro.h" enum { CONF_FILES_EXECUTABLE = 1 << 0, CONF_FILES_REGULAR = 1 << 1, CONF_FILES_DIRECTORY = 1 << 2, CONF_FILES_BASENAME = 1 << 3, CONF_FILES_FILTER_MASKED = 1 << 4, }; int conf_files_list(char ***ret, const char *suffix, const char *root, unsigned flags, const char *dir); int conf_files_list_at(char ***ret, const char *suffix, int rfd, unsigned flags, const char *dir); int conf_files_list_strv(char ***ret, const char *suffix, const char *root, unsigned flags, const char* const* dirs); int conf_files_list_strv_at(char ***ret, const char *suffix, int rfd, unsigned flags, const char * const *dirs); int conf_files_list_nulstr(char ***ret, const char *suffix, const char *root, unsigned flags, const char *dirs); int conf_files_list_nulstr_at(char ***ret, const char *suffix, int rfd, unsigned flags, const char *dirs); int conf_files_insert(char ***strv, const char *root, char **dirs, const char *path); int conf_files_list_with_replacement( const char *root, char **config_dirs, const char *replacement, char ***files, char **replace_file); int conf_files_list_dropins( char ***ret, const char *dropin_dirname, const char *root, const char * const *dirs);
1,447
44.25
117
h
null
systemd-main/src/basic/confidential-virt.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #if defined(__i386__) || defined(__x86_64__) #include <cpuid.h> #endif #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include "confidential-virt-fundamental.h" #include "confidential-virt.h" #include "fd-util.h" #include "missing_threads.h" #include "string-table.h" #include "utf8.h" #if defined(__x86_64__) static void cpuid(uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx) { log_debug("CPUID func %" PRIx32 " %" PRIx32, *eax, *ecx); __cpuid_count(*eax, *ecx, *eax, *ebx, *ecx, *edx); log_debug("CPUID result %" PRIx32 " %" PRIx32 " %" PRIx32 " %" PRIx32, *eax, *ebx, *ecx, *edx); } static uint32_t cpuid_leaf(uint32_t eax, char ret_sig[static 13], bool swapped) { /* zero-init as some queries explicitly require subleaf == 0 */ uint32_t sig[3] = {}; if (swapped) cpuid(&eax, &sig[0], &sig[2], &sig[1]); else cpuid(&eax, &sig[0], &sig[1], &sig[2]); memcpy(ret_sig, sig, sizeof(sig)); ret_sig[12] = 0; /* \0-terminate the string to make string comparison possible */ /* In some CI tests ret_sig doesn't contain valid UTF8 and prints garbage to the console */ log_debug("CPUID sig '%s'", strna(utf8_is_valid(ret_sig))); return eax; } #define MSR_DEVICE "/dev/cpu/0/msr" static uint64_t msr(uint64_t index) { uint64_t ret; ssize_t rv; _cleanup_close_ int fd = -EBADF; fd = open(MSR_DEVICE, O_RDONLY|O_CLOEXEC); if (fd < 0) { log_debug_errno(errno, "Cannot open MSR device %s (index %" PRIu64 "), ignoring: %m", MSR_DEVICE, index); return 0; } rv = pread(fd, &ret, sizeof(ret), index); if (rv < 0) { log_debug_errno(errno, "Cannot read MSR device %s (index %" PRIu64 "), ignoring: %m", MSR_DEVICE, index); return 0; } else if (rv != sizeof(ret)) { log_debug("Short read %zd bytes from MSR device %s (index %" PRIu64 "), ignoring", rv, MSR_DEVICE, index); return 0; } log_debug("MSR %" PRIu64 " result %" PRIu64 "", index, ret); return ret; } static bool detect_hyperv_sev(void) { uint32_t eax, ebx, ecx, edx, feat; char sig[13] = {}; feat = cpuid_leaf(CPUID_HYPERV_VENDOR_AND_MAX_FUNCTIONS, sig, false); if (feat < CPUID_HYPERV_MIN || feat > CPUID_HYPERV_MAX) return false; if (memcmp(sig, CPUID_SIG_HYPERV, sizeof(sig)) != 0) return false; log_debug("CPUID is on hyperv"); eax = CPUID_HYPERV_FEATURES; ebx = ecx = edx = 0; cpuid(&eax, &ebx, &ecx, &edx); if (ebx & CPUID_HYPERV_ISOLATION && !(ebx & CPUID_HYPERV_CPU_MANAGEMENT)) { eax = CPUID_HYPERV_ISOLATION_CONFIG; ebx = ecx = edx = 0; cpuid(&eax, &ebx, &ecx, &edx); if ((ebx & CPUID_HYPERV_ISOLATION_TYPE_MASK) == CPUID_HYPERV_ISOLATION_TYPE_SNP) return true; } return false; } static ConfidentialVirtualization detect_sev(void) { uint32_t eax, ebx, ecx, edx; uint64_t msrval; eax = CPUID_GET_HIGHEST_FUNCTION; ebx = ecx = edx = 0; cpuid(&eax, &ebx, &ecx, &edx); if (eax < CPUID_AMD_GET_ENCRYPTED_MEMORY_CAPABILITIES) return CONFIDENTIAL_VIRTUALIZATION_NONE; eax = CPUID_AMD_GET_ENCRYPTED_MEMORY_CAPABILITIES; ebx = ecx = edx = 0; cpuid(&eax, &ebx, &ecx, &edx); /* bit 1 == CPU supports SEV feature * * Note, Azure blocks this CPUID leaf from its SEV-SNP * guests, so we must fallback to trying some HyperV * specific CPUID checks. */ if (!(eax & EAX_SEV)) { log_debug("No sev in CPUID, trying hyperv CPUID"); if (detect_hyperv_sev()) return CONFIDENTIAL_VIRTUALIZATION_SEV_SNP; log_debug("No hyperv CPUID"); return CONFIDENTIAL_VIRTUALIZATION_NONE; } msrval = msr(MSR_AMD64_SEV); /* Test reverse order, since the SEV-SNP bit implies * the SEV-ES bit, which implies the SEV bit */ if (msrval & MSR_SEV_SNP) return CONFIDENTIAL_VIRTUALIZATION_SEV_SNP; if (msrval & MSR_SEV_ES) return CONFIDENTIAL_VIRTUALIZATION_SEV_ES; if (msrval & MSR_SEV) return CONFIDENTIAL_VIRTUALIZATION_SEV; return CONFIDENTIAL_VIRTUALIZATION_NONE; } static ConfidentialVirtualization detect_tdx(void) { uint32_t eax, ebx, ecx, edx; char sig[13] = {}; eax = CPUID_GET_HIGHEST_FUNCTION; ebx = ecx = edx = 0; cpuid(&eax, &ebx, &ecx, &edx); if (eax < CPUID_INTEL_TDX_ENUMERATION) return CONFIDENTIAL_VIRTUALIZATION_NONE; cpuid_leaf(CPUID_INTEL_TDX_ENUMERATION, sig, true); if (memcmp(sig, CPUID_SIG_INTEL_TDX, sizeof(sig)) == 0) return CONFIDENTIAL_VIRTUALIZATION_TDX; return CONFIDENTIAL_VIRTUALIZATION_NONE; } static bool detect_hypervisor(void) { uint32_t eax, ebx, ecx, edx; bool is_hv; eax = CPUID_PROCESSOR_INFO_AND_FEATURE_BITS; ebx = ecx = edx = 0; cpuid(&eax, &ebx, &ecx, &edx); is_hv = ecx & CPUID_FEATURE_HYPERVISOR; log_debug("CPUID is hypervisor: %s", yes_no(is_hv)); return is_hv; } ConfidentialVirtualization detect_confidential_virtualization(void) { static thread_local ConfidentialVirtualization cached_found = _CONFIDENTIAL_VIRTUALIZATION_INVALID; char sig[13] = {}; ConfidentialVirtualization cv = CONFIDENTIAL_VIRTUALIZATION_NONE; if (cached_found >= 0) return cached_found; /* Skip everything on bare metal */ if (detect_hypervisor()) { cpuid_leaf(0, sig, true); if (memcmp(sig, CPUID_SIG_AMD, sizeof(sig)) == 0) cv = detect_sev(); else if (memcmp(sig, CPUID_SIG_INTEL, sizeof(sig)) == 0) cv = detect_tdx(); } cached_found = cv; return cv; } #else /* ! x86_64 */ ConfidentialVirtualization detect_confidential_virtualization(void) { log_debug("No confidential virtualization detection on this architecture"); return CONFIDENTIAL_VIRTUALIZATION_NONE; } #endif /* ! x86_64 */ static const char *const confidential_virtualization_table[_CONFIDENTIAL_VIRTUALIZATION_MAX] = { [CONFIDENTIAL_VIRTUALIZATION_NONE] = "none", [CONFIDENTIAL_VIRTUALIZATION_SEV] = "sev", [CONFIDENTIAL_VIRTUALIZATION_SEV_ES] = "sev-es", [CONFIDENTIAL_VIRTUALIZATION_SEV_SNP] = "sev-snp", [CONFIDENTIAL_VIRTUALIZATION_TDX] = "tdx", }; DEFINE_STRING_TABLE_LOOKUP(confidential_virtualization, ConfidentialVirtualization);
7,357
31.131004
107
c
null
systemd-main/src/basic/confidential-virt.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "errno-list.h" #include "macro.h" typedef enum ConfidentialVirtualization { CONFIDENTIAL_VIRTUALIZATION_NONE = 0, CONFIDENTIAL_VIRTUALIZATION_SEV, CONFIDENTIAL_VIRTUALIZATION_SEV_ES, CONFIDENTIAL_VIRTUALIZATION_SEV_SNP, CONFIDENTIAL_VIRTUALIZATION_TDX, _CONFIDENTIAL_VIRTUALIZATION_MAX, _CONFIDENTIAL_VIRTUALIZATION_INVALID = -EINVAL, _CONFIDENTIAL_VIRTUALIZATION_ERRNO_MAX = -ERRNO_MAX, /* ensure full range of errno fits into this enum */ } ConfidentialVirtualization; ConfidentialVirtualization detect_confidential_virtualization(void); const char *confidential_virtualization_to_string(ConfidentialVirtualization v) _const_; ConfidentialVirtualization confidential_virtualization_from_string(const char *s) _pure_;
882
32.961538
113
h
null
systemd-main/src/basic/constants.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #if !defined(HAS_FEATURE_MEMORY_SANITIZER) # if defined(__has_feature) # if __has_feature(memory_sanitizer) # define HAS_FEATURE_MEMORY_SANITIZER 1 # endif # endif # if !defined(HAS_FEATURE_MEMORY_SANITIZER) # define HAS_FEATURE_MEMORY_SANITIZER 0 # endif #endif #if !defined(HAS_FEATURE_ADDRESS_SANITIZER) # ifdef __SANITIZE_ADDRESS__ # define HAS_FEATURE_ADDRESS_SANITIZER 1 # elif defined(__has_feature) # if __has_feature(address_sanitizer) # define HAS_FEATURE_ADDRESS_SANITIZER 1 # endif # endif # if !defined(HAS_FEATURE_ADDRESS_SANITIZER) # define HAS_FEATURE_ADDRESS_SANITIZER 0 # endif #endif #define DEFAULT_RESTART_USEC (100*USEC_PER_MSEC) /* Many different things, but also system unit start/stop */ #define DEFAULT_TIMEOUT_USEC (DEFAULT_TIMEOUT_SEC*USEC_PER_SEC) /* User unit start/stop */ #define DEFAULT_USER_TIMEOUT_USEC (DEFAULT_USER_TIMEOUT_SEC*USEC_PER_SEC) /* Timeout for user confirmation on the console */ #define DEFAULT_CONFIRM_USEC (30*USEC_PER_SEC) /* We use an extra-long timeout for the reload. This is because a reload or reexec means generators are rerun * which are timed out after DEFAULT_TIMEOUT_USEC. Let's use twice that time here, so that the generators can * have their timeout, and for everything else there's the same time budget in place. */ #define DAEMON_RELOAD_TIMEOUT_SEC (DEFAULT_TIMEOUT_USEC * 2) #define DEFAULT_START_LIMIT_INTERVAL (10*USEC_PER_SEC) #define DEFAULT_START_LIMIT_BURST 5 /* Wait for 1.5 seconds at maximum for freeze operation */ #define FREEZE_TIMEOUT (1500 * USEC_PER_MSEC) /* The default time after which exit-on-idle services exit. This * should be kept lower than the watchdog timeout, because otherwise * the watchdog pings will keep the loop busy. */ #define DEFAULT_EXIT_USEC (30*USEC_PER_SEC) /* The default value for the net.unix.max_dgram_qlen sysctl */ #define DEFAULT_UNIX_MAX_DGRAM_QLEN 512 #define SIGNALS_CRASH_HANDLER SIGSEGV,SIGILL,SIGFPE,SIGBUS,SIGQUIT,SIGABRT #define SIGNALS_IGNORE SIGPIPE #define NOTIFY_FD_MAX 768 #define NOTIFY_BUFFER_MAX PIPE_BUF #if HAVE_SPLIT_USR # define _CONF_PATHS_SPLIT_USR_NULSTR(n) "/lib/" n "\0" # define _CONF_PATHS_SPLIT_USR(n) , "/lib/" n #else # define _CONF_PATHS_SPLIT_USR_NULSTR(n) # define _CONF_PATHS_SPLIT_USR(n) #endif /* Return a nulstr for a standard cascade of configuration paths, suitable to pass to * conf_files_list_nulstr() to implement drop-in directories for extending configuration files. */ #define CONF_PATHS_NULSTR(n) \ "/etc/" n "\0" \ "/run/" n "\0" \ "/usr/local/lib/" n "\0" \ "/usr/lib/" n "\0" \ _CONF_PATHS_SPLIT_USR_NULSTR(n) #define CONF_PATHS_USR(n) \ "/etc/" n, \ "/run/" n, \ "/usr/local/lib/" n, \ "/usr/lib/" n #define CONF_PATHS(n) \ CONF_PATHS_USR(n) \ _CONF_PATHS_SPLIT_USR(n) #define CONF_PATHS_USR_STRV(n) \ STRV_MAKE(CONF_PATHS_USR(n)) #define CONF_PATHS_STRV(n) \ STRV_MAKE(CONF_PATHS(n)) /* The limit for PID 1 itself (which is not inherited to children) */ #define HIGH_RLIMIT_MEMLOCK (1024ULL*1024ULL*64ULL) /* Since kernel 5.16 the kernel default limit was raised to 8M. Let's adjust things on old kernels too, and * in containers so that our children inherit that. */ #define DEFAULT_RLIMIT_MEMLOCK (1024ULL*1024ULL*8ULL) #define PLYMOUTH_SOCKET { \ .un.sun_family = AF_UNIX, \ .un.sun_path = "\0/org/freedesktop/plymouthd", \ } /* Path where PID1 listens for varlink subscriptions from systemd-oomd to notify of changes in ManagedOOM settings. */ #define VARLINK_ADDR_PATH_MANAGED_OOM_SYSTEM "/run/systemd/io.system.ManagedOOM" /* Path where systemd-oomd listens for varlink connections from user managers to report changes in ManagedOOM settings. */ #define VARLINK_ADDR_PATH_MANAGED_OOM_USER "/run/systemd/oom/io.system.ManagedOOM" #define KERNEL_BASELINE_VERSION "4.15"
4,371
37.690265
122
h
null
systemd-main/src/basic/coverage.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /* Use the coverage-related tweaks below only for C stuff as they're not really * C++ compatible, and the only thing that is built with a C++ compiler is * the lone test-bus-vtable-cc unit test. */ #ifndef __cplusplus void __gcov_dump(void); void __gcov_reset(void); /* When built with --coverage (gcov) we need to explicitly call __gcov_dump() * in places where we use _exit(), since _exit() skips at-exit hooks resulting * in lost coverage. * * To make sure we don't miss any _exit() calls, this header file is included * explicitly on the compiler command line via the -include directive (only * when built with -Db_coverage=true) */ void _exit(int); static inline _Noreturn void _coverage__exit(int status) { __gcov_dump(); _exit(status); } #define _exit(x) _coverage__exit(x) /* gcov provides wrappers for the exec*() calls but there's none for execveat() * and execvpe() which means we lose all coverage prior to such call. To mitigate * this, let's add simple wrappers in gcov's style[0] for these exec*() calls, * which dump and reset the coverage data as needed. * * [0] https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libgcc/libgcov-interface.c;h=b2ee930864183b78c8826255183ca86e15e21ded;hb=HEAD */ int execveat(int, const char *, char * const [], char * const [], int); int execvpe(const char *, char * const [], char * const []); static inline int _coverage_execveat( int dirfd, const char *pathname, char * const argv[], char * const envp[], int flags) { __gcov_dump(); int r = execveat(dirfd, pathname, argv, envp, flags); __gcov_reset(); return r; } #define execveat(d,p,a,e,f) _coverage_execveat(d, p, a, e, f) static inline int _coverage_execvpe( const char *file, char * const argv[], char * const envp[]) { __gcov_dump(); int r = execvpe(file, argv, envp); __gcov_reset(); return r; } #define execvpe(f,a,e) _coverage_execvpe(f, a, e) #endif
2,218
32.119403
128
h
null
systemd-main/src/basic/devnum-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <string.h> #include <sys/stat.h> #include "chase.h" #include "devnum-util.h" #include "parse-util.h" #include "path-util.h" #include "string-util.h" int parse_devnum(const char *s, dev_t *ret) { const char *major; unsigned x, y; size_t n; int r; n = strspn(s, DIGITS); if (n == 0) return -EINVAL; if (n > DECIMAL_STR_MAX(dev_t)) return -EINVAL; if (s[n] != ':') return -EINVAL; major = strndupa_safe(s, n); r = safe_atou(major, &x); if (r < 0) return r; r = safe_atou(s + n + 1, &y); if (r < 0) return r; if (!DEVICE_MAJOR_VALID(x) || !DEVICE_MINOR_VALID(y)) return -ERANGE; *ret = makedev(x, y); return 0; } int device_path_make_major_minor(mode_t mode, dev_t devnum, char **ret) { const char *t; /* Generates the /dev/{char|block}/MAJOR:MINOR path for a dev_t */ if (S_ISCHR(mode)) t = "char"; else if (S_ISBLK(mode)) t = "block"; else return -ENODEV; if (asprintf(ret, "/dev/%s/" DEVNUM_FORMAT_STR, t, DEVNUM_FORMAT_VAL(devnum)) < 0) return -ENOMEM; return 0; } int device_path_make_inaccessible(mode_t mode, char **ret) { char *s; assert(ret); if (S_ISCHR(mode)) s = strdup("/run/systemd/inaccessible/chr"); else if (S_ISBLK(mode)) s = strdup("/run/systemd/inaccessible/blk"); else return -ENODEV; if (!s) return -ENOMEM; *ret = s; return 0; } int device_path_make_canonical(mode_t mode, dev_t devnum, char **ret) { _cleanup_free_ char *p = NULL; int r; /* Finds the canonical path for a device, i.e. resolves the /dev/{char|block}/MAJOR:MINOR path to the end. */ assert(ret); if (devnum_is_zero(devnum)) /* A special hack to make sure our 'inaccessible' device nodes work. They won't have symlinks in * /dev/block/ and /dev/char/, hence we handle them specially here. */ return device_path_make_inaccessible(mode, ret); r = device_path_make_major_minor(mode, devnum, &p); if (r < 0) return r; return chase(p, NULL, 0, ret, NULL); } int device_path_parse_major_minor(const char *path, mode_t *ret_mode, dev_t *ret_devnum) { mode_t mode; dev_t devnum; int r; /* Tries to extract the major/minor directly from the device path if we can. Handles /dev/block/ and /dev/char/ * paths, as well out synthetic inaccessible device nodes. Never goes to disk. Returns -ENODEV if the device * path cannot be parsed like this. */ if (path_equal(path, "/run/systemd/inaccessible/chr")) { mode = S_IFCHR; devnum = makedev(0, 0); } else if (path_equal(path, "/run/systemd/inaccessible/blk")) { mode = S_IFBLK; devnum = makedev(0, 0); } else { const char *w; w = path_startswith(path, "/dev/block/"); if (w) mode = S_IFBLK; else { w = path_startswith(path, "/dev/char/"); if (!w) return -ENODEV; mode = S_IFCHR; } r = parse_devnum(w, &devnum); if (r < 0) return r; } if (ret_mode) *ret_mode = mode; if (ret_devnum) *ret_devnum = devnum; return 0; }
3,892
27.007194
119
c
null
systemd-main/src/basic/devnum-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include <stdbool.h> #include <sys/types.h> #include "stdio-util.h" int parse_devnum(const char *s, dev_t *ret); /* glibc and the Linux kernel have different ideas about the major/minor size. These calls will check whether the * specified major is valid by the Linux kernel's standards, not by glibc's. Linux has 20bits of minor, and 12 bits of * major space. See MINORBITS in linux/kdev_t.h in the kernel sources. (If you wonder why we define _y here, instead of * comparing directly >= 0: it's to trick out -Wtype-limits, which would otherwise complain if the type is unsigned, as * such a test would be pointless in such a case.) */ #define DEVICE_MAJOR_VALID(x) \ ({ \ typeof(x) _x = (x), _y = 0; \ _x >= _y && _x < (UINT32_C(1) << 12); \ \ }) #define DEVICE_MINOR_VALID(x) \ ({ \ typeof(x) _x = (x), _y = 0; \ _x >= _y && _x < (UINT32_C(1) << 20); \ }) int device_path_make_major_minor(mode_t mode, dev_t devnum, char **ret); int device_path_make_inaccessible(mode_t mode, char **ret); int device_path_make_canonical(mode_t mode, dev_t devnum, char **ret); int device_path_parse_major_minor(const char *path, mode_t *ret_mode, dev_t *ret_devnum); static inline bool devnum_set_and_equal(dev_t a, dev_t b) { /* Returns true if a and b definitely refer to the same device. If either is zero, this means "don't * know" and we'll return false */ return a == b && a != 0; } /* Maximum string length for a major:minor string. (Note that DECIMAL_STR_MAX includes space for a trailing NUL) */ #define DEVNUM_STR_MAX (DECIMAL_STR_MAX(dev_t)-1+1+DECIMAL_STR_MAX(dev_t)) #define DEVNUM_FORMAT_STR "%u:%u" #define DEVNUM_FORMAT_VAL(d) major(d), minor(d) static inline char *format_devnum(dev_t d, char buf[static DEVNUM_STR_MAX]) { return ASSERT_PTR(snprintf_ok(buf, DEVNUM_STR_MAX, DEVNUM_FORMAT_STR, DEVNUM_FORMAT_VAL(d))); } #define FORMAT_DEVNUM(d) format_devnum((d), (char[DEVNUM_STR_MAX]) {}) static inline bool devnum_is_zero(dev_t d) { return major(d) == 0 && minor(d) == 0; }
2,586
44.385965
119
h
null
systemd-main/src/basic/dirent-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <sys/stat.h> #include "dirent-util.h" #include "path-util.h" #include "stat-util.h" #include "string-util.h" int dirent_ensure_type(int dir_fd, struct dirent *de) { STRUCT_STATX_DEFINE(sx); int r; assert(dir_fd >= 0); assert(de); if (de->d_type != DT_UNKNOWN) return 0; if (dot_or_dot_dot(de->d_name)) { de->d_type = DT_DIR; return 0; } /* Let's ask only for the type, nothing else. */ r = statx_fallback(dir_fd, de->d_name, AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT, STATX_TYPE, &sx); if (r < 0) return r; assert(FLAGS_SET(sx.stx_mask, STATX_TYPE)); de->d_type = IFTODT(sx.stx_mode); /* If the inode is passed too, update the field, i.e. report most recent data */ if (FLAGS_SET(sx.stx_mask, STATX_INO)) de->d_ino = sx.stx_ino; return 0; } bool dirent_is_file(const struct dirent *de) { assert(de); if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN)) return false; if (hidden_or_backup_file(de->d_name)) return false; return true; } bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) { assert(de); if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN)) return false; if (de->d_name[0] == '.') return false; if (!suffix) return true; return endswith(de->d_name, suffix); } struct dirent *readdir_ensure_type(DIR *d) { int r; assert(d); /* Like readdir(), but fills in .d_type if it is DT_UNKNOWN */ for (;;) { struct dirent *de; errno = 0; de = readdir(d); if (!de) return NULL; r = dirent_ensure_type(dirfd(d), de); if (r >= 0) return de; if (r != -ENOENT) { errno = -r; /* We want to be compatible with readdir(), hence propagate error via errno here */ return NULL; } /* Vanished by now? Then skip immediately to next */ } } struct dirent *readdir_no_dot(DIR *d) { assert(d); for (;;) { struct dirent *de; de = readdir_ensure_type(d); if (!de || !dot_or_dot_dot(de->d_name)) return de; } }
2,646
23.971698
119
c
null
systemd-main/src/basic/dirent-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <dirent.h> #include <errno.h> #include <stdbool.h> #include "macro.h" #include "path-util.h" bool dirent_is_file(const struct dirent *de) _pure_; bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) _pure_; int dirent_ensure_type(int dir_fd, struct dirent *de); struct dirent *readdir_ensure_type(DIR *d); struct dirent *readdir_no_dot(DIR *dirp); #define FOREACH_DIRENT_ALL(de, d, on_error) \ for (struct dirent *(de) = readdir_ensure_type(d);; (de) = readdir_ensure_type(d)) \ if (!de) { \ if (errno > 0) { \ on_error; \ } \ break; \ } else #define FOREACH_DIRENT(de, d, on_error) \ FOREACH_DIRENT_ALL(de, d, on_error) \ if (hidden_or_backup_file((de)->d_name)) \ continue; \ else /* Maximum space one dirent structure might require at most */ #define DIRENT_SIZE_MAX CONST_MAX(sizeof(struct dirent), offsetof(struct dirent, d_name) + NAME_MAX + 1) /* Only if 64-bit off_t is enabled struct dirent + struct dirent64 are actually the same. We require this, and * we want them to be interchangeable to make getdents64() work, hence verify that. */ assert_cc(_FILE_OFFSET_BITS == 64); #if HAVE_STRUCT_DIRENT64 assert_cc(sizeof(struct dirent) == sizeof(struct dirent64)); assert_cc(offsetof(struct dirent, d_ino) == offsetof(struct dirent64, d_ino)); assert_cc(sizeof_field(struct dirent, d_ino) == sizeof_field(struct dirent64, d_ino)); assert_cc(offsetof(struct dirent, d_off) == offsetof(struct dirent64, d_off)); assert_cc(sizeof_field(struct dirent, d_off) == sizeof_field(struct dirent64, d_off)); assert_cc(offsetof(struct dirent, d_reclen) == offsetof(struct dirent64, d_reclen)); assert_cc(sizeof_field(struct dirent, d_reclen) == sizeof_field(struct dirent64, d_reclen)); assert_cc(offsetof(struct dirent, d_type) == offsetof(struct dirent64, d_type)); assert_cc(sizeof_field(struct dirent, d_type) == sizeof_field(struct dirent64, d_type)); assert_cc(offsetof(struct dirent, d_name) == offsetof(struct dirent64, d_name)); assert_cc(sizeof_field(struct dirent, d_name) == sizeof_field(struct dirent64, d_name)); #endif #define FOREACH_DIRENT_IN_BUFFER(de, buf, sz) \ for (void *_end = (uint8_t*) ({ (de) = (buf); }) + (sz); \ (uint8_t*) (de) < (uint8_t*) _end; \ (de) = (struct dirent*) ((uint8_t*) (de) + (de)->d_reclen)) #define DEFINE_DIRENT_BUFFER(name, sz) \ union { \ struct dirent de; \ uint8_t data[(sz) * DIRENT_SIZE_MAX]; \ } name
3,278
51.047619
110
h
null
systemd-main/src/basic/dns-def.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /* Length of a single label, with all escaping removed, excluding any trailing dot or NUL byte */ #define DNS_LABEL_MAX 63 /* Worst case length of a single label, with all escaping applied and room for a trailing NUL byte. */ #define DNS_LABEL_ESCAPED_MAX (DNS_LABEL_MAX*4+1) /* Maximum length of a full hostname, consisting of a series of unescaped labels, and no trailing dot or NUL byte */ #define DNS_HOSTNAME_MAX 253 /* Maximum length of a full hostname, on the wire, including the final NUL byte */ #define DNS_WIRE_FORMAT_HOSTNAME_MAX 255 /* Maximum number of labels per valid hostname */ #define DNS_N_LABELS_MAX 127
692
37.5
116
h
null
systemd-main/src/basic/efivars.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #if !ENABLE_EFI # include <errno.h> #endif #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include "sd-id128.h" #include "efivars-fundamental.h" #include "time-util.h" #define EFI_VENDOR_LOADER SD_ID128_MAKE(4a,67,b0,82,0a,4c,41,cf,b6,c7,44,0b,29,bb,8c,4f) #define EFI_VENDOR_LOADER_STR SD_ID128_MAKE_UUID_STR(4a,67,b0,82,0a,4c,41,cf,b6,c7,44,0b,29,bb,8c,4f) #define EFI_VENDOR_GLOBAL SD_ID128_MAKE(8b,e4,df,61,93,ca,11,d2,aa,0d,00,e0,98,03,2b,8c) #define EFI_VENDOR_GLOBAL_STR SD_ID128_MAKE_UUID_STR(8b,e4,df,61,93,ca,11,d2,aa,0d,00,e0,98,03,2b,8c) #define EFI_VENDOR_SYSTEMD SD_ID128_MAKE(8c,f2,64,4b,4b,0b,42,8f,93,87,6d,87,60,50,dc,67) #define EFI_VENDOR_SYSTEMD_STR SD_ID128_MAKE_UUID_STR(8c,f2,64,4b,4b,0b,42,8f,93,87,6d,87,60,50,dc,67) #define EFI_VARIABLE_NON_VOLATILE UINT32_C(0x00000001) #define EFI_VARIABLE_BOOTSERVICE_ACCESS UINT32_C(0x00000002) #define EFI_VARIABLE_RUNTIME_ACCESS UINT32_C(0x00000004) /* Note that the <lowercaseuuid>-<varname> naming scheme is an efivarfs convention, i.e. part of the Linux * API file system implementation for EFI. EFI itself processes UIDS in binary form. */ #define EFI_VENDOR_VARIABLE_STR(vendor, name) name "-" vendor #define EFI_GLOBAL_VARIABLE_STR(name) EFI_VENDOR_VARIABLE_STR(EFI_VENDOR_GLOBAL_STR, name) #define EFI_LOADER_VARIABLE_STR(name) EFI_VENDOR_VARIABLE_STR(EFI_VENDOR_LOADER_STR, name) #define EFI_SYSTEMD_VARIABLE_STR(name) EFI_VENDOR_VARIABLE_STR(EFI_VENDOR_SYSTEMD_STR, name) #define EFI_GLOBAL_VARIABLE(name) EFI_GLOBAL_VARIABLE_STR(STRINGIFY(name)) #define EFI_LOADER_VARIABLE(name) EFI_LOADER_VARIABLE_STR(STRINGIFY(name)) #define EFI_SYSTEMD_VARIABLE(name) EFI_SYSTEMD_VARIABLE_STR(STRINGIFY(name)) #define EFIVAR_PATH(variable) "/sys/firmware/efi/efivars/" variable #define EFIVAR_CACHE_PATH(variable) "/run/systemd/efivars/" variable #if ENABLE_EFI int efi_get_variable(const char *variable, uint32_t *attribute, void **ret_value, size_t *ret_size); int efi_get_variable_string(const char *variable, char **ret); int efi_set_variable(const char *variable, const void *value, size_t size); int efi_set_variable_string(const char *variable, const char *p); bool is_efi_boot(void); bool is_efi_secure_boot(void); SecureBootMode efi_get_secure_boot_mode(void); int cache_efi_options_variable(void); int systemd_efi_options_variable(char **ret); int systemd_efi_options_efivarfs_if_newer(char **ret); #else static inline int efi_get_variable(const char *variable, uint32_t *attribute, void **value, size_t *size) { return -EOPNOTSUPP; } static inline int efi_get_variable_string(const char *variable, char **ret) { return -EOPNOTSUPP; } static inline int efi_set_variable(const char *variable, const void *value, size_t size) { return -EOPNOTSUPP; } static inline int efi_set_variable_string(const char *variable, const char *p) { return -EOPNOTSUPP; } static inline bool is_efi_boot(void) { return false; } static inline bool is_efi_secure_boot(void) { return false; } static inline SecureBootMode efi_get_secure_boot_mode(void) { return SECURE_BOOT_UNKNOWN; } static inline int cache_efi_options_variable(void) { return -EOPNOTSUPP; } static inline int systemd_efi_options_variable(char **line) { return -ENODATA; } static inline int systemd_efi_options_efivarfs_if_newer(char **line) { return -ENODATA; } #endif
3,497
33.633663
107
h
null
systemd-main/src/basic/env-file.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "env-file.h" #include "env-util.h" #include "escape.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "string-util.h" #include "strv.h" #include "tmpfile-util.h" #include "utf8.h" typedef int (*push_env_func_t)( const char *filename, unsigned line, const char *key, char *value, void *userdata); static int parse_env_file_internal( FILE *f, const char *fname, push_env_func_t push, void *userdata) { size_t n_key = 0, n_value = 0, last_value_whitespace = SIZE_MAX, last_key_whitespace = SIZE_MAX; _cleanup_free_ char *contents = NULL, *key = NULL, *value = NULL; unsigned line = 1; int r; enum { PRE_KEY, KEY, PRE_VALUE, VALUE, VALUE_ESCAPE, SINGLE_QUOTE_VALUE, DOUBLE_QUOTE_VALUE, DOUBLE_QUOTE_VALUE_ESCAPE, COMMENT, COMMENT_ESCAPE } state = PRE_KEY; assert(f || fname); assert(push); if (f) r = read_full_stream(f, &contents, NULL); else r = read_full_file(fname, &contents, NULL); if (r < 0) return r; for (char *p = contents; *p; p++) { char c = *p; switch (state) { case PRE_KEY: if (strchr(COMMENTS, c)) state = COMMENT; else if (!strchr(WHITESPACE, c)) { state = KEY; last_key_whitespace = SIZE_MAX; if (!GREEDY_REALLOC(key, n_key+2)) return -ENOMEM; key[n_key++] = c; } break; case KEY: if (strchr(NEWLINE, c)) { state = PRE_KEY; line++; n_key = 0; } else if (c == '=') { state = PRE_VALUE; last_value_whitespace = SIZE_MAX; } else { if (!strchr(WHITESPACE, c)) last_key_whitespace = SIZE_MAX; else if (last_key_whitespace == SIZE_MAX) last_key_whitespace = n_key; if (!GREEDY_REALLOC(key, n_key+2)) return -ENOMEM; key[n_key++] = c; } break; case PRE_VALUE: if (strchr(NEWLINE, c)) { state = PRE_KEY; line++; key[n_key] = 0; if (value) value[n_value] = 0; /* strip trailing whitespace from key */ if (last_key_whitespace != SIZE_MAX) key[last_key_whitespace] = 0; r = push(fname, line, key, value, userdata); if (r < 0) return r; n_key = 0; value = NULL; n_value = 0; } else if (c == '\'') state = SINGLE_QUOTE_VALUE; else if (c == '"') state = DOUBLE_QUOTE_VALUE; else if (c == '\\') state = VALUE_ESCAPE; else if (!strchr(WHITESPACE, c)) { state = VALUE; if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; } break; case VALUE: if (strchr(NEWLINE, c)) { state = PRE_KEY; line++; key[n_key] = 0; if (value) value[n_value] = 0; /* Chomp off trailing whitespace from value */ if (last_value_whitespace != SIZE_MAX) value[last_value_whitespace] = 0; /* strip trailing whitespace from key */ if (last_key_whitespace != SIZE_MAX) key[last_key_whitespace] = 0; r = push(fname, line, key, value, userdata); if (r < 0) return r; n_key = 0; value = NULL; n_value = 0; } else if (c == '\\') { state = VALUE_ESCAPE; last_value_whitespace = SIZE_MAX; } else { if (!strchr(WHITESPACE, c)) last_value_whitespace = SIZE_MAX; else if (last_value_whitespace == SIZE_MAX) last_value_whitespace = n_value; if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; } break; case VALUE_ESCAPE: state = VALUE; if (!strchr(NEWLINE, c)) { /* Escaped newlines we eat up entirely */ if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; } break; case SINGLE_QUOTE_VALUE: if (c == '\'') state = PRE_VALUE; else { if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; } break; case DOUBLE_QUOTE_VALUE: if (c == '"') state = PRE_VALUE; else if (c == '\\') state = DOUBLE_QUOTE_VALUE_ESCAPE; else { if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; } break; case DOUBLE_QUOTE_VALUE_ESCAPE: state = DOUBLE_QUOTE_VALUE; if (strchr(SHELL_NEED_ESCAPE, c)) { /* If this is a char that needs escaping, just unescape it. */ if (!GREEDY_REALLOC(value, n_value+2)) return -ENOMEM; value[n_value++] = c; } else if (c != '\n') { /* If other char than what needs escaping, keep the "\" in place, like the * real shell does. */ if (!GREEDY_REALLOC(value, n_value+3)) return -ENOMEM; value[n_value++] = '\\'; value[n_value++] = c; } /* Escaped newlines (aka "continuation lines") are eaten up entirely */ break; case COMMENT: if (c == '\\') state = COMMENT_ESCAPE; else if (strchr(NEWLINE, c)) { state = PRE_KEY; line++; } break; case COMMENT_ESCAPE: log_debug("The line which doesn't begin with \";\" or \"#\", but follows a comment" \ " line trailing with escape is now treated as a non comment line since v254."); if (strchr(NEWLINE, c)) { state = PRE_KEY; line++; } else state = COMMENT; break; } } if (IN_SET(state, PRE_VALUE, VALUE, VALUE_ESCAPE, SINGLE_QUOTE_VALUE, DOUBLE_QUOTE_VALUE, DOUBLE_QUOTE_VALUE_ESCAPE)) { key[n_key] = 0; if (value) value[n_value] = 0; if (state == VALUE) if (last_value_whitespace != SIZE_MAX) value[last_value_whitespace] = 0; /* strip trailing whitespace from key */ if (last_key_whitespace != SIZE_MAX) key[last_key_whitespace] = 0; r = push(fname, line, key, value, userdata); if (r < 0) return r; value = NULL; } return 0; } static int check_utf8ness_and_warn( const char *filename, unsigned line, const char *key, char *value) { assert(key); if (!utf8_is_valid(key)) { _cleanup_free_ char *p = NULL; p = utf8_escape_invalid(key); return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p); } if (value && !utf8_is_valid(value)) { _cleanup_free_ char *p = NULL; p = utf8_escape_invalid(value); return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p); } return 0; } static int parse_env_file_push( const char *filename, unsigned line, const char *key, char *value, void *userdata) { const char *k; va_list aq, *ap = userdata; int r; assert(key); r = check_utf8ness_and_warn(filename, line, key, value); if (r < 0) return r; va_copy(aq, *ap); while ((k = va_arg(aq, const char *))) { char **v; v = va_arg(aq, char **); if (streq(key, k)) { va_end(aq); free_and_replace(*v, value); return 1; } } va_end(aq); free(value); return 0; } int parse_env_filev( FILE *f, const char *fname, va_list ap) { int r; va_list aq; assert(f || fname); va_copy(aq, ap); r = parse_env_file_internal(f, fname, parse_env_file_push, &aq); va_end(aq); return r; } int parse_env_file_fdv(int fd, const char *fname, va_list ap) { _cleanup_fclose_ FILE *f = NULL; va_list aq; int r; assert(fd >= 0); r = fdopen_independent(fd, "re", &f); if (r < 0) return r; va_copy(aq, ap); r = parse_env_file_internal(f, fname, parse_env_file_push, &aq); va_end(aq); return r; } int parse_env_file_sentinel( FILE *f, const char *fname, ...) { va_list ap; int r; assert(f || fname); va_start(ap, fname); r = parse_env_filev(f, fname, ap); va_end(ap); return r; } int parse_env_file_fd_sentinel( int fd, const char *fname, /* only used for logging */ ...) { va_list ap; int r; assert(fd >= 0); va_start(ap, fname); r = parse_env_file_fdv(fd, fname, ap); va_end(ap); return r; } static int load_env_file_push( const char *filename, unsigned line, const char *key, char *value, void *userdata) { char ***m = userdata; char *p; int r; assert(key); r = check_utf8ness_and_warn(filename, line, key, value); if (r < 0) return r; p = strjoin(key, "=", value); if (!p) return -ENOMEM; r = strv_env_replace_consume(m, p); if (r < 0) return r; free(value); return 0; } int load_env_file(FILE *f, const char *fname, char ***ret) { _cleanup_strv_free_ char **m = NULL; int r; assert(f || fname); assert(ret); r = parse_env_file_internal(f, fname, load_env_file_push, &m); if (r < 0) return r; *ret = TAKE_PTR(m); return 0; } static int load_env_file_push_pairs( const char *filename, unsigned line, const char *key, char *value, void *userdata) { char ***m = ASSERT_PTR(userdata); int r; assert(key); r = check_utf8ness_and_warn(filename, line, key, value); if (r < 0) return r; /* Check if the key is present */ for (char **t = *m; t && *t; t += 2) if (streq(t[0], key)) { if (value) return free_and_replace(t[1], value); else return free_and_strdup(t+1, ""); } r = strv_extend(m, key); if (r < 0) return r; if (value) return strv_push(m, value); else return strv_extend(m, ""); } int load_env_file_pairs(FILE *f, const char *fname, char ***ret) { _cleanup_strv_free_ char **m = NULL; int r; assert(f || fname); assert(ret); r = parse_env_file_internal(f, fname, load_env_file_push_pairs, &m); if (r < 0) return r; *ret = TAKE_PTR(m); return 0; } int load_env_file_pairs_fd(int fd, const char *fname, char ***ret) { _cleanup_fclose_ FILE *f = NULL; int r; assert(fd >= 0); r = fdopen_independent(fd, "re", &f); if (r < 0) return r; return load_env_file_pairs(f, fname, ret); } static int merge_env_file_push( const char *filename, unsigned line, const char *key, char *value, void *userdata) { char ***env = ASSERT_PTR(userdata); char *expanded_value; int r; assert(key); if (!value) { log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key); return 0; } if (!env_name_is_valid(key)) { log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key); free(value); return 0; } r = replace_env(value, *env, REPLACE_ENV_USE_ENVIRONMENT|REPLACE_ENV_ALLOW_BRACELESS|REPLACE_ENV_ALLOW_EXTENDED, &expanded_value); if (r < 0) return log_error_errno(r, "%s:%u: Failed to expand variable '%s': %m", strna(filename), line, value); free_and_replace(value, expanded_value); log_debug("%s:%u: setting %s=%s", filename, line, key, value); return load_env_file_push(filename, line, key, value, env); } int merge_env_file( char ***env, FILE *f, const char *fname) { assert(env); assert(f || fname); /* NOTE: this function supports braceful and braceless variable expansions, * plus "extended" substitutions, unlike other exported parsing functions. */ return parse_env_file_internal(f, fname, merge_env_file_push, env); } static void write_env_var(FILE *f, const char *v) { const char *p; assert(f); assert(v); p = strchr(v, '='); if (!p) { /* Fallback */ fputs_unlocked(v, f); fputc_unlocked('\n', f); return; } p++; fwrite_unlocked(v, 1, p-v, f); if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) { fputc_unlocked('"', f); for (; *p; p++) { if (strchr(SHELL_NEED_ESCAPE, *p)) fputc_unlocked('\\', f); fputc_unlocked(*p, f); } fputc_unlocked('"', f); } else fputs_unlocked(p, f); fputc_unlocked('\n', f); } int write_env_file_at(int dir_fd, const char *fname, char **l) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *p = NULL; int r; assert(dir_fd >= 0 || dir_fd == AT_FDCWD); assert(fname); r = fopen_temporary_at(dir_fd, fname, &f, &p); if (r < 0) return r; (void) fchmod_umask(fileno(f), 0644); STRV_FOREACH(i, l) write_env_var(f, *i); r = fflush_and_check(f); if (r >= 0) { if (renameat(dir_fd, p, dir_fd, fname) >= 0) return 0; r = -errno; } (void) unlinkat(dir_fd, p, 0); return r; }
19,078
29.09306
117
c
null
systemd-main/src/basic/env-file.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include "macro.h" int parse_env_filev(FILE *f, const char *fname, va_list ap); int parse_env_file_fdv(int fd, const char *fname, va_list ap); int parse_env_file_sentinel(FILE *f, const char *fname, ...) _sentinel_; #define parse_env_file(f, fname, ...) parse_env_file_sentinel(f, fname, __VA_ARGS__, NULL) int parse_env_file_fd_sentinel(int fd, const char *fname, ...) _sentinel_; #define parse_env_file_fd(fd, fname, ...) parse_env_file_fd_sentinel(fd, fname, __VA_ARGS__, NULL) int load_env_file(FILE *f, const char *fname, char ***ret); int load_env_file_pairs(FILE *f, const char *fname, char ***ret); int load_env_file_pairs_fd(int fd, const char *fname, char ***ret); int merge_env_file(char ***env, FILE *f, const char *fname); int write_env_file_at(int dir_fd, const char *fname, char **l); static inline int write_env_file(const char *fname, char **l) { return write_env_file_at(AT_FDCWD, fname, l); }
1,045
39.230769
98
h
null
systemd-main/src/basic/errno-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdlib.h> #include <string.h> #include "macro.h" /* strerror(3) says that glibc uses a maximum length of 1024 bytes. */ #define ERRNO_BUF_LEN 1024 /* Note: the lifetime of the compound literal is the immediately surrounding block, * see C11 §6.5.2.5, and * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks * * Note that we use the GNU variant of strerror_r() here. */ #define STRERROR(errnum) strerror_r(abs(errnum), (char[ERRNO_BUF_LEN]){}, ERRNO_BUF_LEN) /* A helper to print an error message or message for functions that return 0 on EOF. * Note that we can't use ({ … }) to define a temporary variable, so errnum is * evaluated twice. */ #define STRERROR_OR_EOF(errnum) ((errnum) != 0 ? STRERROR(errnum) : "Unexpected EOF") static inline void _reset_errno_(int *saved_errno) { if (*saved_errno < 0) /* Invalidated by UNPROTECT_ERRNO? */ return; errno = *saved_errno; } #define PROTECT_ERRNO \ _cleanup_(_reset_errno_) _unused_ int _saved_errno_ = errno #define UNPROTECT_ERRNO \ do { \ errno = _saved_errno_; \ _saved_errno_ = -1; \ } while (false) #define LOCAL_ERRNO(value) \ PROTECT_ERRNO; \ errno = abs(value) static inline int negative_errno(void) { /* This helper should be used to shut up gcc if you know 'errno' is * negative. Instead of "return -errno;", use "return negative_errno();" * It will suppress bogus gcc warnings in case it assumes 'errno' might * be 0 and thus the caller's error-handling might not be triggered. */ assert_return(errno > 0, -EINVAL); return -errno; } static inline int RET_NERRNO(int ret) { /* Helper to wrap system calls in to make them return negative errno errors. This brings system call * error handling in sync with how we usually handle errors in our own code, i.e. with immediate * returning of negative errno. Usage is like this: * * … * r = RET_NERRNO(unlink(t)); * … * * or * * … * fd = RET_NERRNO(open("/etc/fstab", O_RDONLY|O_CLOEXEC)); * … */ if (ret < 0) return negative_errno(); return ret; } static inline int errno_or_else(int fallback) { /* To be used when invoking library calls where errno handling is not defined clearly: we return * errno if it is set, and the specified error otherwise. The idea is that the caller initializes * errno to zero before doing an API call, and then uses this helper to retrieve a somewhat useful * error code */ if (errno > 0) return -errno; return -abs(fallback); } /* For send()/recv() or read()/write(). */ static inline bool ERRNO_IS_TRANSIENT(int r) { return IN_SET(abs(r), EAGAIN, EINTR); } /* Hint #1: ENETUNREACH happens if we try to connect to "non-existing" special IP addresses, such as ::5. * * Hint #2: The kernel sends e.g., EHOSTUNREACH or ENONET to userspace in some ICMP error cases. See the * icmp_err_convert[] in net/ipv4/icmp.c in the kernel sources. * * Hint #3: When asynchronous connect() on TCP fails because the host never acknowledges a single packet, * kernel tells us that with ETIMEDOUT, see tcp(7). */ static inline bool ERRNO_IS_DISCONNECT(int r) { return IN_SET(abs(r), ECONNABORTED, ECONNREFUSED, ECONNRESET, EHOSTDOWN, EHOSTUNREACH, ENETDOWN, ENETRESET, ENETUNREACH, ENONET, ENOPROTOOPT, ENOTCONN, EPIPE, EPROTO, ESHUTDOWN, ETIMEDOUT); } /* Transient errors we might get on accept() that we should ignore. As per error handling comment in * the accept(2) man page. */ static inline bool ERRNO_IS_ACCEPT_AGAIN(int r) { return ERRNO_IS_DISCONNECT(r) || ERRNO_IS_TRANSIENT(r) || abs(r) == EOPNOTSUPP; } /* Resource exhaustion, could be our fault or general system trouble */ static inline bool ERRNO_IS_RESOURCE(int r) { return IN_SET(abs(r), EMFILE, ENFILE, ENOMEM); } /* Seven different errors for "operation/system call/ioctl/socket feature not supported" */ static inline bool ERRNO_IS_NOT_SUPPORTED(int r) { return IN_SET(abs(r), EOPNOTSUPP, ENOTTY, ENOSYS, EAFNOSUPPORT, EPFNOSUPPORT, EPROTONOSUPPORT, ESOCKTNOSUPPORT); } /* Two different errors for access problems */ static inline bool ERRNO_IS_PRIVILEGE(int r) { return IN_SET(abs(r), EACCES, EPERM); } /* Three different errors for "not enough disk space" */ static inline bool ERRNO_IS_DISK_SPACE(int r) { return IN_SET(abs(r), ENOSPC, EDQUOT, EFBIG); } /* Three different errors for "this device does not quite exist" */ static inline bool ERRNO_IS_DEVICE_ABSENT(int r) { return IN_SET(abs(r), ENODEV, ENXIO, ENOENT); } /* Quite often we want to handle cases where the backing FS doesn't support extended attributes at all and * where it simply doesn't have the requested xattr the same way */ static inline bool ERRNO_IS_XATTR_ABSENT(int r) { return abs(r) == ENODATA || ERRNO_IS_NOT_SUPPORTED(r); }
6,202
34.045198
108
h
null
systemd-main/src/basic/escape.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stdlib.h> #include <string.h> #include "alloc-util.h" #include "escape.h" #include "hexdecoct.h" #include "macro.h" #include "strv.h" #include "utf8.h" int cescape_char(char c, char *buf) { char *buf_old = buf; /* Needs space for 4 characters in the buffer */ switch (c) { case '\a': *(buf++) = '\\'; *(buf++) = 'a'; break; case '\b': *(buf++) = '\\'; *(buf++) = 'b'; break; case '\f': *(buf++) = '\\'; *(buf++) = 'f'; break; case '\n': *(buf++) = '\\'; *(buf++) = 'n'; break; case '\r': *(buf++) = '\\'; *(buf++) = 'r'; break; case '\t': *(buf++) = '\\'; *(buf++) = 't'; break; case '\v': *(buf++) = '\\'; *(buf++) = 'v'; break; case '\\': *(buf++) = '\\'; *(buf++) = '\\'; break; case '"': *(buf++) = '\\'; *(buf++) = '"'; break; case '\'': *(buf++) = '\\'; *(buf++) = '\''; break; default: /* For special chars we prefer octal over * hexadecimal encoding, simply because glib's * g_strescape() does the same */ if ((c < ' ') || (c >= 127)) { *(buf++) = '\\'; *(buf++) = octchar((unsigned char) c >> 6); *(buf++) = octchar((unsigned char) c >> 3); *(buf++) = octchar((unsigned char) c); } else *(buf++) = c; break; } return buf - buf_old; } char* cescape_length(const char *s, size_t n) { const char *f; char *r, *t; assert(s || n == 0); /* Does C style string escaping. May be reversed with * cunescape(). */ r = new(char, n*4 + 1); if (!r) return NULL; for (f = s, t = r; f < s + n; f++) t += cescape_char(*f, t); *t = 0; return r; } char* cescape(const char *s) { assert(s); return cescape_length(s, strlen(s)); } int cunescape_one(const char *p, size_t length, char32_t *ret, bool *eight_bit, bool accept_nul) { int r = 1; assert(p); assert(ret); /* Unescapes C style. Returns the unescaped character in ret. * Sets *eight_bit to true if the escaped sequence either fits in * one byte in UTF-8 or is a non-unicode literal byte and should * instead be copied directly. */ if (length != SIZE_MAX && length < 1) return -EINVAL; switch (p[0]) { case 'a': *ret = '\a'; break; case 'b': *ret = '\b'; break; case 'f': *ret = '\f'; break; case 'n': *ret = '\n'; break; case 'r': *ret = '\r'; break; case 't': *ret = '\t'; break; case 'v': *ret = '\v'; break; case '\\': *ret = '\\'; break; case '"': *ret = '"'; break; case '\'': *ret = '\''; break; case 's': /* This is an extension of the XDG syntax files */ *ret = ' '; break; case 'x': { /* hexadecimal encoding */ int a, b; if (length != SIZE_MAX && length < 3) return -EINVAL; a = unhexchar(p[1]); if (a < 0) return -EINVAL; b = unhexchar(p[2]); if (b < 0) return -EINVAL; /* Don't allow NUL bytes */ if (a == 0 && b == 0 && !accept_nul) return -EINVAL; *ret = (a << 4U) | b; *eight_bit = true; r = 3; break; } case 'u': { /* C++11 style 16-bit unicode */ int a[4]; size_t i; uint32_t c; if (length != SIZE_MAX && length < 5) return -EINVAL; for (i = 0; i < 4; i++) { a[i] = unhexchar(p[1 + i]); if (a[i] < 0) return a[i]; } c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3]; /* Don't allow 0 chars */ if (c == 0 && !accept_nul) return -EINVAL; *ret = c; r = 5; break; } case 'U': { /* C++11 style 32-bit unicode */ int a[8]; size_t i; char32_t c; if (length != SIZE_MAX && length < 9) return -EINVAL; for (i = 0; i < 8; i++) { a[i] = unhexchar(p[1 + i]); if (a[i] < 0) return a[i]; } c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) | ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7]; /* Don't allow 0 chars */ if (c == 0 && !accept_nul) return -EINVAL; /* Don't allow invalid code points */ if (!unichar_is_valid(c)) return -EINVAL; *ret = c; r = 9; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { /* octal encoding */ int a, b, c; char32_t m; if (length != SIZE_MAX && length < 3) return -EINVAL; a = unoctchar(p[0]); if (a < 0) return -EINVAL; b = unoctchar(p[1]); if (b < 0) return -EINVAL; c = unoctchar(p[2]); if (c < 0) return -EINVAL; /* don't allow NUL bytes */ if (a == 0 && b == 0 && c == 0 && !accept_nul) return -EINVAL; /* Don't allow bytes above 255 */ m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c; if (m > 255) return -EINVAL; *ret = m; *eight_bit = true; r = 3; break; } default: return -EINVAL; } return r; } ssize_t cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) { _cleanup_free_ char *ans = NULL; char *t; const char *f; size_t pl; int r; assert(s); assert(ret); /* Undoes C style string escaping, and optionally prefixes it. */ pl = strlen_ptr(prefix); ans = new(char, pl+length+1); if (!ans) return -ENOMEM; if (prefix) memcpy(ans, prefix, pl); for (f = s, t = ans + pl; f < s + length; f++) { size_t remaining; bool eight_bit = false; char32_t u; remaining = s + length - f; assert(remaining > 0); if (*f != '\\') { /* A literal, copy verbatim */ *(t++) = *f; continue; } if (remaining == 1) { if (flags & UNESCAPE_RELAX) { /* A trailing backslash, copy verbatim */ *(t++) = *f; continue; } return -EINVAL; } r = cunescape_one(f + 1, remaining - 1, &u, &eight_bit, flags & UNESCAPE_ACCEPT_NUL); if (r < 0) { if (flags & UNESCAPE_RELAX) { /* Invalid escape code, let's take it literal then */ *(t++) = '\\'; continue; } return r; } f += r; if (eight_bit) /* One byte? Set directly as specified */ *(t++) = u; else /* Otherwise encode as multi-byte UTF-8 */ t += utf8_encode_unichar(t, u); } *t = 0; assert(t >= ans); /* Let static analyzers know that the answer is non-negative. */ *ret = TAKE_PTR(ans); return t - *ret; } char* xescape_full(const char *s, const char *bad, size_t console_width, XEscapeFlags flags) { char *ans, *t, *prev, *prev2; const char *f; /* Escapes all chars in bad, in addition to \ and all special chars, in \xFF style escaping. May be * reversed with cunescape(). If XESCAPE_8_BIT is specified, characters >= 127 are let through * unchanged. This corresponds to non-ASCII printable characters in pre-unicode encodings. * * If console_width is reached, or XESCAPE_FORCE_ELLIPSIS is set, output is truncated and "..." is * appended. */ if (console_width == 0) return strdup(""); ans = new(char, MIN(strlen(s), console_width) * 4 + 1); if (!ans) return NULL; memset(ans, '_', MIN(strlen(s), console_width) * 4); ans[MIN(strlen(s), console_width) * 4] = 0; bool force_ellipsis = FLAGS_SET(flags, XESCAPE_FORCE_ELLIPSIS); for (f = s, t = prev = prev2 = ans; ; f++) { char *tmp_t = t; if (!*f) { if (force_ellipsis) break; *t = 0; return ans; } if ((unsigned char) *f < ' ' || (!FLAGS_SET(flags, XESCAPE_8_BIT) && (unsigned char) *f >= 127) || *f == '\\' || strchr(bad, *f)) { if ((size_t) (t - ans) + 4 + 3 * force_ellipsis > console_width) break; *(t++) = '\\'; *(t++) = 'x'; *(t++) = hexchar(*f >> 4); *(t++) = hexchar(*f); } else { if ((size_t) (t - ans) + 1 + 3 * force_ellipsis > console_width) break; *(t++) = *f; } /* We might need to go back two cycles to fit three dots, so remember two positions */ prev2 = prev; prev = tmp_t; } /* We can just write where we want, since chars are one-byte */ size_t c = MIN(console_width, 3u); /* If the console is too narrow, write fewer dots */ size_t off; if (console_width - c >= (size_t) (t - ans)) off = (size_t) (t - ans); else if (console_width - c >= (size_t) (prev - ans)) off = (size_t) (prev - ans); else if (console_width - c >= (size_t) (prev2 - ans)) off = (size_t) (prev2 - ans); else off = console_width - c; assert(off <= (size_t) (t - ans)); memcpy(ans + off, "...", c); ans[off + c] = '\0'; return ans; } char* escape_non_printable_full(const char *str, size_t console_width, XEscapeFlags flags) { if (FLAGS_SET(flags, XESCAPE_8_BIT)) return xescape_full(str, "", console_width, flags); else return utf8_escape_non_printable_full(str, console_width, FLAGS_SET(flags, XESCAPE_FORCE_ELLIPSIS)); } char* octescape(const char *s, size_t len) { char *buf, *t; /* Escapes all chars in bad, in addition to \ and " chars, in \nnn style escaping. */ assert(s || len == 0); t = buf = new(char, len * 4 + 1); if (!buf) return NULL; for (size_t i = 0; i < len; i++) { uint8_t u = (uint8_t) s[i]; if (u < ' ' || u >= 127 || IN_SET(u, '\\', '"')) { *(t++) = '\\'; *(t++) = '0' + (u >> 6); *(t++) = '0' + ((u >> 3) & 7); *(t++) = '0' + (u & 7); } else *(t++) = u; } *t = 0; return buf; } static char* strcpy_backslash_escaped(char *t, const char *s, const char *bad) { assert(bad); assert(t); assert(s); while (*s) { int l = utf8_encoded_valid_unichar(s, SIZE_MAX); if (char_is_cc(*s) || l < 0) t += cescape_char(*(s++), t); else if (l == 1) { if (*s == '\\' || strchr(bad, *s)) *(t++) = '\\'; *(t++) = *(s++); } else { t = mempcpy(t, s, l); s += l; } } return t; } char* shell_escape(const char *s, const char *bad) { char *buf, *t; buf = new(char, strlen(s)*4+1); if (!buf) return NULL; t = strcpy_backslash_escaped(buf, s, bad); *t = 0; return buf; } char* shell_maybe_quote(const char *s, ShellEscapeFlags flags) { const char *p; char *buf, *t; assert(s); /* Encloses a string in quotes if necessary to make it OK as a shell string. */ if (FLAGS_SET(flags, SHELL_ESCAPE_EMPTY) && isempty(s)) return strdup("\"\""); /* We don't use $'' here in the POSIX mode. "" is fine too. */ for (p = s; *p; ) { int l = utf8_encoded_valid_unichar(p, SIZE_MAX); if (char_is_cc(*p) || l < 0 || strchr(WHITESPACE SHELL_NEED_QUOTES, *p)) break; p += l; } if (!*p) return strdup(s); buf = new(char, FLAGS_SET(flags, SHELL_ESCAPE_POSIX) + 1 + strlen(s)*4 + 1 + 1); if (!buf) return NULL; t = buf; if (FLAGS_SET(flags, SHELL_ESCAPE_POSIX)) { *(t++) = '$'; *(t++) = '\''; } else *(t++) = '"'; t = mempcpy(t, s, p - s); t = strcpy_backslash_escaped(t, p, FLAGS_SET(flags, SHELL_ESCAPE_POSIX) ? SHELL_NEED_ESCAPE_POSIX : SHELL_NEED_ESCAPE); if (FLAGS_SET(flags, SHELL_ESCAPE_POSIX)) *(t++) = '\''; else *(t++) = '"'; *t = 0; return str_realloc(buf); } char* quote_command_line(char **argv, ShellEscapeFlags flags) { _cleanup_free_ char *result = NULL; assert(argv); STRV_FOREACH(a, argv) { _cleanup_free_ char *t = NULL; t = shell_maybe_quote(*a, flags); if (!t) return NULL; if (!strextend_with_separator(&result, " ", t)) return NULL; } return str_realloc(TAKE_PTR(result)); }
17,054
28.558059
127
c
null
systemd-main/src/basic/escape.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include <stddef.h> #include <stdint.h> #include <sys/types.h> #include <uchar.h> #include "string-util.h" #include "missing_type.h" /* What characters are special in the shell? */ /* must be escaped outside and inside double-quotes */ #define SHELL_NEED_ESCAPE "\"\\`$" /* Those that can be escaped or double-quoted. * * Strictly speaking, ! does not need to be escaped, except in interactive * mode, but let's be extra nice to the user and quote ! in case this * output is ever used in interactive mode. */ #define SHELL_NEED_QUOTES SHELL_NEED_ESCAPE GLOB_CHARS "'()<>|&;!" /* Note that we assume control characters would need to be escaped too in * addition to the "special" characters listed here, if they appear in the * string. Current users disallow control characters. Also '"' shall not * be escaped. */ #define SHELL_NEED_ESCAPE_POSIX "\\\'" typedef enum UnescapeFlags { UNESCAPE_RELAX = 1 << 0, UNESCAPE_ACCEPT_NUL = 1 << 1, } UnescapeFlags; typedef enum ShellEscapeFlags { /* The default is to add shell quotes ("") so the shell will consider this a single argument. * Tabs and newlines are escaped. */ SHELL_ESCAPE_POSIX = 1 << 1, /* Use POSIX shell escape syntax (a string enclosed in $'') instead of plain quotes. */ SHELL_ESCAPE_EMPTY = 1 << 2, /* Format empty arguments as "". */ } ShellEscapeFlags; char* cescape(const char *s); char* cescape_length(const char *s, size_t n); int cescape_char(char c, char *buf); int cunescape_one(const char *p, size_t length, char32_t *ret, bool *eight_bit, bool accept_nul); ssize_t cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret); static inline ssize_t cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) { return cunescape_length_with_prefix(s, length, NULL, flags, ret); } static inline ssize_t cunescape(const char *s, UnescapeFlags flags, char **ret) { return cunescape_length(s, strlen(s), flags, ret); } typedef enum XEscapeFlags { XESCAPE_8_BIT = 1 << 0, XESCAPE_FORCE_ELLIPSIS = 1 << 1, } XEscapeFlags; char* xescape_full(const char *s, const char *bad, size_t console_width, XEscapeFlags flags); static inline char* xescape(const char *s, const char *bad) { return xescape_full(s, bad, SIZE_MAX, 0); } char* octescape(const char *s, size_t len); char* escape_non_printable_full(const char *str, size_t console_width, XEscapeFlags flags); char* shell_escape(const char *s, const char *bad); char* shell_maybe_quote(const char *s, ShellEscapeFlags flags); char* quote_command_line(char **argv, ShellEscapeFlags flags);
2,782
37.123288
124
h
null
systemd-main/src/basic/ether-addr-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <inttypes.h> #include <net/ethernet.h> #include <stdio.h> #include <sys/types.h> #include "ether-addr-util.h" #include "hexdecoct.h" #include "macro.h" #include "string-util.h" char *hw_addr_to_string_full( const struct hw_addr_data *addr, HardwareAddressToStringFlags flags, char buffer[static HW_ADDR_TO_STRING_MAX]) { assert(addr); assert(buffer); assert(addr->length <= HW_ADDR_MAX_SIZE); for (size_t i = 0, j = 0; i < addr->length; i++) { buffer[j++] = hexchar(addr->bytes[i] >> 4); buffer[j++] = hexchar(addr->bytes[i] & 0x0f); if (!FLAGS_SET(flags, HW_ADDR_TO_STRING_NO_COLON)) buffer[j++] = ':'; } buffer[addr->length == 0 || FLAGS_SET(flags, HW_ADDR_TO_STRING_NO_COLON) ? addr->length * 2 : addr->length * 3 - 1] = '\0'; return buffer; } struct hw_addr_data *hw_addr_set(struct hw_addr_data *addr, const uint8_t *bytes, size_t length) { assert(addr); assert(length <= HW_ADDR_MAX_SIZE); addr->length = length; memcpy_safe(addr->bytes, bytes, length); return addr; } int hw_addr_compare(const struct hw_addr_data *a, const struct hw_addr_data *b) { int r; assert(a); assert(b); r = CMP(a->length, b->length); if (r != 0) return r; return memcmp(a->bytes, b->bytes, a->length); } void hw_addr_hash_func(const struct hw_addr_data *p, struct siphash *state) { assert(p); assert(state); siphash24_compress(&p->length, sizeof(p->length), state); siphash24_compress(p->bytes, p->length, state); } DEFINE_HASH_OPS(hw_addr_hash_ops, struct hw_addr_data, hw_addr_hash_func, hw_addr_compare); DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(hw_addr_hash_ops_free, struct hw_addr_data, hw_addr_hash_func, hw_addr_compare, free); char* ether_addr_to_string(const struct ether_addr *addr, char buffer[ETHER_ADDR_TO_STRING_MAX]) { assert(addr); assert(buffer); /* Like ether_ntoa() but uses %02x instead of %x to print * ethernet addresses, which makes them look less funny. Also, * doesn't use a static buffer. */ sprintf(buffer, "%02x:%02x:%02x:%02x:%02x:%02x", addr->ether_addr_octet[0], addr->ether_addr_octet[1], addr->ether_addr_octet[2], addr->ether_addr_octet[3], addr->ether_addr_octet[4], addr->ether_addr_octet[5]); return buffer; } int ether_addr_to_string_alloc(const struct ether_addr *addr, char **ret) { char *buf; assert(addr); assert(ret); buf = new(char, ETHER_ADDR_TO_STRING_MAX); if (!buf) return -ENOMEM; ether_addr_to_string(addr, buf); *ret = buf; return 0; } int ether_addr_compare(const struct ether_addr *a, const struct ether_addr *b) { return memcmp(a, b, ETH_ALEN); } static void ether_addr_hash_func(const struct ether_addr *p, struct siphash *state) { siphash24_compress(p, sizeof(struct ether_addr), state); } DEFINE_HASH_OPS(ether_addr_hash_ops, struct ether_addr, ether_addr_hash_func, ether_addr_compare); DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(ether_addr_hash_ops_free, struct ether_addr, ether_addr_hash_func, ether_addr_compare, free); static int parse_hw_addr_one_field(const char **s, char sep, size_t len, uint8_t *buf) { const char *hex = HEXDIGITS, *p; uint16_t data = 0; bool cont; assert(s); assert(*s); assert(IN_SET(len, 1, 2)); assert(buf); p = *s; for (size_t i = 0; i < len * 2; i++) { const char *hexoff; size_t x; if (*p == '\0' || *p == sep) { if (i == 0) return -EINVAL; break; } hexoff = strchr(hex, *p); if (!hexoff) return -EINVAL; assert(hexoff >= hex); x = hexoff - hex; if (x >= 16) x -= 6; /* A-F */ assert(x < 16); data <<= 4; data += x; p++; } if (*p != '\0' && *p != sep) return -EINVAL; switch (len) { case 1: buf[0] = data; break; case 2: buf[0] = (data & 0xff00) >> 8; buf[1] = data & 0xff; break; default: assert_not_reached(); } cont = *p == sep; *s = p + cont; return cont; } int parse_hw_addr_full(const char *s, size_t expected_len, struct hw_addr_data *ret) { size_t field_size, max_len, len = 0; uint8_t bytes[HW_ADDR_MAX_SIZE]; char sep; int r; assert(s); assert(expected_len <= HW_ADDR_MAX_SIZE || expected_len == SIZE_MAX); assert(ret); /* This accepts the following formats: * * Dot separated 2 bytes format: xxyy.zzaa.bbcc * Colon separated 1 bytes format: xx:yy:zz:aa:bb:cc * Hyphen separated 1 bytes format: xx-yy-zz-aa-bb-cc * * Moreover, if expected_len == 0, 4, or 16, this also accepts: * * IPv4 format: used by IPv4 tunnel, e.g. ipgre * IPv6 format: used by IPv6 tunnel, e.g. ip6gre * * The expected_len argument controls the length of acceptable addresses: * * 0: accepts 4 (AF_INET), 16 (AF_INET6), 6 (ETH_ALEN), or 20 (INFINIBAND_ALEN). * SIZE_MAX: accepts arbitrary length, but at least one separator must be included. * Otherwise: accepts addresses with matching length. */ if (IN_SET(expected_len, 0, sizeof(struct in_addr), sizeof(struct in6_addr))) { union in_addr_union a; int family; if (expected_len == 0) r = in_addr_from_string_auto(s, &family, &a); else { family = expected_len == sizeof(struct in_addr) ? AF_INET : AF_INET6; r = in_addr_from_string(family, s, &a); } if (r >= 0) { ret->length = FAMILY_ADDRESS_SIZE(family); memcpy(ret->bytes, a.bytes, ret->length); return 0; } } max_len = expected_len == 0 ? INFINIBAND_ALEN : expected_len == SIZE_MAX ? HW_ADDR_MAX_SIZE : expected_len; sep = s[strspn(s, HEXDIGITS)]; if (sep == '.') field_size = 2; else if (IN_SET(sep, ':', '-')) field_size = 1; else return -EINVAL; if (max_len % field_size != 0) return -EINVAL; for (size_t i = 0; i < max_len / field_size; i++) { r = parse_hw_addr_one_field(&s, sep, field_size, bytes + i * field_size); if (r < 0) return r; if (r == 0) { len = (i + 1) * field_size; break; } } if (len == 0) return -EINVAL; if (expected_len == 0) { if (!IN_SET(len, 4, 16, ETH_ALEN, INFINIBAND_ALEN)) return -EINVAL; } else if (expected_len != SIZE_MAX) { if (len != expected_len) return -EINVAL; } ret->length = len; memcpy(ret->bytes, bytes, ret->length); return 0; } int parse_ether_addr(const char *s, struct ether_addr *ret) { struct hw_addr_data a; int r; assert(s); assert(ret); r = parse_hw_addr_full(s, ETH_ALEN, &a); if (r < 0) return r; *ret = a.ether; return 0; }
8,262
29.267399
129
c