id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_486_4
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. CredSSP layer and Kerberos support. Copyright 2012-2017 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gssapi/gssapi.h> #include "rdesktop.h" extern RD_BOOL g_use_password_as_pin; extern char *g_sc_csp_name; extern char *g_sc_reader_name; extern char *g_sc_card_name; extern char *g_sc_container_name; static gss_OID_desc _gss_spnego_krb5_mechanism_oid_desc = { 9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" }; static STREAM ber_wrap_hdr_data(int tagval, STREAM in) { STREAM out; int size = s_length(in) + 16; out = xmalloc(sizeof(struct stream)); memset(out, 0, sizeof(struct stream)); out->data = xmalloc(size); out->size = size; out->p = out->data; ber_out_header(out, tagval, s_length(in)); out_uint8p(out, in->data, s_length(in)); s_mark_end(out); return out; } static void cssp_gss_report_error(OM_uint32 code, char *str, OM_uint32 major_status, OM_uint32 minor_status) { OM_uint32 msgctx = 0, ms; gss_buffer_desc status_string; logger(Core, Debug, "GSS error [%d:%d:%d]: %s", (major_status & 0xff000000) >> 24, // Calling error (major_status & 0xff0000) >> 16, // Routine error major_status & 0xffff, // Supplementary info bits str); do { ms = gss_display_status(&minor_status, major_status, code, GSS_C_NULL_OID, &msgctx, &status_string); if (ms != GSS_S_COMPLETE) continue; logger(Core, Debug, " - %s", status_string.value); } while (ms == GSS_S_COMPLETE && msgctx); } static RD_BOOL cssp_gss_mech_available(gss_OID mech) { int mech_found; OM_uint32 major_status, minor_status; gss_OID_set mech_set; mech_found = 0; if (mech == GSS_C_NO_OID) return True; major_status = gss_indicate_mechs(&minor_status, &mech_set); if (!mech_set) return False; if (GSS_ERROR(major_status)) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to get available mechs on system", major_status, minor_status); return False; } gss_test_oid_set_member(&minor_status, mech, mech_set, &mech_found); if (GSS_ERROR(major_status)) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to match mechanism in set", major_status, minor_status); return False; } if (!mech_found) return False; return True; } static RD_BOOL cssp_gss_get_service_name(char *server, gss_name_t * name) { gss_buffer_desc output; OM_uint32 major_status, minor_status; const char service_name[] = "TERMSRV"; gss_OID type = (gss_OID) GSS_C_NT_HOSTBASED_SERVICE; int size = (strlen(service_name) + 1 + strlen(server) + 1); output.value = malloc(size); snprintf(output.value, size, "%s@%s", service_name, server); output.length = strlen(output.value) + 1; major_status = gss_import_name(&minor_status, &output, type, name); if (GSS_ERROR(major_status)) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to create service principal name", major_status, minor_status); return False; } gss_release_buffer(&minor_status, &output); return True; } static RD_BOOL cssp_gss_wrap(gss_ctx_id_t ctx, STREAM in, STREAM out) { int conf_state; OM_uint32 major_status; OM_uint32 minor_status; gss_buffer_desc inbuf, outbuf; inbuf.value = in->data; inbuf.length = s_length(in); major_status = gss_wrap(&minor_status, ctx, True, GSS_C_QOP_DEFAULT, &inbuf, &conf_state, &outbuf); if (major_status != GSS_S_COMPLETE) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to encrypt and sign message", major_status, minor_status); return False; } if (!conf_state) { logger(Core, Error, "cssp_gss_wrap(), GSS Confidentiality failed, no encryption of message performed."); return False; } // write enc data to out stream out->data = out->p = xmalloc(outbuf.length); out->size = outbuf.length; out_uint8p(out, outbuf.value, outbuf.length); s_mark_end(out); gss_release_buffer(&minor_status, &outbuf); return True; } static RD_BOOL cssp_gss_unwrap(gss_ctx_id_t ctx, STREAM in, STREAM out) { OM_uint32 major_status; OM_uint32 minor_status; gss_qop_t qop_state; gss_buffer_desc inbuf, outbuf; int conf_state; inbuf.value = in->data; inbuf.length = s_length(in); major_status = gss_unwrap(&minor_status, ctx, &inbuf, &outbuf, &conf_state, &qop_state); if (major_status != GSS_S_COMPLETE) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to decrypt message", major_status, minor_status); return False; } out->data = out->p = xmalloc(outbuf.length); out->size = outbuf.length; out_uint8p(out, outbuf.value, outbuf.length); s_mark_end(out); gss_release_buffer(&minor_status, &outbuf); return True; } static STREAM cssp_encode_tspasswordcreds(char *username, char *password, char *domain) { STREAM out, h1, h2; struct stream tmp = { 0 }; struct stream message = { 0 }; memset(&tmp, 0, sizeof(tmp)); memset(&message, 0, sizeof(message)); s_realloc(&tmp, 512 * 4); // domainName [0] s_reset(&tmp); out_utf16s(&tmp, domain); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // userName [1] s_reset(&tmp); out_utf16s(&tmp, username); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // password [2] s_reset(&tmp); out_utf16s(&tmp, password); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // build message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup xfree(tmp.data); xfree(message.data); return out; } /* KeySpecs from wincrypt.h */ #define AT_KEYEXCHANGE 1 #define AT_SIGNATURE 2 static STREAM cssp_encode_tscspdatadetail(unsigned char keyspec, char *card, char *reader, char *container, char *csp) { STREAM out; STREAM h1, h2; struct stream tmp = { 0 }; struct stream message = { 0 }; s_realloc(&tmp, 512 * 4); // keySpec [0] s_reset(&tmp); out_uint8(&tmp, keyspec); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // cardName [1] if (card) { s_reset(&tmp); out_utf16s(&tmp, card); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // readerName [2] if (reader) { s_reset(&tmp); out_utf16s(&tmp, reader); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // containerName [3] if (container) { s_reset(&tmp); out_utf16s(&tmp, container); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // cspName [4] if (csp) { s_reset(&tmp); out_utf16s(&tmp, csp); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 4, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } s_mark_end(&message); // build message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup free(tmp.data); free(message.data); return out; } static STREAM cssp_encode_tssmartcardcreds(char *username, char *password, char *domain) { STREAM out, h1, h2; struct stream tmp = { 0 }; struct stream message = { 0 }; s_realloc(&tmp, 512 * 4); // pin [0] s_reset(&tmp); out_utf16s(&tmp, password); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // cspData [1] h2 = cssp_encode_tscspdatadetail(AT_KEYEXCHANGE, g_sc_card_name, g_sc_reader_name, g_sc_container_name, g_sc_csp_name); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // userHint [2] if (username && strlen(username)) { s_reset(&tmp); out_utf16s(&tmp, username); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // domainHint [3] if (domain && strlen(domain)) { s_reset(&tmp); out_utf16s(&tmp, domain); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } s_mark_end(&message); // build message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup free(tmp.data); free(message.data); return out; } STREAM cssp_encode_tscredentials(char *username, char *password, char *domain) { STREAM out; STREAM h1, h2, h3; struct stream tmp = { 0 }; struct stream message = { 0 }; // credType [0] s_realloc(&tmp, sizeof(uint8)); s_reset(&tmp); if (g_use_password_as_pin == False) { out_uint8(&tmp, 1); // TSPasswordCreds } else { out_uint8(&tmp, 2); // TSSmartCardCreds } s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // credentials [1] if (g_use_password_as_pin == False) { h3 = cssp_encode_tspasswordcreds(username, password, domain); } else { h3 = cssp_encode_tssmartcardcreds(username, password, domain); } h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, h3); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h3); s_free(h2); s_free(h1); // Construct ASN.1 message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup xfree(message.data); xfree(tmp.data); return out; } RD_BOOL cssp_send_tsrequest(STREAM token, STREAM auth, STREAM pubkey) { STREAM s; STREAM h1, h2, h3, h4, h5; struct stream tmp = { 0 }; struct stream message = { 0 }; memset(&message, 0, sizeof(message)); memset(&tmp, 0, sizeof(tmp)); // version [0] s_realloc(&tmp, sizeof(uint8)); s_reset(&tmp); out_uint8(&tmp, 2); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // negoToken [1] if (token && s_length(token)) { h5 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, token); h4 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h5); h3 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, h4); h2 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, h3); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h5); s_free(h4); s_free(h3); s_free(h2); s_free(h1); } // authInfo [2] if (auth && s_length(auth)) { h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, auth); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_free(h2); s_free(h1); } // pubKeyAuth [3] if (pubkey && s_length(pubkey)) { h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, pubkey); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } s_mark_end(&message); // Construct ASN.1 Message // Todo: can h1 be send directly instead of tcp_init() approach h1 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); s = tcp_init(s_length(h1)); out_uint8p(s, h1->data, s_length(h1)); s_mark_end(s); s_free(h1); tcp_send(s); // cleanup xfree(message.data); xfree(tmp.data); return True; } RD_BOOL cssp_read_tsrequest(STREAM token, STREAM pubkey) { STREAM s; int length; int tagval; struct stream packet; s = tcp_recv(NULL, 4); if (s == NULL) return False; // verify ASN.1 header if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) { logger(Protocol, Error, "cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x", s->p[0]); return False; } // peek at first 4 bytes to get full message length if (s->p[1] < 0x80) length = s->p[1] - 2; else if (s->p[1] == 0x81) length = s->p[2] - 1; else if (s->p[1] == 0x82) length = (s->p[2] << 8) | s->p[3]; else return False; // receive the remainings of message s = tcp_recv(s, length); packet = *s; // parse the response and into nego token if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; // version [0] if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!s_check_rem(s, length)) { rdp_protocol_error("cssp_read_tsrequest(), consume of version from stream would overrun", &packet); } in_uint8s(s, length); // negoToken [1] if (token) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; if (!s_check_rem(s, length)) { rdp_protocol_error("cssp_read_tsrequest(), consume of token from stream would overrun", &packet); } s_realloc(token, length); s_reset(token); out_uint8p(token, s->p, length); s_mark_end(token); } // pubKey [3] if (pubkey) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; pubkey->data = pubkey->p = s->p; pubkey->end = pubkey->data + length; pubkey->size = length; } return True; } RD_BOOL cssp_connect(char *server, char *user, char *domain, char *password, STREAM s) { UNUSED(s); OM_uint32 actual_time; gss_cred_id_t cred; gss_buffer_desc input_tok, output_tok; gss_name_t target_name; OM_uint32 major_status, minor_status; int context_established = 0; gss_ctx_id_t gss_ctx; gss_OID desired_mech = &_gss_spnego_krb5_mechanism_oid_desc; STREAM ts_creds; struct stream token = { 0 }; struct stream pubkey = { 0 }; struct stream pubkey_cmp = { 0 }; // Verify that system gss support spnego if (!cssp_gss_mech_available(desired_mech)) { logger(Core, Debug, "cssp_connect(), system doesn't have support for desired authentication mechanism"); return False; } // Get service name if (!cssp_gss_get_service_name(server, &target_name)) { logger(Core, Debug, "cssp_connect(), failed to get target service name"); return False; } // Establish TLS connection to server if (!tcp_tls_connect()) { logger(Core, Debug, "cssp_connect(), failed to establish TLS connection"); return False; } tcp_tls_get_server_pubkey(&pubkey); // Enter the spnego loop OM_uint32 actual_services; gss_OID actual_mech; struct stream blob = { 0 }; gss_ctx = GSS_C_NO_CONTEXT; cred = GSS_C_NO_CREDENTIAL; input_tok.length = 0; output_tok.length = 0; minor_status = 0; int i = 0; do { major_status = gss_init_sec_context(&minor_status, cred, &gss_ctx, target_name, desired_mech, GSS_C_MUTUAL_FLAG | GSS_C_DELEG_FLAG, GSS_C_INDEFINITE, GSS_C_NO_CHANNEL_BINDINGS, &input_tok, &actual_mech, &output_tok, &actual_services, &actual_time); if (GSS_ERROR(major_status)) { if (i == 0) logger(Core, Notice, "Failed to initialize NLA, do you have correct Kerberos TGT initialized ?"); else logger(Core, Error, "cssp_connect(), negotiation failed"); cssp_gss_report_error(GSS_C_GSS_CODE, "cssp_connect(), negotiation failed.", major_status, minor_status); goto bail_out; } // validate required services if (!(actual_services & GSS_C_CONF_FLAG)) { logger(Core, Error, "cssp_connect(), confidentiality service required but is not available"); goto bail_out; } // Send token to server if (output_tok.length != 0) { if (output_tok.length > token.size) s_realloc(&token, output_tok.length); s_reset(&token); out_uint8p(&token, output_tok.value, output_tok.length); s_mark_end(&token); if (!cssp_send_tsrequest(&token, NULL, NULL)) goto bail_out; (void) gss_release_buffer(&minor_status, &output_tok); } // Read token from server if (major_status & GSS_S_CONTINUE_NEEDED) { (void) gss_release_buffer(&minor_status, &input_tok); if (!cssp_read_tsrequest(&token, NULL)) goto bail_out; input_tok.value = token.data; input_tok.length = s_length(&token); } else { // Send encrypted pubkey for verification to server context_established = 1; if (!cssp_gss_wrap(gss_ctx, &pubkey, &blob)) goto bail_out; if (!cssp_send_tsrequest(NULL, NULL, &blob)) goto bail_out; context_established = 1; } i++; } while (!context_established); // read tsrequest response and decrypt for public key validation if (!cssp_read_tsrequest(NULL, &blob)) goto bail_out; if (!cssp_gss_unwrap(gss_ctx, &blob, &pubkey_cmp)) goto bail_out; pubkey_cmp.data[0] -= 1; // validate public key if (memcmp(pubkey.data, pubkey_cmp.data, s_length(&pubkey)) != 0) { logger(Core, Error, "cssp_connect(), public key mismatch, cannot guarantee integrity of server connection"); goto bail_out; } // Send TSCredentials ts_creds = cssp_encode_tscredentials(user, password, domain); if (!cssp_gss_wrap(gss_ctx, ts_creds, &blob)) goto bail_out; s_free(ts_creds); if (!cssp_send_tsrequest(NULL, &blob, NULL)) goto bail_out; return True; bail_out: xfree(token.data); return False; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_486_4
crossvul-cpp_data_good_3952_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Drawing Orders * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "window.h" #include <winpr/wtypes.h> #include <winpr/crt.h> #include <freerdp/api.h> #include <freerdp/log.h> #include <freerdp/graphics.h> #include <freerdp/codec/bitmap.h> #include <freerdp/gdi/gdi.h> #include "orders.h" #include "../cache/glyph.h" #include "../cache/bitmap.h" #include "../cache/brush.h" #include "../cache/cache.h" #define TAG FREERDP_TAG("core.orders") BYTE get_primary_drawing_order_field_bytes(UINT32 orderType, BOOL* pValid) { if (pValid) *pValid = TRUE; switch (orderType) { case 0: return DSTBLT_ORDER_FIELD_BYTES; case 1: return PATBLT_ORDER_FIELD_BYTES; case 2: return SCRBLT_ORDER_FIELD_BYTES; case 3: return 0; case 4: return 0; case 5: return 0; case 6: return 0; case 7: return DRAW_NINE_GRID_ORDER_FIELD_BYTES; case 8: return MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES; case 9: return LINE_TO_ORDER_FIELD_BYTES; case 10: return OPAQUE_RECT_ORDER_FIELD_BYTES; case 11: return SAVE_BITMAP_ORDER_FIELD_BYTES; case 12: return 0; case 13: return MEMBLT_ORDER_FIELD_BYTES; case 14: return MEM3BLT_ORDER_FIELD_BYTES; case 15: return MULTI_DSTBLT_ORDER_FIELD_BYTES; case 16: return MULTI_PATBLT_ORDER_FIELD_BYTES; case 17: return MULTI_SCRBLT_ORDER_FIELD_BYTES; case 18: return MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES; case 19: return FAST_INDEX_ORDER_FIELD_BYTES; case 20: return POLYGON_SC_ORDER_FIELD_BYTES; case 21: return POLYGON_CB_ORDER_FIELD_BYTES; case 22: return POLYLINE_ORDER_FIELD_BYTES; case 23: return 0; case 24: return FAST_GLYPH_ORDER_FIELD_BYTES; case 25: return ELLIPSE_SC_ORDER_FIELD_BYTES; case 26: return ELLIPSE_CB_ORDER_FIELD_BYTES; case 27: return GLYPH_INDEX_ORDER_FIELD_BYTES; default: if (pValid) *pValid = FALSE; WLog_WARN(TAG, "Invalid orderType 0x%08X received", orderType); return 0; } } static BYTE get_cbr2_bpp(UINT32 bpp, BOOL* pValid) { if (pValid) *pValid = TRUE; switch (bpp) { case 3: return 8; case 4: return 16; case 5: return 24; case 6: return 32; default: WLog_WARN(TAG, "Invalid bpp %" PRIu32, bpp); if (pValid) *pValid = FALSE; return 0; } } static BYTE get_bmf_bpp(UINT32 bmf, BOOL* pValid) { if (pValid) *pValid = TRUE; switch (bmf) { case 1: return 1; case 3: return 8; case 4: return 16; case 5: return 24; case 6: return 32; default: WLog_WARN(TAG, "Invalid bmf %" PRIu32, bmf); if (pValid) *pValid = FALSE; return 0; } } static BYTE get_bpp_bmf(UINT32 bpp, BOOL* pValid) { if (pValid) *pValid = TRUE; switch (bpp) { case 1: return 1; case 8: return 3; case 16: return 4; case 24: return 5; case 32: return 6; default: WLog_WARN(TAG, "Invalid color depth %" PRIu32, bpp); if (pValid) *pValid = FALSE; return 0; } } static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName, BOOL condition) { if (!condition) { if (settings->AllowUnanouncedOrdersFromServer) { WLog_Print(log, WLOG_WARN, "%s - SERVER BUG: The support for this feature was not announced!", orderName); return TRUE; } else { WLog_Print(log, WLOG_ERROR, "%s - SERVER BUG: The support for this feature was not announced! Use " "/relax-order-checks to ignore", orderName); return FALSE; } } return TRUE; } static BOOL check_alt_order_supported(wLog* log, rdpSettings* settings, BYTE orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: case ORDER_TYPE_SWITCH_SURFACE: condition = settings->OffscreenSupportLevel != 0; break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: condition = settings->DrawNineGridEnabled; break; case ORDER_TYPE_FRAME_MARKER: condition = settings->FrameMarkerCommandEnabled; break; case ORDER_TYPE_GDIPLUS_FIRST: case ORDER_TYPE_GDIPLUS_NEXT: case ORDER_TYPE_GDIPLUS_END: case ORDER_TYPE_GDIPLUS_CACHE_FIRST: case ORDER_TYPE_GDIPLUS_CACHE_NEXT: case ORDER_TYPE_GDIPLUS_CACHE_END: condition = settings->DrawGdiPlusCacheEnabled; break; case ORDER_TYPE_WINDOW: condition = settings->RemoteWndSupportLevel != WINDOW_LEVEL_NOT_SUPPORTED; break; case ORDER_TYPE_STREAM_BITMAP_FIRST: case ORDER_TYPE_STREAM_BITMAP_NEXT: case ORDER_TYPE_COMPDESK_FIRST: condition = TRUE; break; default: WLog_Print(log, WLOG_WARN, "%s - Alternate Secondary Drawing Order UNKNOWN", orderName); condition = FALSE; break; } return check_order_activated(log, settings, orderName, condition); } static BOOL check_secondary_order_supported(wLog* log, rdpSettings* settings, BYTE orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: condition = settings->BitmapCacheEnabled; break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: condition = settings->BitmapCacheEnabled; break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: condition = settings->BitmapCacheV3Enabled; break; case ORDER_TYPE_CACHE_COLOR_TABLE: condition = (settings->OrderSupport[NEG_MEMBLT_INDEX] || settings->OrderSupport[NEG_MEM3BLT_INDEX]); break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: case GLYPH_SUPPORT_ENCODE: condition = TRUE; break; case GLYPH_SUPPORT_NONE: default: condition = FALSE; break; } } break; case ORDER_TYPE_CACHE_BRUSH: condition = TRUE; break; default: WLog_Print(log, WLOG_WARN, "SECONDARY ORDER %s not supported", orderName); break; } return check_order_activated(log, settings, orderName, condition); } static BOOL check_primary_order_supported(wLog* log, rdpSettings* settings, UINT32 orderType, const char* orderName) { BOOL condition = FALSE; switch (orderType) { case ORDER_TYPE_DSTBLT: condition = settings->OrderSupport[NEG_DSTBLT_INDEX]; break; case ORDER_TYPE_SCRBLT: condition = settings->OrderSupport[NEG_SCRBLT_INDEX]; break; case ORDER_TYPE_DRAW_NINE_GRID: condition = settings->OrderSupport[NEG_DRAWNINEGRID_INDEX]; break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: condition = settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX]; break; case ORDER_TYPE_LINE_TO: condition = settings->OrderSupport[NEG_LINETO_INDEX]; break; /* [MS-RDPEGDI] 2.2.2.2.1.1.2.5 OpaqueRect (OPAQUERECT_ORDER) * suggests that PatBlt and OpaqueRect imply each other. */ case ORDER_TYPE_PATBLT: case ORDER_TYPE_OPAQUE_RECT: condition = settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] || settings->OrderSupport[NEG_PATBLT_INDEX]; break; case ORDER_TYPE_SAVE_BITMAP: condition = settings->OrderSupport[NEG_SAVEBITMAP_INDEX]; break; case ORDER_TYPE_MEMBLT: condition = settings->OrderSupport[NEG_MEMBLT_INDEX]; break; case ORDER_TYPE_MEM3BLT: condition = settings->OrderSupport[NEG_MEM3BLT_INDEX]; break; case ORDER_TYPE_MULTI_DSTBLT: condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX]; break; case ORDER_TYPE_MULTI_PATBLT: condition = settings->OrderSupport[NEG_MULTIPATBLT_INDEX]; break; case ORDER_TYPE_MULTI_SCRBLT: condition = settings->OrderSupport[NEG_MULTIDSTBLT_INDEX]; break; case ORDER_TYPE_MULTI_OPAQUE_RECT: condition = settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX]; break; case ORDER_TYPE_FAST_INDEX: condition = settings->OrderSupport[NEG_FAST_INDEX_INDEX]; break; case ORDER_TYPE_POLYGON_SC: condition = settings->OrderSupport[NEG_POLYGON_SC_INDEX]; break; case ORDER_TYPE_POLYGON_CB: condition = settings->OrderSupport[NEG_POLYGON_CB_INDEX]; break; case ORDER_TYPE_POLYLINE: condition = settings->OrderSupport[NEG_POLYLINE_INDEX]; break; case ORDER_TYPE_FAST_GLYPH: condition = settings->OrderSupport[NEG_FAST_GLYPH_INDEX]; break; case ORDER_TYPE_ELLIPSE_SC: condition = settings->OrderSupport[NEG_ELLIPSE_SC_INDEX]; break; case ORDER_TYPE_ELLIPSE_CB: condition = settings->OrderSupport[NEG_ELLIPSE_CB_INDEX]; break; case ORDER_TYPE_GLYPH_INDEX: condition = settings->OrderSupport[NEG_GLYPH_INDEX_INDEX]; break; default: WLog_Print(log, WLOG_WARN, "%s Primary Drawing Order not supported", orderName); break; } return check_order_activated(log, settings, orderName, condition); } static const char* primary_order_string(UINT32 orderType) { const char* orders[] = { "[0x%02" PRIx8 "] DstBlt", "[0x%02" PRIx8 "] PatBlt", "[0x%02" PRIx8 "] ScrBlt", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] DrawNineGrid", "[0x%02" PRIx8 "] MultiDrawNineGrid", "[0x%02" PRIx8 "] LineTo", "[0x%02" PRIx8 "] OpaqueRect", "[0x%02" PRIx8 "] SaveBitmap", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] MemBlt", "[0x%02" PRIx8 "] Mem3Blt", "[0x%02" PRIx8 "] MultiDstBlt", "[0x%02" PRIx8 "] MultiPatBlt", "[0x%02" PRIx8 "] MultiScrBlt", "[0x%02" PRIx8 "] MultiOpaqueRect", "[0x%02" PRIx8 "] FastIndex", "[0x%02" PRIx8 "] PolygonSC", "[0x%02" PRIx8 "] PolygonCB", "[0x%02" PRIx8 "] Polyline", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] FastGlyph", "[0x%02" PRIx8 "] EllipseSC", "[0x%02" PRIx8 "] EllipseCB", "[0x%02" PRIx8 "] GlyphIndex" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static const char* secondary_order_string(UINT32 orderType) { const char* orders[] = { "[0x%02" PRIx8 "] Cache Bitmap", "[0x%02" PRIx8 "] Cache Color Table", "[0x%02" PRIx8 "] Cache Bitmap (Compressed)", "[0x%02" PRIx8 "] Cache Glyph", "[0x%02" PRIx8 "] Cache Bitmap V2", "[0x%02" PRIx8 "] Cache Bitmap V2 (Compressed)", "[0x%02" PRIx8 "] UNUSED", "[0x%02" PRIx8 "] Cache Brush", "[0x%02" PRIx8 "] Cache Bitmap V3" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static const char* altsec_order_string(BYTE orderType) { const char* orders[] = { "[0x%02" PRIx8 "] Switch Surface", "[0x%02" PRIx8 "] Create Offscreen Bitmap", "[0x%02" PRIx8 "] Stream Bitmap First", "[0x%02" PRIx8 "] Stream Bitmap Next", "[0x%02" PRIx8 "] Create NineGrid Bitmap", "[0x%02" PRIx8 "] Draw GDI+ First", "[0x%02" PRIx8 "] Draw GDI+ Next", "[0x%02" PRIx8 "] Draw GDI+ End", "[0x%02" PRIx8 "] Draw GDI+ Cache First", "[0x%02" PRIx8 "] Draw GDI+ Cache Next", "[0x%02" PRIx8 "] Draw GDI+ Cache End", "[0x%02" PRIx8 "] Windowing", "[0x%02" PRIx8 "] Desktop Composition", "[0x%02" PRIx8 "] Frame Marker" }; const char* fmt = "[0x%02" PRIx8 "] UNKNOWN"; static char buffer[64] = { 0 }; if (orderType < ARRAYSIZE(orders)) fmt = orders[orderType]; sprintf_s(buffer, ARRAYSIZE(buffer), fmt, orderType); return buffer; } static INLINE BOOL update_read_coord(wStream* s, INT32* coord, BOOL delta) { INT8 lsi8; INT16 lsi16; if (delta) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_INT8(s, lsi8); *coord += lsi8; } else { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_INT16(s, lsi16); *coord = lsi16; } return TRUE; } static INLINE BOOL update_write_coord(wStream* s, INT32 coord) { Stream_Write_UINT16(s, coord); return TRUE; } static INLINE BOOL update_read_color(wStream* s, UINT32* color) { BYTE byte; if (Stream_GetRemainingLength(s) < 3) return FALSE; *color = 0; Stream_Read_UINT8(s, byte); *color = (UINT32)byte; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 8) & 0xFF00; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 16) & 0xFF0000; return TRUE; } static INLINE BOOL update_write_color(wStream* s, UINT32 color) { BYTE byte; byte = (color & 0xFF); Stream_Write_UINT8(s, byte); byte = ((color >> 8) & 0xFF); Stream_Write_UINT8(s, byte); byte = ((color >> 16) & 0xFF); Stream_Write_UINT8(s, byte); return TRUE; } static INLINE BOOL update_read_colorref(wStream* s, UINT32* color) { BYTE byte; if (Stream_GetRemainingLength(s) < 4) return FALSE; *color = 0; Stream_Read_UINT8(s, byte); *color = byte; Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 8); Stream_Read_UINT8(s, byte); *color |= ((UINT32)byte << 16); Stream_Seek_UINT8(s); return TRUE; } static INLINE BOOL update_read_color_quad(wStream* s, UINT32* color) { return update_read_colorref(s, color); } static INLINE void update_write_color_quad(wStream* s, UINT32 color) { BYTE byte; byte = (color >> 16) & 0xFF; Stream_Write_UINT8(s, byte); byte = (color >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = color & 0xFF; Stream_Write_UINT8(s, byte); } static INLINE BOOL update_read_2byte_unsigned(wStream* s, UINT32* value) { BYTE byte; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) return FALSE; *value = (byte & 0x7F) << 8; Stream_Read_UINT8(s, byte); *value |= byte; } else { *value = (byte & 0x7F); } return TRUE; } static INLINE BOOL update_write_2byte_unsigned(wStream* s, UINT32 value) { BYTE byte; if (value > 0x7FFF) return FALSE; if (value >= 0x7F) { byte = ((value & 0x7F00) >> 8); Stream_Write_UINT8(s, byte | 0x80); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else { byte = (value & 0x7F); Stream_Write_UINT8(s, byte); } return TRUE; } static INLINE BOOL update_read_2byte_signed(wStream* s, INT32* value) { BYTE byte; BOOL negative; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); negative = (byte & 0x40) ? TRUE : FALSE; *value = (byte & 0x3F); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); *value = (*value << 8) | byte; } if (negative) *value *= -1; return TRUE; } static INLINE BOOL update_write_2byte_signed(wStream* s, INT32 value) { BYTE byte; BOOL negative = FALSE; if (value < 0) { negative = TRUE; value *= -1; } if (value > 0x3FFF) return FALSE; if (value >= 0x3F) { byte = ((value & 0x3F00) >> 8); if (negative) byte |= 0x40; Stream_Write_UINT8(s, byte | 0x80); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else { byte = (value & 0x3F); if (negative) byte |= 0x40; Stream_Write_UINT8(s, byte); } return TRUE; } static INLINE BOOL update_read_4byte_unsigned(wStream* s, UINT32* value) { BYTE byte; BYTE count; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); count = (byte & 0xC0) >> 6; if (Stream_GetRemainingLength(s) < count) return FALSE; switch (count) { case 0: *value = (byte & 0x3F); break; case 1: *value = (byte & 0x3F) << 8; Stream_Read_UINT8(s, byte); *value |= byte; break; case 2: *value = (byte & 0x3F) << 16; Stream_Read_UINT8(s, byte); *value |= (byte << 8); Stream_Read_UINT8(s, byte); *value |= byte; break; case 3: *value = (byte & 0x3F) << 24; Stream_Read_UINT8(s, byte); *value |= (byte << 16); Stream_Read_UINT8(s, byte); *value |= (byte << 8); Stream_Read_UINT8(s, byte); *value |= byte; break; default: break; } return TRUE; } static INLINE BOOL update_write_4byte_unsigned(wStream* s, UINT32 value) { BYTE byte; if (value <= 0x3F) { Stream_Write_UINT8(s, value); } else if (value <= 0x3FFF) { byte = (value >> 8) & 0x3F; Stream_Write_UINT8(s, byte | 0x40); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else if (value <= 0x3FFFFF) { byte = (value >> 16) & 0x3F; Stream_Write_UINT8(s, byte | 0x80); byte = (value >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else if (value <= 0x3FFFFFFF) { byte = (value >> 24) & 0x3F; Stream_Write_UINT8(s, byte | 0xC0); byte = (value >> 16) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (value & 0xFF); Stream_Write_UINT8(s, byte); } else return FALSE; return TRUE; } static INLINE BOOL update_read_delta(wStream* s, INT32* value) { BYTE byte; if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, byte); if (byte & 0x40) *value = (byte | ~0x3F); else *value = (byte & 0x3F); if (byte & 0x80) { if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, byte); *value = (*value << 8) | byte; } return TRUE; } #if 0 static INLINE void update_read_glyph_delta(wStream* s, UINT16* value) { BYTE byte; Stream_Read_UINT8(s, byte); if (byte == 0x80) Stream_Read_UINT16(s, *value); else *value = (byte & 0x3F); } static INLINE void update_seek_glyph_delta(wStream* s) { BYTE byte; Stream_Read_UINT8(s, byte); if (byte & 0x80) Stream_Seek_UINT8(s); } #endif static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) { if (fieldFlags & ORDER_FIELD_01) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->x); } if (fieldFlags & ORDER_FIELD_02) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->y); } if (fieldFlags & ORDER_FIELD_03) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->style); } if (fieldFlags & ORDER_FIELD_04) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, brush->hatch); } if (brush->style & CACHED_BRUSH) { BOOL rc; brush->index = brush->hatch; brush->bpp = get_bmf_bpp(brush->style, &rc); if (!rc) return FALSE; if (brush->bpp == 0) brush->bpp = 1; } if (fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 7) return FALSE; brush->data = (BYTE*)brush->p8x8; Stream_Read_UINT8(s, brush->data[7]); Stream_Read_UINT8(s, brush->data[6]); Stream_Read_UINT8(s, brush->data[5]); Stream_Read_UINT8(s, brush->data[4]); Stream_Read_UINT8(s, brush->data[3]); Stream_Read_UINT8(s, brush->data[2]); Stream_Read_UINT8(s, brush->data[1]); brush->data[0] = brush->hatch; } return TRUE; } static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) { if (fieldFlags & ORDER_FIELD_01) { Stream_Write_UINT8(s, brush->x); } if (fieldFlags & ORDER_FIELD_02) { Stream_Write_UINT8(s, brush->y); } if (fieldFlags & ORDER_FIELD_03) { Stream_Write_UINT8(s, brush->style); } if (brush->style & CACHED_BRUSH) { BOOL rc; brush->hatch = brush->index; brush->bpp = get_bmf_bpp(brush->style, &rc); if (!rc) return FALSE; if (brush->bpp == 0) brush->bpp = 1; } if (fieldFlags & ORDER_FIELD_04) { Stream_Write_UINT8(s, brush->hatch); } if (fieldFlags & ORDER_FIELD_05) { brush->data = (BYTE*)brush->p8x8; Stream_Write_UINT8(s, brush->data[7]); Stream_Write_UINT8(s, brush->data[6]); Stream_Write_UINT8(s, brush->data[5]); Stream_Write_UINT8(s, brush->data[4]); Stream_Write_UINT8(s, brush->data[3]); Stream_Write_UINT8(s, brush->data[2]); Stream_Write_UINT8(s, brush->data[1]); brush->data[0] = brush->hatch; } return TRUE; } static INLINE BOOL update_read_delta_rects(wStream* s, DELTA_RECT* rectangles, UINT32* nr) { UINT32 number = *nr; UINT32 i; BYTE flags = 0; BYTE* zeroBits; UINT32 zeroBitsSize; if (number > 45) { WLog_WARN(TAG, "Invalid number of delta rectangles %" PRIu32, number); return FALSE; } zeroBitsSize = ((number + 1) / 2); if (Stream_GetRemainingLength(s) < zeroBitsSize) return FALSE; Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); ZeroMemory(rectangles, sizeof(DELTA_RECT) * number); for (i = 0; i < number; i++) { if (i % 2 == 0) flags = zeroBits[i / 2]; if ((~flags & 0x80) && !update_read_delta(s, &rectangles[i].left)) return FALSE; if ((~flags & 0x40) && !update_read_delta(s, &rectangles[i].top)) return FALSE; if (~flags & 0x20) { if (!update_read_delta(s, &rectangles[i].width)) return FALSE; } else if (i > 0) rectangles[i].width = rectangles[i - 1].width; else rectangles[i].width = 0; if (~flags & 0x10) { if (!update_read_delta(s, &rectangles[i].height)) return FALSE; } else if (i > 0) rectangles[i].height = rectangles[i - 1].height; else rectangles[i].height = 0; if (i > 0) { rectangles[i].left += rectangles[i - 1].left; rectangles[i].top += rectangles[i - 1].top; } flags <<= 4; } return TRUE; } static INLINE BOOL update_read_delta_points(wStream* s, DELTA_POINT* points, int number, INT16 x, INT16 y) { int i; BYTE flags = 0; BYTE* zeroBits; UINT32 zeroBitsSize; zeroBitsSize = ((number + 3) / 4); if (Stream_GetRemainingLength(s) < zeroBitsSize) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < %" PRIu32 "", zeroBitsSize); return FALSE; } Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); ZeroMemory(points, sizeof(DELTA_POINT) * number); for (i = 0; i < number; i++) { if (i % 4 == 0) flags = zeroBits[i / 4]; if ((~flags & 0x80) && !update_read_delta(s, &points[i].x)) { WLog_ERR(TAG, "update_read_delta(x) failed"); return FALSE; } if ((~flags & 0x40) && !update_read_delta(s, &points[i].y)) { WLog_ERR(TAG, "update_read_delta(y) failed"); return FALSE; } flags <<= 2; } return TRUE; } #define ORDER_FIELD_BYTE(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 1) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT8(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_2BYTE(NO, TARGET1, TARGET2) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 2) \ { \ WLog_ERR(TAG, "error reading %s or %s", #TARGET1, #TARGET2); \ return FALSE; \ } \ Stream_Read_UINT8(s, TARGET1); \ Stream_Read_UINT8(s, TARGET2); \ } \ } while (0) #define ORDER_FIELD_UINT16(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 2) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT16(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_UINT32(NO, TARGET) \ do \ { \ if (orderInfo->fieldFlags & (1 << (NO - 1))) \ { \ if (Stream_GetRemainingLength(s) < 4) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ Stream_Read_UINT32(s, TARGET); \ } \ } while (0) #define ORDER_FIELD_COORD(NO, TARGET) \ do \ { \ if ((orderInfo->fieldFlags & (1 << (NO - 1))) && \ !update_read_coord(s, &TARGET, orderInfo->deltaCoordinates)) \ { \ WLog_ERR(TAG, "error reading %s", #TARGET); \ return FALSE; \ } \ } while (0) static INLINE BOOL ORDER_FIELD_COLOR(const ORDER_INFO* orderInfo, wStream* s, UINT32 NO, UINT32* TARGET) { if (!TARGET || !orderInfo) return FALSE; if ((orderInfo->fieldFlags & (1 << (NO - 1))) && !update_read_color(s, TARGET)) return FALSE; return TRUE; } static INLINE BOOL FIELD_SKIP_BUFFER16(wStream* s, UINT32 TARGET_LEN) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, TARGET_LEN); if (!Stream_SafeSeek(s, TARGET_LEN)) { WLog_ERR(TAG, "error skipping %" PRIu32 " bytes", TARGET_LEN); return FALSE; } return TRUE; } /* Primary Drawing Orders */ static BOOL update_read_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, DSTBLT_ORDER* dstblt) { ORDER_FIELD_COORD(1, dstblt->nLeftRect); ORDER_FIELD_COORD(2, dstblt->nTopRect); ORDER_FIELD_COORD(3, dstblt->nWidth); ORDER_FIELD_COORD(4, dstblt->nHeight); ORDER_FIELD_BYTE(5, dstblt->bRop); return TRUE; } int update_approximate_dstblt_order(ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt) { return 32; } BOOL update_write_dstblt_order(wStream* s, ORDER_INFO* orderInfo, const DSTBLT_ORDER* dstblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_dstblt_order(orderInfo, dstblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, dstblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, dstblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, dstblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, dstblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, dstblt->bRop); return TRUE; } static BOOL update_read_patblt_order(wStream* s, const ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { ORDER_FIELD_COORD(1, patblt->nLeftRect); ORDER_FIELD_COORD(2, patblt->nTopRect); ORDER_FIELD_COORD(3, patblt->nWidth); ORDER_FIELD_COORD(4, patblt->nHeight); ORDER_FIELD_BYTE(5, patblt->bRop); ORDER_FIELD_COLOR(orderInfo, s, 6, &patblt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 7, &patblt->foreColor); return update_read_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7); } int update_approximate_patblt_order(ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { return 32; } BOOL update_write_patblt_order(wStream* s, ORDER_INFO* orderInfo, PATBLT_ORDER* patblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_patblt_order(orderInfo, patblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, patblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, patblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, patblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, patblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, patblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, patblt->backColor); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_color(s, patblt->foreColor); orderInfo->fieldFlags |= ORDER_FIELD_08; orderInfo->fieldFlags |= ORDER_FIELD_09; orderInfo->fieldFlags |= ORDER_FIELD_10; orderInfo->fieldFlags |= ORDER_FIELD_11; orderInfo->fieldFlags |= ORDER_FIELD_12; update_write_brush(s, &patblt->brush, orderInfo->fieldFlags >> 7); return TRUE; } static BOOL update_read_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, SCRBLT_ORDER* scrblt) { ORDER_FIELD_COORD(1, scrblt->nLeftRect); ORDER_FIELD_COORD(2, scrblt->nTopRect); ORDER_FIELD_COORD(3, scrblt->nWidth); ORDER_FIELD_COORD(4, scrblt->nHeight); ORDER_FIELD_BYTE(5, scrblt->bRop); ORDER_FIELD_COORD(6, scrblt->nXSrc); ORDER_FIELD_COORD(7, scrblt->nYSrc); return TRUE; } int update_approximate_scrblt_order(ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt) { return 32; } BOOL update_write_scrblt_order(wStream* s, ORDER_INFO* orderInfo, const SCRBLT_ORDER* scrblt) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_scrblt_order(orderInfo, scrblt))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, scrblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, scrblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, scrblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, scrblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; Stream_Write_UINT8(s, scrblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_coord(s, scrblt->nXSrc); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_coord(s, scrblt->nYSrc); return TRUE; } static BOOL update_read_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo, OPAQUE_RECT_ORDER* opaque_rect) { BYTE byte; ORDER_FIELD_COORD(1, opaque_rect->nLeftRect); ORDER_FIELD_COORD(2, opaque_rect->nTopRect); ORDER_FIELD_COORD(3, opaque_rect->nWidth); ORDER_FIELD_COORD(4, opaque_rect->nHeight); if (orderInfo->fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x00FFFF00) | ((UINT32)byte); } if (orderInfo->fieldFlags & ORDER_FIELD_06) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8); } if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); opaque_rect->color = (opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16); } return TRUE; } int update_approximate_opaque_rect_order(ORDER_INFO* orderInfo, const OPAQUE_RECT_ORDER* opaque_rect) { return 32; } BOOL update_write_opaque_rect_order(wStream* s, ORDER_INFO* orderInfo, const OPAQUE_RECT_ORDER* opaque_rect) { BYTE byte; int inf = update_approximate_opaque_rect_order(orderInfo, opaque_rect); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; // TODO: Color format conversion orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; update_write_coord(s, opaque_rect->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, opaque_rect->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, opaque_rect->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, opaque_rect->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_05; byte = opaque_rect->color & 0x000000FF; Stream_Write_UINT8(s, byte); orderInfo->fieldFlags |= ORDER_FIELD_06; byte = (opaque_rect->color & 0x0000FF00) >> 8; Stream_Write_UINT8(s, byte); orderInfo->fieldFlags |= ORDER_FIELD_07; byte = (opaque_rect->color & 0x00FF0000) >> 16; Stream_Write_UINT8(s, byte); return TRUE; } static BOOL update_read_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo, DRAW_NINE_GRID_ORDER* draw_nine_grid) { ORDER_FIELD_COORD(1, draw_nine_grid->srcLeft); ORDER_FIELD_COORD(2, draw_nine_grid->srcTop); ORDER_FIELD_COORD(3, draw_nine_grid->srcRight); ORDER_FIELD_COORD(4, draw_nine_grid->srcBottom); ORDER_FIELD_UINT16(5, draw_nine_grid->bitmapId); return TRUE; } static BOOL update_read_multi_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_DSTBLT_ORDER* multi_dstblt) { ORDER_FIELD_COORD(1, multi_dstblt->nLeftRect); ORDER_FIELD_COORD(2, multi_dstblt->nTopRect); ORDER_FIELD_COORD(3, multi_dstblt->nWidth); ORDER_FIELD_COORD(4, multi_dstblt->nHeight); ORDER_FIELD_BYTE(5, multi_dstblt->bRop); ORDER_FIELD_BYTE(6, multi_dstblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_dstblt->cbData); return update_read_delta_rects(s, multi_dstblt->rectangles, &multi_dstblt->numRectangles); } return TRUE; } static BOOL update_read_multi_patblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_PATBLT_ORDER* multi_patblt) { ORDER_FIELD_COORD(1, multi_patblt->nLeftRect); ORDER_FIELD_COORD(2, multi_patblt->nTopRect); ORDER_FIELD_COORD(3, multi_patblt->nWidth); ORDER_FIELD_COORD(4, multi_patblt->nHeight); ORDER_FIELD_BYTE(5, multi_patblt->bRop); ORDER_FIELD_COLOR(orderInfo, s, 6, &multi_patblt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 7, &multi_patblt->foreColor); if (!update_read_brush(s, &multi_patblt->brush, orderInfo->fieldFlags >> 7)) return FALSE; ORDER_FIELD_BYTE(13, multi_patblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_14) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_patblt->cbData); if (!update_read_delta_rects(s, multi_patblt->rectangles, &multi_patblt->numRectangles)) return FALSE; } return TRUE; } static BOOL update_read_multi_scrblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_SCRBLT_ORDER* multi_scrblt) { ORDER_FIELD_COORD(1, multi_scrblt->nLeftRect); ORDER_FIELD_COORD(2, multi_scrblt->nTopRect); ORDER_FIELD_COORD(3, multi_scrblt->nWidth); ORDER_FIELD_COORD(4, multi_scrblt->nHeight); ORDER_FIELD_BYTE(5, multi_scrblt->bRop); ORDER_FIELD_COORD(6, multi_scrblt->nXSrc); ORDER_FIELD_COORD(7, multi_scrblt->nYSrc); ORDER_FIELD_BYTE(8, multi_scrblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_09) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_scrblt->cbData); return update_read_delta_rects(s, multi_scrblt->rectangles, &multi_scrblt->numRectangles); } return TRUE; } static BOOL update_read_multi_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect) { BYTE byte; ORDER_FIELD_COORD(1, multi_opaque_rect->nLeftRect); ORDER_FIELD_COORD(2, multi_opaque_rect->nTopRect); ORDER_FIELD_COORD(3, multi_opaque_rect->nWidth); ORDER_FIELD_COORD(4, multi_opaque_rect->nHeight); if (orderInfo->fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FFFF00) | ((UINT32)byte); } if (orderInfo->fieldFlags & ORDER_FIELD_06) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8); } if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16); } ORDER_FIELD_BYTE(8, multi_opaque_rect->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_09) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_opaque_rect->cbData); return update_read_delta_rects(s, multi_opaque_rect->rectangles, &multi_opaque_rect->numRectangles); } return TRUE; } static BOOL update_read_multi_draw_nine_grid_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_DRAW_NINE_GRID_ORDER* multi_draw_nine_grid) { ORDER_FIELD_COORD(1, multi_draw_nine_grid->srcLeft); ORDER_FIELD_COORD(2, multi_draw_nine_grid->srcTop); ORDER_FIELD_COORD(3, multi_draw_nine_grid->srcRight); ORDER_FIELD_COORD(4, multi_draw_nine_grid->srcBottom); ORDER_FIELD_UINT16(5, multi_draw_nine_grid->bitmapId); ORDER_FIELD_BYTE(6, multi_draw_nine_grid->nDeltaEntries); if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_draw_nine_grid->cbData); return update_read_delta_rects(s, multi_draw_nine_grid->rectangles, &multi_draw_nine_grid->nDeltaEntries); } return TRUE; } static BOOL update_read_line_to_order(wStream* s, const ORDER_INFO* orderInfo, LINE_TO_ORDER* line_to) { ORDER_FIELD_UINT16(1, line_to->backMode); ORDER_FIELD_COORD(2, line_to->nXStart); ORDER_FIELD_COORD(3, line_to->nYStart); ORDER_FIELD_COORD(4, line_to->nXEnd); ORDER_FIELD_COORD(5, line_to->nYEnd); ORDER_FIELD_COLOR(orderInfo, s, 6, &line_to->backColor); ORDER_FIELD_BYTE(7, line_to->bRop2); ORDER_FIELD_BYTE(8, line_to->penStyle); ORDER_FIELD_BYTE(9, line_to->penWidth); ORDER_FIELD_COLOR(orderInfo, s, 10, &line_to->penColor); return TRUE; } int update_approximate_line_to_order(ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to) { return 32; } BOOL update_write_line_to_order(wStream* s, ORDER_INFO* orderInfo, const LINE_TO_ORDER* line_to) { if (!Stream_EnsureRemainingCapacity(s, update_approximate_line_to_order(orderInfo, line_to))) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT16(s, line_to->backMode); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, line_to->nXStart); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, line_to->nYStart); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, line_to->nXEnd); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_coord(s, line_to->nYEnd); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, line_to->backColor); orderInfo->fieldFlags |= ORDER_FIELD_07; Stream_Write_UINT8(s, line_to->bRop2); orderInfo->fieldFlags |= ORDER_FIELD_08; Stream_Write_UINT8(s, line_to->penStyle); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT8(s, line_to->penWidth); orderInfo->fieldFlags |= ORDER_FIELD_10; update_write_color(s, line_to->penColor); return TRUE; } static BOOL update_read_polyline_order(wStream* s, const ORDER_INFO* orderInfo, POLYLINE_ORDER* polyline) { UINT16 word; UINT32 new_num = polyline->numDeltaEntries; ORDER_FIELD_COORD(1, polyline->xStart); ORDER_FIELD_COORD(2, polyline->yStart); ORDER_FIELD_BYTE(3, polyline->bRop2); ORDER_FIELD_UINT16(4, word); ORDER_FIELD_COLOR(orderInfo, s, 5, &polyline->penColor); ORDER_FIELD_BYTE(6, new_num); if (orderInfo->fieldFlags & ORDER_FIELD_07) { DELTA_POINT* new_points; if (new_num == 0) return FALSE; if (Stream_GetRemainingLength(s) < 1) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, polyline->cbData); new_points = (DELTA_POINT*)realloc(polyline->points, sizeof(DELTA_POINT) * new_num); if (!new_points) { WLog_ERR(TAG, "realloc(%" PRIu32 ") failed", new_num); return FALSE; } polyline->points = new_points; polyline->numDeltaEntries = new_num; return update_read_delta_points(s, polyline->points, polyline->numDeltaEntries, polyline->xStart, polyline->yStart); } return TRUE; } static BOOL update_read_memblt_order(wStream* s, const ORDER_INFO* orderInfo, MEMBLT_ORDER* memblt) { if (!s || !orderInfo || !memblt) return FALSE; ORDER_FIELD_UINT16(1, memblt->cacheId); ORDER_FIELD_COORD(2, memblt->nLeftRect); ORDER_FIELD_COORD(3, memblt->nTopRect); ORDER_FIELD_COORD(4, memblt->nWidth); ORDER_FIELD_COORD(5, memblt->nHeight); ORDER_FIELD_BYTE(6, memblt->bRop); ORDER_FIELD_COORD(7, memblt->nXSrc); ORDER_FIELD_COORD(8, memblt->nYSrc); ORDER_FIELD_UINT16(9, memblt->cacheIndex); memblt->colorIndex = (memblt->cacheId >> 8); memblt->cacheId = (memblt->cacheId & 0xFF); memblt->bitmap = NULL; return TRUE; } int update_approximate_memblt_order(ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt) { return 64; } BOOL update_write_memblt_order(wStream* s, ORDER_INFO* orderInfo, const MEMBLT_ORDER* memblt) { UINT16 cacheId; if (!Stream_EnsureRemainingCapacity(s, update_approximate_memblt_order(orderInfo, memblt))) return FALSE; cacheId = (memblt->cacheId & 0xFF) | ((memblt->colorIndex & 0xFF) << 8); orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT16(s, cacheId); orderInfo->fieldFlags |= ORDER_FIELD_02; update_write_coord(s, memblt->nLeftRect); orderInfo->fieldFlags |= ORDER_FIELD_03; update_write_coord(s, memblt->nTopRect); orderInfo->fieldFlags |= ORDER_FIELD_04; update_write_coord(s, memblt->nWidth); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_coord(s, memblt->nHeight); orderInfo->fieldFlags |= ORDER_FIELD_06; Stream_Write_UINT8(s, memblt->bRop); orderInfo->fieldFlags |= ORDER_FIELD_07; update_write_coord(s, memblt->nXSrc); orderInfo->fieldFlags |= ORDER_FIELD_08; update_write_coord(s, memblt->nYSrc); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT16(s, memblt->cacheIndex); return TRUE; } static BOOL update_read_mem3blt_order(wStream* s, const ORDER_INFO* orderInfo, MEM3BLT_ORDER* mem3blt) { ORDER_FIELD_UINT16(1, mem3blt->cacheId); ORDER_FIELD_COORD(2, mem3blt->nLeftRect); ORDER_FIELD_COORD(3, mem3blt->nTopRect); ORDER_FIELD_COORD(4, mem3blt->nWidth); ORDER_FIELD_COORD(5, mem3blt->nHeight); ORDER_FIELD_BYTE(6, mem3blt->bRop); ORDER_FIELD_COORD(7, mem3blt->nXSrc); ORDER_FIELD_COORD(8, mem3blt->nYSrc); ORDER_FIELD_COLOR(orderInfo, s, 9, &mem3blt->backColor); ORDER_FIELD_COLOR(orderInfo, s, 10, &mem3blt->foreColor); if (!update_read_brush(s, &mem3blt->brush, orderInfo->fieldFlags >> 10)) return FALSE; ORDER_FIELD_UINT16(16, mem3blt->cacheIndex); mem3blt->colorIndex = (mem3blt->cacheId >> 8); mem3blt->cacheId = (mem3blt->cacheId & 0xFF); mem3blt->bitmap = NULL; return TRUE; } static BOOL update_read_save_bitmap_order(wStream* s, const ORDER_INFO* orderInfo, SAVE_BITMAP_ORDER* save_bitmap) { ORDER_FIELD_UINT32(1, save_bitmap->savedBitmapPosition); ORDER_FIELD_COORD(2, save_bitmap->nLeftRect); ORDER_FIELD_COORD(3, save_bitmap->nTopRect); ORDER_FIELD_COORD(4, save_bitmap->nRightRect); ORDER_FIELD_COORD(5, save_bitmap->nBottomRect); ORDER_FIELD_BYTE(6, save_bitmap->operation); return TRUE; } static BOOL update_read_glyph_index_order(wStream* s, const ORDER_INFO* orderInfo, GLYPH_INDEX_ORDER* glyph_index) { ORDER_FIELD_BYTE(1, glyph_index->cacheId); ORDER_FIELD_BYTE(2, glyph_index->flAccel); ORDER_FIELD_BYTE(3, glyph_index->ulCharInc); ORDER_FIELD_BYTE(4, glyph_index->fOpRedundant); ORDER_FIELD_COLOR(orderInfo, s, 5, &glyph_index->backColor); ORDER_FIELD_COLOR(orderInfo, s, 6, &glyph_index->foreColor); ORDER_FIELD_UINT16(7, glyph_index->bkLeft); ORDER_FIELD_UINT16(8, glyph_index->bkTop); ORDER_FIELD_UINT16(9, glyph_index->bkRight); ORDER_FIELD_UINT16(10, glyph_index->bkBottom); ORDER_FIELD_UINT16(11, glyph_index->opLeft); ORDER_FIELD_UINT16(12, glyph_index->opTop); ORDER_FIELD_UINT16(13, glyph_index->opRight); ORDER_FIELD_UINT16(14, glyph_index->opBottom); if (!update_read_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14)) return FALSE; ORDER_FIELD_UINT16(20, glyph_index->x); ORDER_FIELD_UINT16(21, glyph_index->y); if (orderInfo->fieldFlags & ORDER_FIELD_22) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, glyph_index->cbData); if (Stream_GetRemainingLength(s) < glyph_index->cbData) return FALSE; CopyMemory(glyph_index->data, Stream_Pointer(s), glyph_index->cbData); Stream_Seek(s, glyph_index->cbData); } return TRUE; } int update_approximate_glyph_index_order(ORDER_INFO* orderInfo, const GLYPH_INDEX_ORDER* glyph_index) { return 64; } BOOL update_write_glyph_index_order(wStream* s, ORDER_INFO* orderInfo, GLYPH_INDEX_ORDER* glyph_index) { int inf = update_approximate_glyph_index_order(orderInfo, glyph_index); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; orderInfo->fieldFlags = 0; orderInfo->fieldFlags |= ORDER_FIELD_01; Stream_Write_UINT8(s, glyph_index->cacheId); orderInfo->fieldFlags |= ORDER_FIELD_02; Stream_Write_UINT8(s, glyph_index->flAccel); orderInfo->fieldFlags |= ORDER_FIELD_03; Stream_Write_UINT8(s, glyph_index->ulCharInc); orderInfo->fieldFlags |= ORDER_FIELD_04; Stream_Write_UINT8(s, glyph_index->fOpRedundant); orderInfo->fieldFlags |= ORDER_FIELD_05; update_write_color(s, glyph_index->backColor); orderInfo->fieldFlags |= ORDER_FIELD_06; update_write_color(s, glyph_index->foreColor); orderInfo->fieldFlags |= ORDER_FIELD_07; Stream_Write_UINT16(s, glyph_index->bkLeft); orderInfo->fieldFlags |= ORDER_FIELD_08; Stream_Write_UINT16(s, glyph_index->bkTop); orderInfo->fieldFlags |= ORDER_FIELD_09; Stream_Write_UINT16(s, glyph_index->bkRight); orderInfo->fieldFlags |= ORDER_FIELD_10; Stream_Write_UINT16(s, glyph_index->bkBottom); orderInfo->fieldFlags |= ORDER_FIELD_11; Stream_Write_UINT16(s, glyph_index->opLeft); orderInfo->fieldFlags |= ORDER_FIELD_12; Stream_Write_UINT16(s, glyph_index->opTop); orderInfo->fieldFlags |= ORDER_FIELD_13; Stream_Write_UINT16(s, glyph_index->opRight); orderInfo->fieldFlags |= ORDER_FIELD_14; Stream_Write_UINT16(s, glyph_index->opBottom); orderInfo->fieldFlags |= ORDER_FIELD_15; orderInfo->fieldFlags |= ORDER_FIELD_16; orderInfo->fieldFlags |= ORDER_FIELD_17; orderInfo->fieldFlags |= ORDER_FIELD_18; orderInfo->fieldFlags |= ORDER_FIELD_19; update_write_brush(s, &glyph_index->brush, orderInfo->fieldFlags >> 14); orderInfo->fieldFlags |= ORDER_FIELD_20; Stream_Write_UINT16(s, glyph_index->x); orderInfo->fieldFlags |= ORDER_FIELD_21; Stream_Write_UINT16(s, glyph_index->y); orderInfo->fieldFlags |= ORDER_FIELD_22; Stream_Write_UINT8(s, glyph_index->cbData); Stream_Write(s, glyph_index->data, glyph_index->cbData); return TRUE; } static BOOL update_read_fast_index_order(wStream* s, const ORDER_INFO* orderInfo, FAST_INDEX_ORDER* fast_index) { ORDER_FIELD_BYTE(1, fast_index->cacheId); ORDER_FIELD_2BYTE(2, fast_index->ulCharInc, fast_index->flAccel); ORDER_FIELD_COLOR(orderInfo, s, 3, &fast_index->backColor); ORDER_FIELD_COLOR(orderInfo, s, 4, &fast_index->foreColor); ORDER_FIELD_COORD(5, fast_index->bkLeft); ORDER_FIELD_COORD(6, fast_index->bkTop); ORDER_FIELD_COORD(7, fast_index->bkRight); ORDER_FIELD_COORD(8, fast_index->bkBottom); ORDER_FIELD_COORD(9, fast_index->opLeft); ORDER_FIELD_COORD(10, fast_index->opTop); ORDER_FIELD_COORD(11, fast_index->opRight); ORDER_FIELD_COORD(12, fast_index->opBottom); ORDER_FIELD_COORD(13, fast_index->x); ORDER_FIELD_COORD(14, fast_index->y); if (orderInfo->fieldFlags & ORDER_FIELD_15) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, fast_index->cbData); if (Stream_GetRemainingLength(s) < fast_index->cbData) return FALSE; CopyMemory(fast_index->data, Stream_Pointer(s), fast_index->cbData); Stream_Seek(s, fast_index->cbData); } return TRUE; } static BOOL update_read_fast_glyph_order(wStream* s, const ORDER_INFO* orderInfo, FAST_GLYPH_ORDER* fastGlyph) { GLYPH_DATA_V2* glyph = &fastGlyph->glyphData; ORDER_FIELD_BYTE(1, fastGlyph->cacheId); ORDER_FIELD_2BYTE(2, fastGlyph->ulCharInc, fastGlyph->flAccel); ORDER_FIELD_COLOR(orderInfo, s, 3, &fastGlyph->backColor); ORDER_FIELD_COLOR(orderInfo, s, 4, &fastGlyph->foreColor); ORDER_FIELD_COORD(5, fastGlyph->bkLeft); ORDER_FIELD_COORD(6, fastGlyph->bkTop); ORDER_FIELD_COORD(7, fastGlyph->bkRight); ORDER_FIELD_COORD(8, fastGlyph->bkBottom); ORDER_FIELD_COORD(9, fastGlyph->opLeft); ORDER_FIELD_COORD(10, fastGlyph->opTop); ORDER_FIELD_COORD(11, fastGlyph->opRight); ORDER_FIELD_COORD(12, fastGlyph->opBottom); ORDER_FIELD_COORD(13, fastGlyph->x); ORDER_FIELD_COORD(14, fastGlyph->y); if (orderInfo->fieldFlags & ORDER_FIELD_15) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, fastGlyph->cbData); if (Stream_GetRemainingLength(s) < fastGlyph->cbData) return FALSE; CopyMemory(fastGlyph->data, Stream_Pointer(s), fastGlyph->cbData); if (Stream_GetRemainingLength(s) < fastGlyph->cbData) return FALSE; if (!Stream_SafeSeek(s, 1)) return FALSE; if (fastGlyph->cbData > 1) { UINT32 new_cb; /* parse optional glyph data */ glyph->cacheIndex = fastGlyph->data[0]; if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) || !update_read_2byte_unsigned(s, &glyph->cx) || !update_read_2byte_unsigned(s, &glyph->cy)) return FALSE; glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; new_cb = ((glyph->cx + 7) / 8) * glyph->cy; new_cb += ((new_cb % 4) > 0) ? 4 - (new_cb % 4) : 0; if (fastGlyph->cbData < new_cb) return FALSE; if (new_cb > 0) { BYTE* new_aj; new_aj = (BYTE*)realloc(glyph->aj, new_cb); if (!new_aj) return FALSE; glyph->aj = new_aj; glyph->cb = new_cb; Stream_Read(s, glyph->aj, glyph->cb); } Stream_Seek(s, fastGlyph->cbData - new_cb); } } return TRUE; } static BOOL update_read_polygon_sc_order(wStream* s, const ORDER_INFO* orderInfo, POLYGON_SC_ORDER* polygon_sc) { UINT32 num = polygon_sc->numPoints; ORDER_FIELD_COORD(1, polygon_sc->xStart); ORDER_FIELD_COORD(2, polygon_sc->yStart); ORDER_FIELD_BYTE(3, polygon_sc->bRop2); ORDER_FIELD_BYTE(4, polygon_sc->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_sc->brushColor); ORDER_FIELD_BYTE(6, num); if (orderInfo->fieldFlags & ORDER_FIELD_07) { DELTA_POINT* newpoints; if (num == 0) return FALSE; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, polygon_sc->cbData); newpoints = (DELTA_POINT*)realloc(polygon_sc->points, sizeof(DELTA_POINT) * num); if (!newpoints) return FALSE; polygon_sc->points = newpoints; polygon_sc->numPoints = num; return update_read_delta_points(s, polygon_sc->points, polygon_sc->numPoints, polygon_sc->xStart, polygon_sc->yStart); } return TRUE; } static BOOL update_read_polygon_cb_order(wStream* s, const ORDER_INFO* orderInfo, POLYGON_CB_ORDER* polygon_cb) { UINT32 num = polygon_cb->numPoints; ORDER_FIELD_COORD(1, polygon_cb->xStart); ORDER_FIELD_COORD(2, polygon_cb->yStart); ORDER_FIELD_BYTE(3, polygon_cb->bRop2); ORDER_FIELD_BYTE(4, polygon_cb->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 5, &polygon_cb->backColor); ORDER_FIELD_COLOR(orderInfo, s, 6, &polygon_cb->foreColor); if (!update_read_brush(s, &polygon_cb->brush, orderInfo->fieldFlags >> 6)) return FALSE; ORDER_FIELD_BYTE(12, num); if (orderInfo->fieldFlags & ORDER_FIELD_13) { DELTA_POINT* newpoints; if (num == 0) return FALSE; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, polygon_cb->cbData); newpoints = (DELTA_POINT*)realloc(polygon_cb->points, sizeof(DELTA_POINT) * num); if (!newpoints) return FALSE; polygon_cb->points = newpoints; polygon_cb->numPoints = num; if (!update_read_delta_points(s, polygon_cb->points, polygon_cb->numPoints, polygon_cb->xStart, polygon_cb->yStart)) return FALSE; } polygon_cb->backMode = (polygon_cb->bRop2 & 0x80) ? BACKMODE_TRANSPARENT : BACKMODE_OPAQUE; polygon_cb->bRop2 = (polygon_cb->bRop2 & 0x1F); return TRUE; } static BOOL update_read_ellipse_sc_order(wStream* s, const ORDER_INFO* orderInfo, ELLIPSE_SC_ORDER* ellipse_sc) { ORDER_FIELD_COORD(1, ellipse_sc->leftRect); ORDER_FIELD_COORD(2, ellipse_sc->topRect); ORDER_FIELD_COORD(3, ellipse_sc->rightRect); ORDER_FIELD_COORD(4, ellipse_sc->bottomRect); ORDER_FIELD_BYTE(5, ellipse_sc->bRop2); ORDER_FIELD_BYTE(6, ellipse_sc->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_sc->color); return TRUE; } static BOOL update_read_ellipse_cb_order(wStream* s, const ORDER_INFO* orderInfo, ELLIPSE_CB_ORDER* ellipse_cb) { ORDER_FIELD_COORD(1, ellipse_cb->leftRect); ORDER_FIELD_COORD(2, ellipse_cb->topRect); ORDER_FIELD_COORD(3, ellipse_cb->rightRect); ORDER_FIELD_COORD(4, ellipse_cb->bottomRect); ORDER_FIELD_BYTE(5, ellipse_cb->bRop2); ORDER_FIELD_BYTE(6, ellipse_cb->fillMode); ORDER_FIELD_COLOR(orderInfo, s, 7, &ellipse_cb->backColor); ORDER_FIELD_COLOR(orderInfo, s, 8, &ellipse_cb->foreColor); return update_read_brush(s, &ellipse_cb->brush, orderInfo->fieldFlags >> 8); } /* Secondary Drawing Orders */ static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { CACHE_BITMAP_ORDER* cache_bitmap; if (!update || !s) return NULL; cache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER)); if (!cache_bitmap) goto fail; if (Stream_GetRemainingLength(s) < 9) goto fail; Stream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ Stream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ if ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32)) { WLog_Print(update->log, WLOG_ERROR, "invalid bitmap bpp %" PRIu32 "", cache_bitmap->bitmapBpp); goto fail; } Stream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ if (compressed) { if ((flags & NO_BITMAP_COMPRESSION_HDR) == 0) { BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ cache_bitmap->bitmapLength -= 8; } } if (cache_bitmap->bitmapLength == 0) goto fail; if (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength) goto fail; cache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength); if (!cache_bitmap->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength); cache_bitmap->compressed = compressed; return cache_bitmap; fail: free_cache_bitmap_order(update->context, cache_bitmap); return NULL; } int update_approximate_cache_bitmap_order(const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed, UINT16* flags) { return 64 + cache_bitmap->bitmapLength; } BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed, UINT16* flags) { UINT32 bitmapLength = cache_bitmap->bitmapLength; int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; *flags = NO_BITMAP_COMPRESSION_HDR; if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) bitmapLength += 8; Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */ Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ if (compressed) { if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) { BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ bitmapLength -= 8; } Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); } else { Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); } return TRUE; } static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, BOOL compressed, UINT16 flags) { BOOL rc; BYTE bitsPerPixelId; CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; if (!update || !s) return NULL; cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); if (!cache_bitmap_v2) goto fail; cache_bitmap_v2->cacheId = flags & 0x0003; cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; bitsPerPixelId = (flags & 0x0078) >> 3; cache_bitmap_v2->bitmapBpp = get_cbr2_bpp(bitsPerPixelId, &rc); if (!rc) goto fail; if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ goto fail; cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth; } else { if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ goto fail; } if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */ goto fail; if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { if (Stream_GetRemainingLength(s) < 8) goto fail; Stream_Read_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } } if (cache_bitmap_v2->bitmapLength == 0) goto fail; if (Stream_GetRemainingLength(s) < cache_bitmap_v2->bitmapLength) goto fail; if (cache_bitmap_v2->bitmapLength == 0) goto fail; cache_bitmap_v2->bitmapDataStream = malloc(cache_bitmap_v2->bitmapLength); if (!cache_bitmap_v2->bitmapDataStream) goto fail; Stream_Read(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); cache_bitmap_v2->compressed = compressed; return cache_bitmap_v2; fail: free_cache_bitmap_v2_order(update->context, cache_bitmap_v2); return NULL; } int update_approximate_cache_bitmap_v2_order(CACHE_BITMAP_V2_ORDER* cache_bitmap_v2, BOOL compressed, UINT16* flags) { return 64 + cache_bitmap_v2->bitmapLength; } BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2, BOOL compressed, UINT16* flags) { BOOL rc; BYTE bitsPerPixelId; if (!Stream_EnsureRemainingCapacity( s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags))) return FALSE; bitsPerPixelId = get_bpp_bmf(cache_bitmap_v2->bitmapBpp, &rc); if (!rc) return FALSE; *flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) | ((cache_bitmap_v2->flags << 7) & 0xFF80); if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) { Stream_Write_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ } if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) { if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ return FALSE; } else { if (!update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ !update_write_2byte_unsigned(s, cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ return FALSE; } if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; if (!update_write_4byte_unsigned(s, cache_bitmap_v2->bitmapLength) || /* bitmapLength */ !update_write_2byte_unsigned(s, cache_bitmap_v2->cacheIndex)) /* cacheIndex */ return FALSE; if (compressed) { if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16( s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16( s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16( s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; } if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength)) return FALSE; Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); } else { if (!Stream_EnsureRemainingCapacity(s, cache_bitmap_v2->bitmapLength)) return FALSE; Stream_Write(s, cache_bitmap_v2->bitmapDataStream, cache_bitmap_v2->bitmapLength); } cache_bitmap_v2->compressed = compressed; return TRUE; } static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s, UINT16 flags) { BOOL rc; BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; UINT32 new_len; BYTE* new_data; CACHE_BITMAP_V3_ORDER* cache_bitmap_v3; if (!update || !s) return NULL; cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER)); if (!cache_bitmap_v3) goto fail; cache_bitmap_v3->cacheId = flags & 0x00000003; cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7; bitsPerPixelId = (flags & 0x00000078) >> 3; cache_bitmap_v3->bpp = get_cbr2_bpp(bitsPerPixelId, &rc); if (!rc) goto fail; if (Stream_GetRemainingLength(s) < 21) goto fail; Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ bitmapData = &cache_bitmap_v3->bitmapData; Stream_Read_UINT8(s, bitmapData->bpp); if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32)) { WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp); goto fail; } Stream_Seek_UINT8(s); /* reserved1 (1 byte) */ Stream_Seek_UINT8(s); /* reserved2 (1 byte) */ Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Read_UINT32(s, new_len); /* length (4 bytes) */ if ((new_len == 0) || (Stream_GetRemainingLength(s) < new_len)) goto fail; new_data = (BYTE*)realloc(bitmapData->data, new_len); if (!new_data) goto fail; bitmapData->data = new_data; bitmapData->length = new_len; Stream_Read(s, bitmapData->data, bitmapData->length); return cache_bitmap_v3; fail: free_cache_bitmap_v3_order(update->context, cache_bitmap_v3); return NULL; } int update_approximate_cache_bitmap_v3_order(CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags) { BITMAP_DATA_EX* bitmapData = &cache_bitmap_v3->bitmapData; return 64 + bitmapData->length; } BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, UINT16* flags) { BOOL rc; BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; if (!Stream_EnsureRemainingCapacity( s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags))) return FALSE; bitmapData = &cache_bitmap_v3->bitmapData; bitsPerPixelId = get_bpp_bmf(cache_bitmap_v3->bpp, &rc); if (!rc) return FALSE; *flags = (cache_bitmap_v3->cacheId & 0x00000003) | ((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078); Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ Stream_Write_UINT8(s, bitmapData->bpp); Stream_Write_UINT8(s, 0); /* reserved1 (1 byte) */ Stream_Write_UINT8(s, 0); /* reserved2 (1 byte) */ Stream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */ Stream_Write(s, bitmapData->data, bitmapData->length); return TRUE; } static CACHE_COLOR_TABLE_ORDER* update_read_cache_color_table_order(rdpUpdate* update, wStream* s, UINT16 flags) { int i; UINT32* colorTable; CACHE_COLOR_TABLE_ORDER* cache_color_table = calloc(1, sizeof(CACHE_COLOR_TABLE_ORDER)); if (!cache_color_table) goto fail; if (Stream_GetRemainingLength(s) < 3) goto fail; Stream_Read_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */ Stream_Read_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */ if (cache_color_table->numberColors != 256) { /* This field MUST be set to 256 */ goto fail; } if (Stream_GetRemainingLength(s) < cache_color_table->numberColors * 4) goto fail; colorTable = (UINT32*)&cache_color_table->colorTable; for (i = 0; i < (int)cache_color_table->numberColors; i++) update_read_color_quad(s, &colorTable[i]); return cache_color_table; fail: free_cache_color_table_order(update->context, cache_color_table); return NULL; } int update_approximate_cache_color_table_order(const CACHE_COLOR_TABLE_ORDER* cache_color_table, UINT16* flags) { return 16 + (256 * 4); } BOOL update_write_cache_color_table_order(wStream* s, const CACHE_COLOR_TABLE_ORDER* cache_color_table, UINT16* flags) { int i, inf; UINT32* colorTable; if (cache_color_table->numberColors != 256) return FALSE; inf = update_approximate_cache_color_table_order(cache_color_table, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT8(s, cache_color_table->cacheIndex); /* cacheIndex (1 byte) */ Stream_Write_UINT16(s, cache_color_table->numberColors); /* numberColors (2 bytes) */ colorTable = (UINT32*)&cache_color_table->colorTable; for (i = 0; i < (int)cache_color_table->numberColors; i++) { update_write_color_quad(s, colorTable[i]); } return TRUE; } static CACHE_GLYPH_ORDER* update_read_cache_glyph_order(rdpUpdate* update, wStream* s, UINT16 flags) { UINT32 i; CACHE_GLYPH_ORDER* cache_glyph_order = calloc(1, sizeof(CACHE_GLYPH_ORDER)); if (!cache_glyph_order || !update || !s) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT8(s, cache_glyph_order->cacheId); /* cacheId (1 byte) */ Stream_Read_UINT8(s, cache_glyph_order->cGlyphs); /* cGlyphs (1 byte) */ for (i = 0; i < cache_glyph_order->cGlyphs; i++) { GLYPH_DATA* glyph = &cache_glyph_order->glyphData[i]; if (Stream_GetRemainingLength(s) < 10) goto fail; Stream_Read_UINT16(s, glyph->cacheIndex); Stream_Read_INT16(s, glyph->x); Stream_Read_INT16(s, glyph->y); Stream_Read_UINT16(s, glyph->cx); Stream_Read_UINT16(s, glyph->cy); glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; if (Stream_GetRemainingLength(s) < glyph->cb) goto fail; glyph->aj = (BYTE*)malloc(glyph->cb); if (!glyph->aj) goto fail; Stream_Read(s, glyph->aj, glyph->cb); } if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_order->cGlyphs > 0)) { cache_glyph_order->unicodeCharacters = calloc(cache_glyph_order->cGlyphs, sizeof(WCHAR)); if (!cache_glyph_order->unicodeCharacters) goto fail; if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_order->cGlyphs) goto fail; Stream_Read_UTF16_String(s, cache_glyph_order->unicodeCharacters, cache_glyph_order->cGlyphs); } return cache_glyph_order; fail: free_cache_glyph_order(update->context, cache_glyph_order); return NULL; } int update_approximate_cache_glyph_order(const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags) { return 2 + cache_glyph->cGlyphs * 32; } BOOL update_write_cache_glyph_order(wStream* s, const CACHE_GLYPH_ORDER* cache_glyph, UINT16* flags) { int i, inf; INT16 lsi16; const GLYPH_DATA* glyph; inf = update_approximate_cache_glyph_order(cache_glyph, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT8(s, cache_glyph->cacheId); /* cacheId (1 byte) */ Stream_Write_UINT8(s, cache_glyph->cGlyphs); /* cGlyphs (1 byte) */ for (i = 0; i < (int)cache_glyph->cGlyphs; i++) { UINT32 cb; glyph = &cache_glyph->glyphData[i]; Stream_Write_UINT16(s, glyph->cacheIndex); /* cacheIndex (2 bytes) */ lsi16 = glyph->x; Stream_Write_UINT16(s, lsi16); /* x (2 bytes) */ lsi16 = glyph->y; Stream_Write_UINT16(s, lsi16); /* y (2 bytes) */ Stream_Write_UINT16(s, glyph->cx); /* cx (2 bytes) */ Stream_Write_UINT16(s, glyph->cy); /* cy (2 bytes) */ cb = ((glyph->cx + 7) / 8) * glyph->cy; cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0; Stream_Write(s, glyph->aj, cb); } if (*flags & CG_GLYPH_UNICODE_PRESENT) { Stream_Zero(s, cache_glyph->cGlyphs * 2); } return TRUE; } static CACHE_GLYPH_V2_ORDER* update_read_cache_glyph_v2_order(rdpUpdate* update, wStream* s, UINT16 flags) { UINT32 i; CACHE_GLYPH_V2_ORDER* cache_glyph_v2 = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER)); if (!cache_glyph_v2) goto fail; cache_glyph_v2->cacheId = (flags & 0x000F); cache_glyph_v2->flags = (flags & 0x00F0) >> 4; cache_glyph_v2->cGlyphs = (flags & 0xFF00) >> 8; for (i = 0; i < cache_glyph_v2->cGlyphs; i++) { GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i]; if (Stream_GetRemainingLength(s) < 1) goto fail; Stream_Read_UINT8(s, glyph->cacheIndex); if (!update_read_2byte_signed(s, &glyph->x) || !update_read_2byte_signed(s, &glyph->y) || !update_read_2byte_unsigned(s, &glyph->cx) || !update_read_2byte_unsigned(s, &glyph->cy)) { goto fail; } glyph->cb = ((glyph->cx + 7) / 8) * glyph->cy; glyph->cb += ((glyph->cb % 4) > 0) ? 4 - (glyph->cb % 4) : 0; if (Stream_GetRemainingLength(s) < glyph->cb) goto fail; glyph->aj = (BYTE*)malloc(glyph->cb); if (!glyph->aj) goto fail; Stream_Read(s, glyph->aj, glyph->cb); } if ((flags & CG_GLYPH_UNICODE_PRESENT) && (cache_glyph_v2->cGlyphs > 0)) { cache_glyph_v2->unicodeCharacters = calloc(cache_glyph_v2->cGlyphs, sizeof(WCHAR)); if (!cache_glyph_v2->unicodeCharacters) goto fail; if (Stream_GetRemainingLength(s) < sizeof(WCHAR) * cache_glyph_v2->cGlyphs) goto fail; Stream_Read_UTF16_String(s, cache_glyph_v2->unicodeCharacters, cache_glyph_v2->cGlyphs); } return cache_glyph_v2; fail: free_cache_glyph_v2_order(update->context, cache_glyph_v2); return NULL; } int update_approximate_cache_glyph_v2_order(const CACHE_GLYPH_V2_ORDER* cache_glyph_v2, UINT16* flags) { return 8 + cache_glyph_v2->cGlyphs * 32; } BOOL update_write_cache_glyph_v2_order(wStream* s, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2, UINT16* flags) { UINT32 i, inf; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, flags); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; *flags = (cache_glyph_v2->cacheId & 0x000F) | ((cache_glyph_v2->flags & 0x000F) << 4) | ((cache_glyph_v2->cGlyphs & 0x00FF) << 8); for (i = 0; i < cache_glyph_v2->cGlyphs; i++) { UINT32 cb; const GLYPH_DATA_V2* glyph = &cache_glyph_v2->glyphData[i]; Stream_Write_UINT8(s, glyph->cacheIndex); if (!update_write_2byte_signed(s, glyph->x) || !update_write_2byte_signed(s, glyph->y) || !update_write_2byte_unsigned(s, glyph->cx) || !update_write_2byte_unsigned(s, glyph->cy)) { return FALSE; } cb = ((glyph->cx + 7) / 8) * glyph->cy; cb += ((cb % 4) > 0) ? 4 - (cb % 4) : 0; Stream_Write(s, glyph->aj, cb); } if (*flags & CG_GLYPH_UNICODE_PRESENT) { Stream_Zero(s, cache_glyph_v2->cGlyphs * 2); } return TRUE; } static BOOL update_decompress_brush(wStream* s, BYTE* output, size_t outSize, BYTE bpp) { INT32 x, y, k; BYTE byte = 0; const BYTE* palette = Stream_Pointer(s) + 16; const INT32 bytesPerPixel = ((bpp + 1) / 8); if (!Stream_SafeSeek(s, 16ULL + 7ULL * bytesPerPixel)) // 64 / 4 return FALSE; for (y = 7; y >= 0; y--) { for (x = 0; x < 8; x++) { UINT32 index; if ((x % 4) == 0) Stream_Read_UINT8(s, byte); index = ((byte >> ((3 - (x % 4)) * 2)) & 0x03); for (k = 0; k < bytesPerPixel; k++) { const size_t dstIndex = ((y * 8 + x) * bytesPerPixel) + k; const size_t srcIndex = (index * bytesPerPixel) + k; if (dstIndex >= outSize) return FALSE; output[dstIndex] = palette[srcIndex]; } } } return TRUE; } static BOOL update_compress_brush(wStream* s, const BYTE* input, BYTE bpp) { return FALSE; } static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStream* s, UINT16 flags) { int i; BOOL rc; BYTE iBitmapFormat; BOOL compressed = FALSE; CACHE_BRUSH_ORDER* cache_brush = calloc(1, sizeof(CACHE_BRUSH_ORDER)); if (!cache_brush) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Read_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ Stream_Read_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ cache_brush->bpp = get_bmf_bpp(iBitmapFormat, &rc); if (!rc) goto fail; Stream_Read_UINT8(s, cache_brush->cx); /* cx (1 byte) */ Stream_Read_UINT8(s, cache_brush->cy); /* cy (1 byte) */ Stream_Read_UINT8(s, cache_brush->style); /* style (1 byte) */ Stream_Read_UINT8(s, cache_brush->length); /* iBytes (1 byte) */ if ((cache_brush->cx == 8) && (cache_brush->cy == 8)) { if (cache_brush->bpp == 1) { if (cache_brush->length != 8) { WLog_Print(update->log, WLOG_ERROR, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length); goto fail; } /* rows are encoded in reverse order */ if (Stream_GetRemainingLength(s) < 8) goto fail; for (i = 7; i >= 0; i--) { Stream_Read_UINT8(s, cache_brush->data[i]); } } else { if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20)) compressed = TRUE; else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24)) compressed = TRUE; else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32)) compressed = TRUE; if (compressed != FALSE) { /* compressed brush */ if (!update_decompress_brush(s, cache_brush->data, sizeof(cache_brush->data), cache_brush->bpp)) goto fail; } else { /* uncompressed brush */ UINT32 scanline = (cache_brush->bpp / 8) * 8; if (Stream_GetRemainingLength(s) < scanline * 8) goto fail; for (i = 7; i >= 0; i--) { Stream_Read(s, &cache_brush->data[i * scanline], scanline); } } } } return cache_brush; fail: free_cache_brush_order(update->context, cache_brush); return NULL; } int update_approximate_cache_brush_order(const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags) { return 64; } BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_brush, UINT16* flags) { int i; BYTE iBitmapFormat; BOOL rc; BOOL compressed = FALSE; if (!Stream_EnsureRemainingCapacity(s, update_approximate_cache_brush_order(cache_brush, flags))) return FALSE; iBitmapFormat = get_bpp_bmf(cache_brush->bpp, &rc); if (!rc) return FALSE; Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */ Stream_Write_UINT8(s, cache_brush->cy); /* cy (1 byte) */ Stream_Write_UINT8(s, cache_brush->style); /* style (1 byte) */ Stream_Write_UINT8(s, cache_brush->length); /* iBytes (1 byte) */ if ((cache_brush->cx == 8) && (cache_brush->cy == 8)) { if (cache_brush->bpp == 1) { if (cache_brush->length != 8) { WLog_ERR(TAG, "incompatible 1bpp brush of length:%" PRIu32 "", cache_brush->length); return FALSE; } for (i = 7; i >= 0; i--) { Stream_Write_UINT8(s, cache_brush->data[i]); } } else { if ((iBitmapFormat == BMF_8BPP) && (cache_brush->length == 20)) compressed = TRUE; else if ((iBitmapFormat == BMF_16BPP) && (cache_brush->length == 24)) compressed = TRUE; else if ((iBitmapFormat == BMF_32BPP) && (cache_brush->length == 32)) compressed = TRUE; if (compressed != FALSE) { /* compressed brush */ if (!update_compress_brush(s, cache_brush->data, cache_brush->bpp)) return FALSE; } else { /* uncompressed brush */ int scanline = (cache_brush->bpp / 8) * 8; for (i = 7; i >= 0; i--) { Stream_Write(s, &cache_brush->data[i * scanline], scanline); } } } } return TRUE; } /* Alternate Secondary Drawing Orders */ static BOOL update_read_create_offscreen_bitmap_order(wStream* s, CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { UINT16 flags; BOOL deleteListPresent; OFFSCREEN_DELETE_LIST* deleteList; if (Stream_GetRemainingLength(s) < 6) return FALSE; Stream_Read_UINT16(s, flags); /* flags (2 bytes) */ create_offscreen_bitmap->id = flags & 0x7FFF; deleteListPresent = (flags & 0x8000) ? TRUE : FALSE; Stream_Read_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */ Stream_Read_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */ deleteList = &(create_offscreen_bitmap->deleteList); if (deleteListPresent) { UINT32 i; if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, deleteList->cIndices); if (deleteList->cIndices > deleteList->sIndices) { UINT16* new_indices; new_indices = (UINT16*)realloc(deleteList->indices, deleteList->cIndices * 2); if (!new_indices) return FALSE; deleteList->sIndices = deleteList->cIndices; deleteList->indices = new_indices; } if (Stream_GetRemainingLength(s) < 2 * deleteList->cIndices) return FALSE; for (i = 0; i < deleteList->cIndices; i++) { Stream_Read_UINT16(s, deleteList->indices[i]); } } else { deleteList->cIndices = 0; } return TRUE; } int update_approximate_create_offscreen_bitmap_order( const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { const OFFSCREEN_DELETE_LIST* deleteList = &(create_offscreen_bitmap->deleteList); return 32 + deleteList->cIndices * 2; } BOOL update_write_create_offscreen_bitmap_order( wStream* s, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { UINT16 flags; BOOL deleteListPresent; const OFFSCREEN_DELETE_LIST* deleteList; if (!Stream_EnsureRemainingCapacity( s, update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap))) return FALSE; deleteList = &(create_offscreen_bitmap->deleteList); flags = create_offscreen_bitmap->id & 0x7FFF; deleteListPresent = (deleteList->cIndices > 0) ? TRUE : FALSE; if (deleteListPresent) flags |= 0x8000; Stream_Write_UINT16(s, flags); /* flags (2 bytes) */ Stream_Write_UINT16(s, create_offscreen_bitmap->cx); /* cx (2 bytes) */ Stream_Write_UINT16(s, create_offscreen_bitmap->cy); /* cy (2 bytes) */ if (deleteListPresent) { int i; Stream_Write_UINT16(s, deleteList->cIndices); for (i = 0; i < (int)deleteList->cIndices; i++) { Stream_Write_UINT16(s, deleteList->indices[i]); } } return TRUE; } static BOOL update_read_switch_surface_order(wStream* s, SWITCH_SURFACE_ORDER* switch_surface) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */ return TRUE; } int update_approximate_switch_surface_order(const SWITCH_SURFACE_ORDER* switch_surface) { return 2; } BOOL update_write_switch_surface_order(wStream* s, const SWITCH_SURFACE_ORDER* switch_surface) { int inf = update_approximate_switch_surface_order(switch_surface); if (!Stream_EnsureRemainingCapacity(s, inf)) return FALSE; Stream_Write_UINT16(s, switch_surface->bitmapId); /* bitmapId (2 bytes) */ return TRUE; } static BOOL update_read_create_nine_grid_bitmap_order(wStream* s, CREATE_NINE_GRID_BITMAP_ORDER* create_nine_grid_bitmap) { NINE_GRID_BITMAP_INFO* nineGridInfo; if (Stream_GetRemainingLength(s) < 19) return FALSE; Stream_Read_UINT8(s, create_nine_grid_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ if ((create_nine_grid_bitmap->bitmapBpp < 1) || (create_nine_grid_bitmap->bitmapBpp > 32)) { WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", create_nine_grid_bitmap->bitmapBpp); return FALSE; } Stream_Read_UINT16(s, create_nine_grid_bitmap->bitmapId); /* bitmapId (2 bytes) */ nineGridInfo = &(create_nine_grid_bitmap->nineGridInfo); Stream_Read_UINT32(s, nineGridInfo->flFlags); /* flFlags (4 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulLeftWidth); /* ulLeftWidth (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulRightWidth); /* ulRightWidth (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulTopHeight); /* ulTopHeight (2 bytes) */ Stream_Read_UINT16(s, nineGridInfo->ulBottomHeight); /* ulBottomHeight (2 bytes) */ update_read_colorref(s, &nineGridInfo->crTransparent); /* crTransparent (4 bytes) */ return TRUE; } static BOOL update_read_frame_marker_order(wStream* s, FRAME_MARKER_ORDER* frame_marker) { if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, frame_marker->action); /* action (4 bytes) */ return TRUE; } static BOOL update_read_stream_bitmap_first_order(wStream* s, STREAM_BITMAP_FIRST_ORDER* stream_bitmap_first) { if (Stream_GetRemainingLength(s) < 10) // 8 + 2 at least return FALSE; Stream_Read_UINT8(s, stream_bitmap_first->bitmapFlags); /* bitmapFlags (1 byte) */ Stream_Read_UINT8(s, stream_bitmap_first->bitmapBpp); /* bitmapBpp (1 byte) */ if ((stream_bitmap_first->bitmapBpp < 1) || (stream_bitmap_first->bitmapBpp > 32)) { WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", stream_bitmap_first->bitmapBpp); return FALSE; } Stream_Read_UINT16(s, stream_bitmap_first->bitmapType); /* bitmapType (2 bytes) */ Stream_Read_UINT16(s, stream_bitmap_first->bitmapWidth); /* bitmapWidth (2 bytes) */ Stream_Read_UINT16(s, stream_bitmap_first->bitmapHeight); /* bitmapHeigth (2 bytes) */ if (stream_bitmap_first->bitmapFlags & STREAM_BITMAP_V2) { if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, stream_bitmap_first->bitmapSize); /* bitmapSize (4 bytes) */ } else { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, stream_bitmap_first->bitmapSize); /* bitmapSize (2 bytes) */ } FIELD_SKIP_BUFFER16( s, stream_bitmap_first->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */ return TRUE; } static BOOL update_read_stream_bitmap_next_order(wStream* s, STREAM_BITMAP_NEXT_ORDER* stream_bitmap_next) { if (Stream_GetRemainingLength(s) < 5) return FALSE; Stream_Read_UINT8(s, stream_bitmap_next->bitmapFlags); /* bitmapFlags (1 byte) */ Stream_Read_UINT16(s, stream_bitmap_next->bitmapType); /* bitmapType (2 bytes) */ FIELD_SKIP_BUFFER16( s, stream_bitmap_next->bitmapBlockSize); /* bitmapBlockSize(2 bytes) + bitmapBlock */ return TRUE; } static BOOL update_read_draw_gdiplus_first_order(wStream* s, DRAW_GDIPLUS_FIRST_ORDER* draw_gdiplus_first) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_first->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalSize); /* cbTotalSize (4 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_first->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_first->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_next_order(wStream* s, DRAW_GDIPLUS_NEXT_ORDER* draw_gdiplus_next) { if (Stream_GetRemainingLength(s) < 3) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ FIELD_SKIP_BUFFER16(s, draw_gdiplus_next->cbSize); /* cbSize(2 bytes) + emfRecords */ return TRUE; } static BOOL update_read_draw_gdiplus_end_order(wStream* s, DRAW_GDIPLUS_END_ORDER* draw_gdiplus_end) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_end->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalSize); /* cbTotalSize (4 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_end->cbTotalEmfSize); /* cbTotalEmfSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_end->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_cache_first_order(wStream* s, DRAW_GDIPLUS_CACHE_FIRST_ORDER* draw_gdiplus_cache_first) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_first->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_first->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_cache_first->cbTotalSize); /* cbTotalSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_cache_first->cbSize); /* emfRecords */ } static BOOL update_read_draw_gdiplus_cache_next_order(wStream* s, DRAW_GDIPLUS_CACHE_NEXT_ORDER* draw_gdiplus_cache_next) { if (Stream_GetRemainingLength(s) < 7) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_next->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_next->cacheIndex); /* cacheIndex (2 bytes) */ FIELD_SKIP_BUFFER16(s, draw_gdiplus_cache_next->cbSize); /* cbSize(2 bytes) + emfRecords */ return TRUE; } static BOOL update_read_draw_gdiplus_cache_end_order(wStream* s, DRAW_GDIPLUS_CACHE_END_ORDER* draw_gdiplus_cache_end) { if (Stream_GetRemainingLength(s) < 11) return FALSE; Stream_Read_UINT8(s, draw_gdiplus_cache_end->flags); /* flags (1 byte) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheType); /* cacheType (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, draw_gdiplus_cache_end->cbSize); /* cbSize (2 bytes) */ Stream_Read_UINT32(s, draw_gdiplus_cache_end->cbTotalSize); /* cbTotalSize (4 bytes) */ return Stream_SafeSeek(s, draw_gdiplus_cache_end->cbSize); /* emfRecords */ } static BOOL update_read_field_flags(wStream* s, UINT32* fieldFlags, BYTE flags, BYTE fieldBytes) { int i; BYTE byte; if (flags & ORDER_ZERO_FIELD_BYTE_BIT0) fieldBytes--; if (flags & ORDER_ZERO_FIELD_BYTE_BIT1) { if (fieldBytes > 1) fieldBytes -= 2; else fieldBytes = 0; } if (Stream_GetRemainingLength(s) < fieldBytes) return FALSE; *fieldFlags = 0; for (i = 0; i < fieldBytes; i++) { Stream_Read_UINT8(s, byte); *fieldFlags |= byte << (i * 8); } return TRUE; } BOOL update_write_field_flags(wStream* s, UINT32 fieldFlags, BYTE flags, BYTE fieldBytes) { BYTE byte; if (fieldBytes == 1) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); } else if (fieldBytes == 2) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 8) & 0xFF; Stream_Write_UINT8(s, byte); } else if (fieldBytes == 3) { byte = fieldFlags & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 8) & 0xFF; Stream_Write_UINT8(s, byte); byte = (fieldFlags >> 16) & 0xFF; Stream_Write_UINT8(s, byte); } else { return FALSE; } return TRUE; } static BOOL update_read_bounds(wStream* s, rdpBounds* bounds) { BYTE flags; if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, flags); /* field flags */ if (flags & BOUND_LEFT) { if (!update_read_coord(s, &bounds->left, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_LEFT) { if (!update_read_coord(s, &bounds->left, TRUE)) return FALSE; } if (flags & BOUND_TOP) { if (!update_read_coord(s, &bounds->top, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_TOP) { if (!update_read_coord(s, &bounds->top, TRUE)) return FALSE; } if (flags & BOUND_RIGHT) { if (!update_read_coord(s, &bounds->right, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_RIGHT) { if (!update_read_coord(s, &bounds->right, TRUE)) return FALSE; } if (flags & BOUND_BOTTOM) { if (!update_read_coord(s, &bounds->bottom, FALSE)) return FALSE; } else if (flags & BOUND_DELTA_BOTTOM) { if (!update_read_coord(s, &bounds->bottom, TRUE)) return FALSE; } return TRUE; } BOOL update_write_bounds(wStream* s, ORDER_INFO* orderInfo) { if (!(orderInfo->controlFlags & ORDER_BOUNDS)) return TRUE; if (orderInfo->controlFlags & ORDER_ZERO_BOUNDS_DELTAS) return TRUE; Stream_Write_UINT8(s, orderInfo->boundsFlags); /* field flags */ if (orderInfo->boundsFlags & BOUND_LEFT) { if (!update_write_coord(s, orderInfo->bounds.left)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_LEFT) { } if (orderInfo->boundsFlags & BOUND_TOP) { if (!update_write_coord(s, orderInfo->bounds.top)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_TOP) { } if (orderInfo->boundsFlags & BOUND_RIGHT) { if (!update_write_coord(s, orderInfo->bounds.right)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_RIGHT) { } if (orderInfo->boundsFlags & BOUND_BOTTOM) { if (!update_write_coord(s, orderInfo->bounds.bottom)) return FALSE; } else if (orderInfo->boundsFlags & BOUND_DELTA_BOTTOM) { } return TRUE; } static BOOL read_primary_order(wLog* log, const char* orderName, wStream* s, const ORDER_INFO* orderInfo, rdpPrimaryUpdate* primary) { BOOL rc = FALSE; if (!s || !orderInfo || !primary || !orderName) return FALSE; switch (orderInfo->orderType) { case ORDER_TYPE_DSTBLT: rc = update_read_dstblt_order(s, orderInfo, &(primary->dstblt)); break; case ORDER_TYPE_PATBLT: rc = update_read_patblt_order(s, orderInfo, &(primary->patblt)); break; case ORDER_TYPE_SCRBLT: rc = update_read_scrblt_order(s, orderInfo, &(primary->scrblt)); break; case ORDER_TYPE_OPAQUE_RECT: rc = update_read_opaque_rect_order(s, orderInfo, &(primary->opaque_rect)); break; case ORDER_TYPE_DRAW_NINE_GRID: rc = update_read_draw_nine_grid_order(s, orderInfo, &(primary->draw_nine_grid)); break; case ORDER_TYPE_MULTI_DSTBLT: rc = update_read_multi_dstblt_order(s, orderInfo, &(primary->multi_dstblt)); break; case ORDER_TYPE_MULTI_PATBLT: rc = update_read_multi_patblt_order(s, orderInfo, &(primary->multi_patblt)); break; case ORDER_TYPE_MULTI_SCRBLT: rc = update_read_multi_scrblt_order(s, orderInfo, &(primary->multi_scrblt)); break; case ORDER_TYPE_MULTI_OPAQUE_RECT: rc = update_read_multi_opaque_rect_order(s, orderInfo, &(primary->multi_opaque_rect)); break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: rc = update_read_multi_draw_nine_grid_order(s, orderInfo, &(primary->multi_draw_nine_grid)); break; case ORDER_TYPE_LINE_TO: rc = update_read_line_to_order(s, orderInfo, &(primary->line_to)); break; case ORDER_TYPE_POLYLINE: rc = update_read_polyline_order(s, orderInfo, &(primary->polyline)); break; case ORDER_TYPE_MEMBLT: rc = update_read_memblt_order(s, orderInfo, &(primary->memblt)); break; case ORDER_TYPE_MEM3BLT: rc = update_read_mem3blt_order(s, orderInfo, &(primary->mem3blt)); break; case ORDER_TYPE_SAVE_BITMAP: rc = update_read_save_bitmap_order(s, orderInfo, &(primary->save_bitmap)); break; case ORDER_TYPE_GLYPH_INDEX: rc = update_read_glyph_index_order(s, orderInfo, &(primary->glyph_index)); break; case ORDER_TYPE_FAST_INDEX: rc = update_read_fast_index_order(s, orderInfo, &(primary->fast_index)); break; case ORDER_TYPE_FAST_GLYPH: rc = update_read_fast_glyph_order(s, orderInfo, &(primary->fast_glyph)); break; case ORDER_TYPE_POLYGON_SC: rc = update_read_polygon_sc_order(s, orderInfo, &(primary->polygon_sc)); break; case ORDER_TYPE_POLYGON_CB: rc = update_read_polygon_cb_order(s, orderInfo, &(primary->polygon_cb)); break; case ORDER_TYPE_ELLIPSE_SC: rc = update_read_ellipse_sc_order(s, orderInfo, &(primary->ellipse_sc)); break; case ORDER_TYPE_ELLIPSE_CB: rc = update_read_ellipse_cb_order(s, orderInfo, &(primary->ellipse_cb)); break; default: WLog_Print(log, WLOG_WARN, "Primary Drawing Order %s not supported, ignoring", orderName); rc = TRUE; break; } if (!rc) { WLog_Print(log, WLOG_ERROR, "%s - update_read_dstblt_order() failed", orderName); return FALSE; } return TRUE; } static BOOL update_recv_primary_order(rdpUpdate* update, wStream* s, BYTE flags) { BYTE field; BOOL rc = FALSE; rdpContext* context = update->context; rdpPrimaryUpdate* primary = update->primary; ORDER_INFO* orderInfo = &(primary->order_info); rdpSettings* settings = context->settings; const char* orderName; if (flags & ORDER_TYPE_CHANGE) { if (Stream_GetRemainingLength(s) < 1) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ } orderName = primary_order_string(orderInfo->orderType); if (!check_primary_order_supported(update->log, settings, orderInfo->orderType, orderName)) return FALSE; field = get_primary_drawing_order_field_bytes(orderInfo->orderType, &rc); if (!rc) return FALSE; if (!update_read_field_flags(s, &(orderInfo->fieldFlags), flags, field)) { WLog_Print(update->log, WLOG_ERROR, "update_read_field_flags() failed"); return FALSE; } if (flags & ORDER_BOUNDS) { if (!(flags & ORDER_ZERO_BOUNDS_DELTAS)) { if (!update_read_bounds(s, &orderInfo->bounds)) { WLog_Print(update->log, WLOG_ERROR, "update_read_bounds() failed"); return FALSE; } } rc = IFCALLRESULT(FALSE, update->SetBounds, context, &orderInfo->bounds); if (!rc) return FALSE; } orderInfo->deltaCoordinates = (flags & ORDER_DELTA_COORDINATES) ? TRUE : FALSE; if (!read_primary_order(update->log, orderName, s, orderInfo, primary)) return FALSE; switch (orderInfo->orderType) { case ORDER_TYPE_DSTBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->dstblt.bRop), gdi_rop3_code(primary->dstblt.bRop)); rc = IFCALLRESULT(FALSE, primary->DstBlt, context, &primary->dstblt); } break; case ORDER_TYPE_PATBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->patblt.bRop), gdi_rop3_code(primary->patblt.bRop)); rc = IFCALLRESULT(FALSE, primary->PatBlt, context, &primary->patblt); } break; case ORDER_TYPE_SCRBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->scrblt.bRop), gdi_rop3_code(primary->scrblt.bRop)); rc = IFCALLRESULT(FALSE, primary->ScrBlt, context, &primary->scrblt); } break; case ORDER_TYPE_OPAQUE_RECT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->OpaqueRect, context, &primary->opaque_rect); } break; case ORDER_TYPE_DRAW_NINE_GRID: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->DrawNineGrid, context, &primary->draw_nine_grid); } break; case ORDER_TYPE_MULTI_DSTBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_dstblt.bRop), gdi_rop3_code(primary->multi_dstblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiDstBlt, context, &primary->multi_dstblt); } break; case ORDER_TYPE_MULTI_PATBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_patblt.bRop), gdi_rop3_code(primary->multi_patblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiPatBlt, context, &primary->multi_patblt); } break; case ORDER_TYPE_MULTI_SCRBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->multi_scrblt.bRop), gdi_rop3_code(primary->multi_scrblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MultiScrBlt, context, &primary->multi_scrblt); } break; case ORDER_TYPE_MULTI_OPAQUE_RECT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->MultiOpaqueRect, context, &primary->multi_opaque_rect); } break; case ORDER_TYPE_MULTI_DRAW_NINE_GRID: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->MultiDrawNineGrid, context, &primary->multi_draw_nine_grid); } break; case ORDER_TYPE_LINE_TO: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->LineTo, context, &primary->line_to); } break; case ORDER_TYPE_POLYLINE: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->Polyline, context, &primary->polyline); } break; case ORDER_TYPE_MEMBLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->memblt.bRop), gdi_rop3_code(primary->memblt.bRop)); rc = IFCALLRESULT(FALSE, primary->MemBlt, context, &primary->memblt); } break; case ORDER_TYPE_MEM3BLT: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s rop=%s [0x%08" PRIx32 "]", orderName, gdi_rop3_code_string(primary->mem3blt.bRop), gdi_rop3_code(primary->mem3blt.bRop)); rc = IFCALLRESULT(FALSE, primary->Mem3Blt, context, &primary->mem3blt); } break; case ORDER_TYPE_SAVE_BITMAP: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->SaveBitmap, context, &primary->save_bitmap); } break; case ORDER_TYPE_GLYPH_INDEX: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->GlyphIndex, context, &primary->glyph_index); } break; case ORDER_TYPE_FAST_INDEX: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->FastIndex, context, &primary->fast_index); } break; case ORDER_TYPE_FAST_GLYPH: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->FastGlyph, context, &primary->fast_glyph); } break; case ORDER_TYPE_POLYGON_SC: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->PolygonSC, context, &primary->polygon_sc); } break; case ORDER_TYPE_POLYGON_CB: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->PolygonCB, context, &primary->polygon_cb); } break; case ORDER_TYPE_ELLIPSE_SC: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->EllipseSC, context, &primary->ellipse_sc); } break; case ORDER_TYPE_ELLIPSE_CB: { WLog_Print(update->log, WLOG_DEBUG, "Primary Drawing Order %s", orderName); rc = IFCALLRESULT(FALSE, primary->EllipseCB, context, &primary->ellipse_cb); } break; default: WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s not supported", orderName); break; } if (!rc) { WLog_Print(update->log, WLOG_WARN, "Primary Drawing Order %s failed", orderName); return FALSE; } if (flags & ORDER_BOUNDS) { rc = IFCALLRESULT(FALSE, update->SetBounds, context, NULL); } return rc; } static BOOL update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) { BOOL rc = FALSE; size_t start, end, diff; BYTE orderType; UINT16 extraFlags; UINT16 orderLength; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpSecondaryUpdate* secondary = update->secondary; const char* name; if (Stream_GetRemainingLength(s) < 5) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 5"); return FALSE; } Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */ if (Stream_GetRemainingLength(s) < orderLength + 7U) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) %" PRIuz " < %" PRIu16, Stream_GetRemainingLength(s), orderLength + 7); return FALSE; } start = Stream_GetPosition(s); name = secondary_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, "Secondary Drawing Order %s", name); if (!check_secondary_order_supported(update->log, settings, orderType, name)) return FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: { const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED); CACHE_BITMAP_ORDER* order = update_read_cache_bitmap_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order); free_cache_bitmap_order(context, order); } } break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: { const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2); CACHE_BITMAP_V2_ORDER* order = update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order); free_cache_bitmap_v2_order(context, order); } } break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: { CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order); free_cache_bitmap_v3_order(context, order); } } break; case ORDER_TYPE_CACHE_COLOR_TABLE: { CACHE_COLOR_TABLE_ORDER* order = update_read_cache_color_table_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order); free_cache_color_table_order(context, order); } } break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: { CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order); free_cache_glyph_order(context, order); } } break; case GLYPH_SUPPORT_ENCODE: { CACHE_GLYPH_V2_ORDER* order = update_read_cache_glyph_v2_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order); free_cache_glyph_v2_order(context, order); } } break; case GLYPH_SUPPORT_NONE: default: break; } } break; case ORDER_TYPE_CACHE_BRUSH: /* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */ { CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order); free_cache_brush_order(context, order); } } break; default: WLog_Print(update->log, WLOG_WARN, "SECONDARY ORDER %s not supported", name); break; } if (!rc) { WLog_Print(update->log, WLOG_ERROR, "SECONDARY ORDER %s failed", name); } start += orderLength + 7; end = Stream_GetPosition(s); if (start > end) { WLog_Print(update->log, WLOG_WARN, "SECONDARY_ORDER %s: read %" PRIuz "bytes too much", name, end - start); return FALSE; } diff = start - end; if (diff > 0) { WLog_Print(update->log, WLOG_DEBUG, "SECONDARY_ORDER %s: read %" PRIuz "bytes short, skipping", name, diff); Stream_Seek(s, diff); } return rc; } static BOOL read_altsec_order(wStream* s, BYTE orderType, rdpAltSecUpdate* altsec) { BOOL rc = FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: rc = update_read_create_offscreen_bitmap_order(s, &(altsec->create_offscreen_bitmap)); break; case ORDER_TYPE_SWITCH_SURFACE: rc = update_read_switch_surface_order(s, &(altsec->switch_surface)); break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: rc = update_read_create_nine_grid_bitmap_order(s, &(altsec->create_nine_grid_bitmap)); break; case ORDER_TYPE_FRAME_MARKER: rc = update_read_frame_marker_order(s, &(altsec->frame_marker)); break; case ORDER_TYPE_STREAM_BITMAP_FIRST: rc = update_read_stream_bitmap_first_order(s, &(altsec->stream_bitmap_first)); break; case ORDER_TYPE_STREAM_BITMAP_NEXT: rc = update_read_stream_bitmap_next_order(s, &(altsec->stream_bitmap_next)); break; case ORDER_TYPE_GDIPLUS_FIRST: rc = update_read_draw_gdiplus_first_order(s, &(altsec->draw_gdiplus_first)); break; case ORDER_TYPE_GDIPLUS_NEXT: rc = update_read_draw_gdiplus_next_order(s, &(altsec->draw_gdiplus_next)); break; case ORDER_TYPE_GDIPLUS_END: rc = update_read_draw_gdiplus_end_order(s, &(altsec->draw_gdiplus_end)); break; case ORDER_TYPE_GDIPLUS_CACHE_FIRST: rc = update_read_draw_gdiplus_cache_first_order(s, &(altsec->draw_gdiplus_cache_first)); break; case ORDER_TYPE_GDIPLUS_CACHE_NEXT: rc = update_read_draw_gdiplus_cache_next_order(s, &(altsec->draw_gdiplus_cache_next)); break; case ORDER_TYPE_GDIPLUS_CACHE_END: rc = update_read_draw_gdiplus_cache_end_order(s, &(altsec->draw_gdiplus_cache_end)); break; case ORDER_TYPE_WINDOW: /* This order is handled elsewhere. */ rc = TRUE; break; case ORDER_TYPE_COMPDESK_FIRST: rc = TRUE; break; default: break; } return rc; } static BOOL update_recv_altsec_order(rdpUpdate* update, wStream* s, BYTE flags) { BYTE orderType = flags >>= 2; /* orderType is in higher 6 bits of flags field */ BOOL rc = FALSE; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpAltSecUpdate* altsec = update->altsec; const char* orderName = altsec_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, "Alternate Secondary Drawing Order %s", orderName); if (!check_alt_order_supported(update->log, settings, orderType, orderName)) return FALSE; if (!read_altsec_order(s, orderType, altsec)) return FALSE; switch (orderType) { case ORDER_TYPE_CREATE_OFFSCREEN_BITMAP: IFCALLRET(altsec->CreateOffscreenBitmap, rc, context, &(altsec->create_offscreen_bitmap)); break; case ORDER_TYPE_SWITCH_SURFACE: IFCALLRET(altsec->SwitchSurface, rc, context, &(altsec->switch_surface)); break; case ORDER_TYPE_CREATE_NINE_GRID_BITMAP: IFCALLRET(altsec->CreateNineGridBitmap, rc, context, &(altsec->create_nine_grid_bitmap)); break; case ORDER_TYPE_FRAME_MARKER: IFCALLRET(altsec->FrameMarker, rc, context, &(altsec->frame_marker)); break; case ORDER_TYPE_STREAM_BITMAP_FIRST: IFCALLRET(altsec->StreamBitmapFirst, rc, context, &(altsec->stream_bitmap_first)); break; case ORDER_TYPE_STREAM_BITMAP_NEXT: IFCALLRET(altsec->StreamBitmapNext, rc, context, &(altsec->stream_bitmap_next)); break; case ORDER_TYPE_GDIPLUS_FIRST: IFCALLRET(altsec->DrawGdiPlusFirst, rc, context, &(altsec->draw_gdiplus_first)); break; case ORDER_TYPE_GDIPLUS_NEXT: IFCALLRET(altsec->DrawGdiPlusNext, rc, context, &(altsec->draw_gdiplus_next)); break; case ORDER_TYPE_GDIPLUS_END: IFCALLRET(altsec->DrawGdiPlusEnd, rc, context, &(altsec->draw_gdiplus_end)); break; case ORDER_TYPE_GDIPLUS_CACHE_FIRST: IFCALLRET(altsec->DrawGdiPlusCacheFirst, rc, context, &(altsec->draw_gdiplus_cache_first)); break; case ORDER_TYPE_GDIPLUS_CACHE_NEXT: IFCALLRET(altsec->DrawGdiPlusCacheNext, rc, context, &(altsec->draw_gdiplus_cache_next)); break; case ORDER_TYPE_GDIPLUS_CACHE_END: IFCALLRET(altsec->DrawGdiPlusCacheEnd, rc, context, &(altsec->draw_gdiplus_cache_end)); break; case ORDER_TYPE_WINDOW: rc = update_recv_altsec_window_order(update, s); break; case ORDER_TYPE_COMPDESK_FIRST: rc = TRUE; break; default: break; } if (!rc) { WLog_Print(update->log, WLOG_WARN, "Alternate Secondary Drawing Order %s failed", orderName); } return rc; } BOOL update_recv_order(rdpUpdate* update, wStream* s) { BOOL rc; BYTE controlFlags; if (Stream_GetRemainingLength(s) < 1) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 1"); return FALSE; } Stream_Read_UINT8(s, controlFlags); /* controlFlags (1 byte) */ if (!(controlFlags & ORDER_STANDARD)) rc = update_recv_altsec_order(update, s, controlFlags); else if (controlFlags & ORDER_SECONDARY) rc = update_recv_secondary_order(update, s, controlFlags); else rc = update_recv_primary_order(update, s, controlFlags); if (!rc) WLog_Print(update->log, WLOG_ERROR, "order flags %02" PRIx8 " failed", controlFlags); return rc; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3952_0
crossvul-cpp_data_bad_113_0
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "delta.h" /* maximum hash entry list for the same hash bucket */ #define HASH_LIMIT 64 #define RABIN_SHIFT 23 #define RABIN_WINDOW 16 static const unsigned int T[256] = { 0x00000000, 0xab59b4d1, 0x56b369a2, 0xfdeadd73, 0x063f6795, 0xad66d344, 0x508c0e37, 0xfbd5bae6, 0x0c7ecf2a, 0xa7277bfb, 0x5acda688, 0xf1941259, 0x0a41a8bf, 0xa1181c6e, 0x5cf2c11d, 0xf7ab75cc, 0x18fd9e54, 0xb3a42a85, 0x4e4ef7f6, 0xe5174327, 0x1ec2f9c1, 0xb59b4d10, 0x48719063, 0xe32824b2, 0x1483517e, 0xbfdae5af, 0x423038dc, 0xe9698c0d, 0x12bc36eb, 0xb9e5823a, 0x440f5f49, 0xef56eb98, 0x31fb3ca8, 0x9aa28879, 0x6748550a, 0xcc11e1db, 0x37c45b3d, 0x9c9defec, 0x6177329f, 0xca2e864e, 0x3d85f382, 0x96dc4753, 0x6b369a20, 0xc06f2ef1, 0x3bba9417, 0x90e320c6, 0x6d09fdb5, 0xc6504964, 0x2906a2fc, 0x825f162d, 0x7fb5cb5e, 0xd4ec7f8f, 0x2f39c569, 0x846071b8, 0x798aaccb, 0xd2d3181a, 0x25786dd6, 0x8e21d907, 0x73cb0474, 0xd892b0a5, 0x23470a43, 0x881ebe92, 0x75f463e1, 0xdeadd730, 0x63f67950, 0xc8afcd81, 0x354510f2, 0x9e1ca423, 0x65c91ec5, 0xce90aa14, 0x337a7767, 0x9823c3b6, 0x6f88b67a, 0xc4d102ab, 0x393bdfd8, 0x92626b09, 0x69b7d1ef, 0xc2ee653e, 0x3f04b84d, 0x945d0c9c, 0x7b0be704, 0xd05253d5, 0x2db88ea6, 0x86e13a77, 0x7d348091, 0xd66d3440, 0x2b87e933, 0x80de5de2, 0x7775282e, 0xdc2c9cff, 0x21c6418c, 0x8a9ff55d, 0x714a4fbb, 0xda13fb6a, 0x27f92619, 0x8ca092c8, 0x520d45f8, 0xf954f129, 0x04be2c5a, 0xafe7988b, 0x5432226d, 0xff6b96bc, 0x02814bcf, 0xa9d8ff1e, 0x5e738ad2, 0xf52a3e03, 0x08c0e370, 0xa39957a1, 0x584ced47, 0xf3155996, 0x0eff84e5, 0xa5a63034, 0x4af0dbac, 0xe1a96f7d, 0x1c43b20e, 0xb71a06df, 0x4ccfbc39, 0xe79608e8, 0x1a7cd59b, 0xb125614a, 0x468e1486, 0xedd7a057, 0x103d7d24, 0xbb64c9f5, 0x40b17313, 0xebe8c7c2, 0x16021ab1, 0xbd5bae60, 0x6cb54671, 0xc7ecf2a0, 0x3a062fd3, 0x915f9b02, 0x6a8a21e4, 0xc1d39535, 0x3c394846, 0x9760fc97, 0x60cb895b, 0xcb923d8a, 0x3678e0f9, 0x9d215428, 0x66f4eece, 0xcdad5a1f, 0x3047876c, 0x9b1e33bd, 0x7448d825, 0xdf116cf4, 0x22fbb187, 0x89a20556, 0x7277bfb0, 0xd92e0b61, 0x24c4d612, 0x8f9d62c3, 0x7836170f, 0xd36fa3de, 0x2e857ead, 0x85dcca7c, 0x7e09709a, 0xd550c44b, 0x28ba1938, 0x83e3ade9, 0x5d4e7ad9, 0xf617ce08, 0x0bfd137b, 0xa0a4a7aa, 0x5b711d4c, 0xf028a99d, 0x0dc274ee, 0xa69bc03f, 0x5130b5f3, 0xfa690122, 0x0783dc51, 0xacda6880, 0x570fd266, 0xfc5666b7, 0x01bcbbc4, 0xaae50f15, 0x45b3e48d, 0xeeea505c, 0x13008d2f, 0xb85939fe, 0x438c8318, 0xe8d537c9, 0x153feaba, 0xbe665e6b, 0x49cd2ba7, 0xe2949f76, 0x1f7e4205, 0xb427f6d4, 0x4ff24c32, 0xe4abf8e3, 0x19412590, 0xb2189141, 0x0f433f21, 0xa41a8bf0, 0x59f05683, 0xf2a9e252, 0x097c58b4, 0xa225ec65, 0x5fcf3116, 0xf49685c7, 0x033df00b, 0xa86444da, 0x558e99a9, 0xfed72d78, 0x0502979e, 0xae5b234f, 0x53b1fe3c, 0xf8e84aed, 0x17bea175, 0xbce715a4, 0x410dc8d7, 0xea547c06, 0x1181c6e0, 0xbad87231, 0x4732af42, 0xec6b1b93, 0x1bc06e5f, 0xb099da8e, 0x4d7307fd, 0xe62ab32c, 0x1dff09ca, 0xb6a6bd1b, 0x4b4c6068, 0xe015d4b9, 0x3eb80389, 0x95e1b758, 0x680b6a2b, 0xc352defa, 0x3887641c, 0x93ded0cd, 0x6e340dbe, 0xc56db96f, 0x32c6cca3, 0x999f7872, 0x6475a501, 0xcf2c11d0, 0x34f9ab36, 0x9fa01fe7, 0x624ac294, 0xc9137645, 0x26459ddd, 0x8d1c290c, 0x70f6f47f, 0xdbaf40ae, 0x207afa48, 0x8b234e99, 0x76c993ea, 0xdd90273b, 0x2a3b52f7, 0x8162e626, 0x7c883b55, 0xd7d18f84, 0x2c043562, 0x875d81b3, 0x7ab75cc0, 0xd1eee811 }; static const unsigned int U[256] = { 0x00000000, 0x7eb5200d, 0x5633f4cb, 0x2886d4c6, 0x073e5d47, 0x798b7d4a, 0x510da98c, 0x2fb88981, 0x0e7cba8e, 0x70c99a83, 0x584f4e45, 0x26fa6e48, 0x0942e7c9, 0x77f7c7c4, 0x5f711302, 0x21c4330f, 0x1cf9751c, 0x624c5511, 0x4aca81d7, 0x347fa1da, 0x1bc7285b, 0x65720856, 0x4df4dc90, 0x3341fc9d, 0x1285cf92, 0x6c30ef9f, 0x44b63b59, 0x3a031b54, 0x15bb92d5, 0x6b0eb2d8, 0x4388661e, 0x3d3d4613, 0x39f2ea38, 0x4747ca35, 0x6fc11ef3, 0x11743efe, 0x3eccb77f, 0x40799772, 0x68ff43b4, 0x164a63b9, 0x378e50b6, 0x493b70bb, 0x61bda47d, 0x1f088470, 0x30b00df1, 0x4e052dfc, 0x6683f93a, 0x1836d937, 0x250b9f24, 0x5bbebf29, 0x73386bef, 0x0d8d4be2, 0x2235c263, 0x5c80e26e, 0x740636a8, 0x0ab316a5, 0x2b7725aa, 0x55c205a7, 0x7d44d161, 0x03f1f16c, 0x2c4978ed, 0x52fc58e0, 0x7a7a8c26, 0x04cfac2b, 0x73e5d470, 0x0d50f47d, 0x25d620bb, 0x5b6300b6, 0x74db8937, 0x0a6ea93a, 0x22e87dfc, 0x5c5d5df1, 0x7d996efe, 0x032c4ef3, 0x2baa9a35, 0x551fba38, 0x7aa733b9, 0x041213b4, 0x2c94c772, 0x5221e77f, 0x6f1ca16c, 0x11a98161, 0x392f55a7, 0x479a75aa, 0x6822fc2b, 0x1697dc26, 0x3e1108e0, 0x40a428ed, 0x61601be2, 0x1fd53bef, 0x3753ef29, 0x49e6cf24, 0x665e46a5, 0x18eb66a8, 0x306db26e, 0x4ed89263, 0x4a173e48, 0x34a21e45, 0x1c24ca83, 0x6291ea8e, 0x4d29630f, 0x339c4302, 0x1b1a97c4, 0x65afb7c9, 0x446b84c6, 0x3adea4cb, 0x1258700d, 0x6ced5000, 0x4355d981, 0x3de0f98c, 0x15662d4a, 0x6bd30d47, 0x56ee4b54, 0x285b6b59, 0x00ddbf9f, 0x7e689f92, 0x51d01613, 0x2f65361e, 0x07e3e2d8, 0x7956c2d5, 0x5892f1da, 0x2627d1d7, 0x0ea10511, 0x7014251c, 0x5facac9d, 0x21198c90, 0x099f5856, 0x772a785b, 0x4c921c31, 0x32273c3c, 0x1aa1e8fa, 0x6414c8f7, 0x4bac4176, 0x3519617b, 0x1d9fb5bd, 0x632a95b0, 0x42eea6bf, 0x3c5b86b2, 0x14dd5274, 0x6a687279, 0x45d0fbf8, 0x3b65dbf5, 0x13e30f33, 0x6d562f3e, 0x506b692d, 0x2ede4920, 0x06589de6, 0x78edbdeb, 0x5755346a, 0x29e01467, 0x0166c0a1, 0x7fd3e0ac, 0x5e17d3a3, 0x20a2f3ae, 0x08242768, 0x76910765, 0x59298ee4, 0x279caee9, 0x0f1a7a2f, 0x71af5a22, 0x7560f609, 0x0bd5d604, 0x235302c2, 0x5de622cf, 0x725eab4e, 0x0ceb8b43, 0x246d5f85, 0x5ad87f88, 0x7b1c4c87, 0x05a96c8a, 0x2d2fb84c, 0x539a9841, 0x7c2211c0, 0x029731cd, 0x2a11e50b, 0x54a4c506, 0x69998315, 0x172ca318, 0x3faa77de, 0x411f57d3, 0x6ea7de52, 0x1012fe5f, 0x38942a99, 0x46210a94, 0x67e5399b, 0x19501996, 0x31d6cd50, 0x4f63ed5d, 0x60db64dc, 0x1e6e44d1, 0x36e89017, 0x485db01a, 0x3f77c841, 0x41c2e84c, 0x69443c8a, 0x17f11c87, 0x38499506, 0x46fcb50b, 0x6e7a61cd, 0x10cf41c0, 0x310b72cf, 0x4fbe52c2, 0x67388604, 0x198da609, 0x36352f88, 0x48800f85, 0x6006db43, 0x1eb3fb4e, 0x238ebd5d, 0x5d3b9d50, 0x75bd4996, 0x0b08699b, 0x24b0e01a, 0x5a05c017, 0x728314d1, 0x0c3634dc, 0x2df207d3, 0x534727de, 0x7bc1f318, 0x0574d315, 0x2acc5a94, 0x54797a99, 0x7cffae5f, 0x024a8e52, 0x06852279, 0x78300274, 0x50b6d6b2, 0x2e03f6bf, 0x01bb7f3e, 0x7f0e5f33, 0x57888bf5, 0x293dabf8, 0x08f998f7, 0x764cb8fa, 0x5eca6c3c, 0x207f4c31, 0x0fc7c5b0, 0x7172e5bd, 0x59f4317b, 0x27411176, 0x1a7c5765, 0x64c97768, 0x4c4fa3ae, 0x32fa83a3, 0x1d420a22, 0x63f72a2f, 0x4b71fee9, 0x35c4dee4, 0x1400edeb, 0x6ab5cde6, 0x42331920, 0x3c86392d, 0x133eb0ac, 0x6d8b90a1, 0x450d4467, 0x3bb8646a }; struct index_entry { const unsigned char *ptr; unsigned int val; struct index_entry *next; }; struct git_delta_index { unsigned long memsize; const void *src_buf; size_t src_size; unsigned int hash_mask; struct index_entry *hash[GIT_FLEX_ARRAY]; }; static int lookup_index_alloc( void **out, unsigned long *out_len, size_t entries, size_t hash_count) { size_t entries_len, hash_len, index_len; GITERR_CHECK_ALLOC_MULTIPLY(&entries_len, entries, sizeof(struct index_entry)); GITERR_CHECK_ALLOC_MULTIPLY(&hash_len, hash_count, sizeof(struct index_entry *)); GITERR_CHECK_ALLOC_ADD(&index_len, sizeof(struct git_delta_index), entries_len); GITERR_CHECK_ALLOC_ADD(&index_len, index_len, hash_len); if (!git__is_ulong(index_len)) { giterr_set(GITERR_NOMEMORY, "overly large delta"); return -1; } *out = git__malloc(index_len); GITERR_CHECK_ALLOC(*out); *out_len = index_len; return 0; } int git_delta_index_init( git_delta_index **out, const void *buf, size_t bufsize) { unsigned int i, hsize, hmask, entries, prev_val, *hash_count; const unsigned char *data, *buffer = buf; struct git_delta_index *index; struct index_entry *entry, **hash; void *mem; unsigned long memsize; *out = NULL; if (!buf || !bufsize) return 0; /* Determine index hash size. Note that indexing skips the first byte to allow for optimizing the rabin polynomial initialization in create_delta(). */ entries = (unsigned int)(bufsize - 1) / RABIN_WINDOW; if (bufsize >= 0xffffffffUL) { /* * Current delta format can't encode offsets into * reference buffer with more than 32 bits. */ entries = 0xfffffffeU / RABIN_WINDOW; } hsize = entries / 4; for (i = 4; i < 31 && (1u << i) < hsize; i++); hsize = 1 << i; hmask = hsize - 1; if (lookup_index_alloc(&mem, &memsize, entries, hsize) < 0) return -1; index = mem; mem = index->hash; hash = mem; mem = hash + hsize; entry = mem; index->memsize = memsize; index->src_buf = buf; index->src_size = bufsize; index->hash_mask = hmask; memset(hash, 0, hsize * sizeof(*hash)); /* allocate an array to count hash entries */ hash_count = git__calloc(hsize, sizeof(*hash_count)); if (!hash_count) { git__free(index); return -1; } /* then populate the index */ prev_val = ~0; for (data = buffer + entries * RABIN_WINDOW - RABIN_WINDOW; data >= buffer; data -= RABIN_WINDOW) { unsigned int val = 0; for (i = 1; i <= RABIN_WINDOW; i++) val = ((val << 8) | data[i]) ^ T[val >> RABIN_SHIFT]; if (val == prev_val) { /* keep the lowest of consecutive identical blocks */ entry[-1].ptr = data + RABIN_WINDOW; } else { prev_val = val; i = val & hmask; entry->ptr = data + RABIN_WINDOW; entry->val = val; entry->next = hash[i]; hash[i] = entry++; hash_count[i]++; } } /* * Determine a limit on the number of entries in the same hash * bucket. This guard us against patological data sets causing * really bad hash distribution with most entries in the same hash * bucket that would bring us to O(m*n) computing costs (m and n * corresponding to reference and target buffer sizes). * * Make sure none of the hash buckets has more entries than * we're willing to test. Otherwise we cull the entry list * uniformly to still preserve a good repartition across * the reference buffer. */ for (i = 0; i < hsize; i++) { if (hash_count[i] < HASH_LIMIT) continue; entry = hash[i]; do { struct index_entry *keep = entry; int skip = hash_count[i] / HASH_LIMIT / 2; do { entry = entry->next; } while(--skip && entry); keep->next = entry; } while (entry); } git__free(hash_count); *out = index; return 0; } void git_delta_index_free(git_delta_index *index) { git__free(index); } size_t git_delta_index_size(git_delta_index *index) { assert(index); return index->memsize; } /* * The maximum size for any opcode sequence, including the initial header * plus rabin window plus biggest copy. */ #define MAX_OP_SIZE (5 + 5 + 1 + RABIN_WINDOW + 7) int git_delta_create_from_index( void **out, size_t *out_len, const struct git_delta_index *index, const void *trg_buf, size_t trg_size, size_t max_size) { unsigned int i, bufpos, bufsize, moff, msize, val; int inscnt; const unsigned char *ref_data, *ref_top, *data, *top; unsigned char *buf; *out = NULL; *out_len = 0; if (!trg_buf || !trg_size) return 0; bufpos = 0; bufsize = 8192; if (max_size && bufsize >= max_size) bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1); buf = git__malloc(bufsize); GITERR_CHECK_ALLOC(buf); /* store reference buffer size */ i = index->src_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; /* store target buffer size */ i = trg_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; ref_data = index->src_buf; ref_top = ref_data + index->src_size; data = trg_buf; top = (const unsigned char *) trg_buf + trg_size; bufpos++; val = 0; for (i = 0; i < RABIN_WINDOW && data < top; i++, data++) { buf[bufpos++] = *data; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; } inscnt = i; moff = 0; msize = 0; while (data < top) { if (msize < 4096) { struct index_entry *entry; val ^= U[data[-RABIN_WINDOW]]; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; i = val & index->hash_mask; for (entry = index->hash[i]; entry; entry = entry->next) { const unsigned char *ref = entry->ptr; const unsigned char *src = data; unsigned int ref_size = (unsigned int)(ref_top - ref); if (entry->val != val) continue; if (ref_size > (unsigned int)(top - src)) ref_size = (unsigned int)(top - src); if (ref_size <= msize) break; while (ref_size-- && *src++ == *ref) ref++; if (msize < (unsigned int)(ref - entry->ptr)) { /* this is our best match so far */ msize = (unsigned int)(ref - entry->ptr); moff = (unsigned int)(entry->ptr - ref_data); if (msize >= 4096) /* good enough */ break; } } } if (msize < 4) { if (!inscnt) bufpos++; buf[bufpos++] = *data++; inscnt++; if (inscnt == 0x7f) { buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } msize = 0; } else { unsigned int left; unsigned char *op; if (inscnt) { while (moff && ref_data[moff-1] == data[-1]) { /* we can match one byte back */ msize++; moff--; data--; bufpos--; if (--inscnt) continue; bufpos--; /* remove count slot */ inscnt--; /* make it -1 */ break; } buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } /* A copy op is currently limited to 64KB (pack v2) */ left = (msize < 0x10000) ? 0 : (msize - 0x10000); msize -= left; op = buf + bufpos++; i = 0x80; if (moff & 0x000000ff) buf[bufpos++] = moff >> 0, i |= 0x01; if (moff & 0x0000ff00) buf[bufpos++] = moff >> 8, i |= 0x02; if (moff & 0x00ff0000) buf[bufpos++] = moff >> 16, i |= 0x04; if (moff & 0xff000000) buf[bufpos++] = moff >> 24, i |= 0x08; if (msize & 0x00ff) buf[bufpos++] = msize >> 0, i |= 0x10; if (msize & 0xff00) buf[bufpos++] = msize >> 8, i |= 0x20; *op = i; data += msize; moff += msize; msize = left; if (msize < 4096) { int j; val = 0; for (j = -RABIN_WINDOW; j < 0; j++) val = ((val << 8) | data[j]) ^ T[val >> RABIN_SHIFT]; } } if (bufpos >= bufsize - MAX_OP_SIZE) { void *tmp = buf; bufsize = bufsize * 3 / 2; if (max_size && bufsize >= max_size) bufsize = max_size + MAX_OP_SIZE + 1; if (max_size && bufpos > max_size) break; buf = git__realloc(buf, bufsize); if (!buf) { git__free(tmp); return -1; } } } if (inscnt) buf[bufpos - inscnt - 1] = inscnt; if (max_size && bufpos > max_size) { giterr_set(GITERR_NOMEMORY, "delta would be larger than maximum size"); git__free(buf); return GIT_EBUFS; } *out_len = bufpos; *out = buf; return 0; } /* * Delta application was heavily cribbed from BinaryDelta.java in JGit, which * itself was heavily cribbed from <code>patch-delta.c</code> in the * GIT project. The original delta patching code was written by * Nicolas Pitre <nico@cam.org>. */ static int hdr_sz( size_t *size, const unsigned char **delta, const unsigned char *end) { const unsigned char *d = *delta; size_t r = 0; unsigned int c, shift = 0; do { if (d == end) { giterr_set(GITERR_INVALID, "truncated delta"); return -1; } c = *d++; r |= (c & 0x7f) << shift; shift += 7; } while (c & 0x80); *delta = d; *size = r; return 0; } int git_delta_read_header( size_t *base_out, size_t *result_out, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; if ((hdr_sz(base_out, &delta, delta_end) < 0) || (hdr_sz(result_out, &delta, delta_end) < 0)) return -1; return 0; } #define DELTA_HEADER_BUFFER_LEN 16 int git_delta_read_header_fromstream( size_t *base_sz, size_t *res_sz, git_packfile_stream *stream) { static const size_t buffer_len = DELTA_HEADER_BUFFER_LEN; unsigned char buffer[DELTA_HEADER_BUFFER_LEN]; const unsigned char *delta, *delta_end; size_t len; ssize_t read; len = read = 0; while (len < buffer_len) { read = git_packfile_stream_read(stream, &buffer[len], buffer_len - len); if (read == 0) break; if (read == GIT_EBUFS) continue; len += read; } delta = buffer; delta_end = delta + len; if ((hdr_sz(base_sz, &delta, delta_end) < 0) || (hdr_sz(res_sz, &delta, delta_end) < 0)) return -1; return 0; } int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; if (cmd & 0x01) off = *delta++; if (cmd & 0x02) off |= *delta++ << 8UL; if (cmd & 0x04) off |= *delta++ << 16UL; if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL); if (cmd & 0x10) len = *delta++; if (cmd & 0x20) len |= *delta++ << 8UL; if (cmd & 0x40) len |= *delta++ << 16UL; if (!len) len = 0x10000; if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_113_0
crossvul-cpp_data_good_2644_3
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Ethernet printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ethertype.h" #include "ether.h" const struct tok ethertype_values[] = { { ETHERTYPE_IP, "IPv4" }, { ETHERTYPE_MPLS, "MPLS unicast" }, { ETHERTYPE_MPLS_MULTI, "MPLS multicast" }, { ETHERTYPE_IPV6, "IPv6" }, { ETHERTYPE_8021Q, "802.1Q" }, { ETHERTYPE_8021Q9100, "802.1Q-9100" }, { ETHERTYPE_8021QinQ, "802.1Q-QinQ" }, { ETHERTYPE_8021Q9200, "802.1Q-9200" }, { ETHERTYPE_VMAN, "VMAN" }, { ETHERTYPE_PUP, "PUP" }, { ETHERTYPE_ARP, "ARP"}, { ETHERTYPE_REVARP, "Reverse ARP"}, { ETHERTYPE_NS, "NS" }, { ETHERTYPE_SPRITE, "Sprite" }, { ETHERTYPE_TRAIL, "Trail" }, { ETHERTYPE_MOPDL, "MOP DL" }, { ETHERTYPE_MOPRC, "MOP RC" }, { ETHERTYPE_DN, "DN" }, { ETHERTYPE_LAT, "LAT" }, { ETHERTYPE_SCA, "SCA" }, { ETHERTYPE_TEB, "TEB" }, { ETHERTYPE_LANBRIDGE, "Lanbridge" }, { ETHERTYPE_DECDNS, "DEC DNS" }, { ETHERTYPE_DECDTS, "DEC DTS" }, { ETHERTYPE_VEXP, "VEXP" }, { ETHERTYPE_VPROD, "VPROD" }, { ETHERTYPE_ATALK, "Appletalk" }, { ETHERTYPE_AARP, "Appletalk ARP" }, { ETHERTYPE_IPX, "IPX" }, { ETHERTYPE_PPP, "PPP" }, { ETHERTYPE_MPCP, "MPCP" }, { ETHERTYPE_SLOW, "Slow Protocols" }, { ETHERTYPE_PPPOED, "PPPoE D" }, { ETHERTYPE_PPPOES, "PPPoE S" }, { ETHERTYPE_EAPOL, "EAPOL" }, { ETHERTYPE_RRCP, "RRCP" }, { ETHERTYPE_MS_NLB_HB, "MS NLB heartbeat" }, { ETHERTYPE_JUMBO, "Jumbo" }, { ETHERTYPE_NSH, "NSH" }, { ETHERTYPE_LOOPBACK, "Loopback" }, { ETHERTYPE_ISO, "OSI" }, { ETHERTYPE_GRE_ISO, "GRE-OSI" }, { ETHERTYPE_CFM_OLD, "CFM (old)" }, { ETHERTYPE_CFM, "CFM" }, { ETHERTYPE_IEEE1905_1, "IEEE1905.1" }, { ETHERTYPE_LLDP, "LLDP" }, { ETHERTYPE_TIPC, "TIPC"}, { ETHERTYPE_GEONET_OLD, "GeoNet (old)"}, { ETHERTYPE_GEONET, "GeoNet"}, { ETHERTYPE_CALM_FAST, "CALM FAST"}, { ETHERTYPE_AOE, "AoE" }, { ETHERTYPE_MEDSA, "MEDSA" }, { 0, NULL} }; static inline void ether_hdr_print(netdissect_options *ndo, const u_char *bp, u_int length) { register const struct ether_header *ep; uint16_t length_type; ep = (const struct ether_header *)bp; ND_PRINT((ndo, "%s > %s", etheraddr_string(ndo, ESRC(ep)), etheraddr_string(ndo, EDST(ep)))); length_type = EXTRACT_16BITS(&ep->ether_length_type); if (!ndo->ndo_qflag) { if (length_type <= ETHERMTU) { ND_PRINT((ndo, ", 802.3")); length = length_type; } else ND_PRINT((ndo, ", ethertype %s (0x%04x)", tok2str(ethertype_values,"Unknown", length_type), length_type)); } else { if (length_type <= ETHERMTU) { ND_PRINT((ndo, ", 802.3")); length = length_type; } else ND_PRINT((ndo, ", %s", tok2str(ethertype_values,"Unknown Ethertype (0x%04x)", length_type))); } ND_PRINT((ndo, ", length %u: ", length)); } /* * Print an Ethernet frame. * This might be encapsulated within another frame; we might be passed * a pointer to a function that can print header information for that * frame's protocol, and an argument to pass to that function. * * FIXME: caplen can and should be derived from ndo->ndo_snapend and p. */ u_int ether_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen, void (*print_encap_header)(netdissect_options *ndo, const u_char *), const u_char *encap_header_arg) { const struct ether_header *ep; u_int orig_length; u_short length_type; u_int hdrlen; int llc_hdrlen; struct lladdr_info src, dst; if (caplen < ETHER_HDRLEN) { ND_PRINT((ndo, "[|ether]")); return (caplen); } if (length < ETHER_HDRLEN) { ND_PRINT((ndo, "[|ether]")); return (length); } if (ndo->ndo_eflag) { if (print_encap_header != NULL) (*print_encap_header)(ndo, encap_header_arg); ether_hdr_print(ndo, p, length); } orig_length = length; length -= ETHER_HDRLEN; caplen -= ETHER_HDRLEN; ep = (const struct ether_header *)p; p += ETHER_HDRLEN; hdrlen = ETHER_HDRLEN; src.addr = ESRC(ep); src.addr_string = etheraddr_string; dst.addr = EDST(ep); dst.addr_string = etheraddr_string; length_type = EXTRACT_16BITS(&ep->ether_length_type); recurse: /* * Is it (gag) an 802.3 encapsulation? */ if (length_type <= ETHERMTU) { /* Try to print the LLC-layer header & higher layers */ llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* packet type not known, print raw packet */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } else if (length_type == ETHERTYPE_8021Q || length_type == ETHERTYPE_8021Q9100 || length_type == ETHERTYPE_8021Q9200 || length_type == ETHERTYPE_8021QinQ) { /* * Print VLAN information, and then go back and process * the enclosed type field. */ if (caplen < 4) { ND_PRINT((ndo, "[|vlan]")); return (hdrlen + caplen); } if (length < 4) { ND_PRINT((ndo, "[|vlan]")); return (hdrlen + length); } if (ndo->ndo_eflag) { uint16_t tag = EXTRACT_16BITS(p); ND_PRINT((ndo, "%s, ", ieee8021q_tci_string(tag))); } length_type = EXTRACT_16BITS(p + 2); if (ndo->ndo_eflag && length_type > ETHERMTU) ND_PRINT((ndo, "ethertype %s, ", tok2str(ethertype_values,"0x%04x", length_type))); p += 4; length -= 4; caplen -= 4; hdrlen += 4; goto recurse; } else if (length_type == ETHERTYPE_JUMBO) { /* * Alteon jumbo frames. * See * * http://tools.ietf.org/html/draft-ietf-isis-ext-eth-01 * * which indicates that, following the type field, * there's an LLC header and payload. */ /* Try to print the LLC-layer header & higher layers */ llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst); if (llc_hdrlen < 0) { /* packet type not known, print raw packet */ if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); llc_hdrlen = -llc_hdrlen; } hdrlen += llc_hdrlen; } else { if (ethertype_print(ndo, length_type, p, length, caplen, &src, &dst) == 0) { /* type not known, print raw packet */ if (!ndo->ndo_eflag) { if (print_encap_header != NULL) (*print_encap_header)(ndo, encap_header_arg); ether_hdr_print(ndo, (const u_char *)ep, orig_length); } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); } } return (hdrlen); } /* * This is the top level routine of the printer. 'p' points * to the ether header of the packet, 'h->len' is the length * of the packet off the wire, and 'h->caplen' is the number * of bytes actually captured. */ u_int ether_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { return (ether_print(ndo, p, h->len, h->caplen, NULL, NULL)); } /* * This is the top level routine of the printer. 'p' points * to the ether header of the packet, 'h->len' is the length * of the packet off the wire, and 'h->caplen' is the number * of bytes actually captured. * * This is for DLT_NETANALYZER, which has a 4-byte pseudo-header * before the Ethernet header. */ u_int netanalyzer_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { /* * Fail if we don't have enough data for the Hilscher pseudo-header. */ if (h->len < 4 || h->caplen < 4) { ND_PRINT((ndo, "[|netanalyzer]")); return (h->caplen); } /* Skip the pseudo-header. */ return (4 + ether_print(ndo, p + 4, h->len - 4, h->caplen - 4, NULL, NULL)); } /* * This is the top level routine of the printer. 'p' points * to the ether header of the packet, 'h->len' is the length * of the packet off the wire, and 'h->caplen' is the number * of bytes actually captured. * * This is for DLT_NETANALYZER_TRANSPARENT, which has a 4-byte * pseudo-header, a 7-byte Ethernet preamble, and a 1-byte Ethernet SOF * before the Ethernet header. */ u_int netanalyzer_transparent_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { /* * Fail if we don't have enough data for the Hilscher pseudo-header, * preamble, and SOF. */ if (h->len < 12 || h->caplen < 12) { ND_PRINT((ndo, "[|netanalyzer-transparent]")); return (h->caplen); } /* Skip the pseudo-header, preamble, and SOF. */ return (12 + ether_print(ndo, p + 12, h->len - 12, h->caplen - 12, NULL, NULL)); } /* * Prints the packet payload, given an Ethernet type code for the payload's * protocol. * * Returns non-zero if it can do so, zero if the ethertype is unknown. */ int ethertype_print(netdissect_options *ndo, u_short ether_type, const u_char *p, u_int length, u_int caplen, const struct lladdr_info *src, const struct lladdr_info *dst) { switch (ether_type) { case ETHERTYPE_IP: ip_print(ndo, p, length); return (1); case ETHERTYPE_IPV6: ip6_print(ndo, p, length); return (1); case ETHERTYPE_ARP: case ETHERTYPE_REVARP: arp_print(ndo, p, length, caplen); return (1); case ETHERTYPE_DN: decnet_print(ndo, p, length, caplen); return (1); case ETHERTYPE_ATALK: if (ndo->ndo_vflag) ND_PRINT((ndo, "et1 ")); atalk_print(ndo, p, length); return (1); case ETHERTYPE_AARP: aarp_print(ndo, p, length); return (1); case ETHERTYPE_IPX: ND_PRINT((ndo, "(NOV-ETHII) ")); ipx_print(ndo, p, length); return (1); case ETHERTYPE_ISO: if (length == 0 || caplen == 0) { ND_PRINT((ndo, " [|osi]")); return (1); } isoclns_print(ndo, p + 1, length - 1); return(1); case ETHERTYPE_PPPOED: case ETHERTYPE_PPPOES: case ETHERTYPE_PPPOED2: case ETHERTYPE_PPPOES2: pppoe_print(ndo, p, length); return (1); case ETHERTYPE_EAPOL: eap_print(ndo, p, length); return (1); case ETHERTYPE_RRCP: rrcp_print(ndo, p, length, src, dst); return (1); case ETHERTYPE_PPP: if (length) { ND_PRINT((ndo, ": ")); ppp_print(ndo, p, length); } return (1); case ETHERTYPE_MPCP: mpcp_print(ndo, p, length); return (1); case ETHERTYPE_SLOW: slow_print(ndo, p, length); return (1); case ETHERTYPE_CFM: case ETHERTYPE_CFM_OLD: cfm_print(ndo, p, length); return (1); case ETHERTYPE_LLDP: lldp_print(ndo, p, length); return (1); case ETHERTYPE_NSH: nsh_print(ndo, p, length); return (1); case ETHERTYPE_LOOPBACK: loopback_print(ndo, p, length); return (1); case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); return (1); case ETHERTYPE_TIPC: tipc_print(ndo, p, length, caplen); return (1); case ETHERTYPE_MS_NLB_HB: msnlb_print(ndo, p); return (1); case ETHERTYPE_GEONET_OLD: case ETHERTYPE_GEONET: geonet_print(ndo, p, length, src); return (1); case ETHERTYPE_CALM_FAST: calm_fast_print(ndo, p, length, src); return (1); case ETHERTYPE_AOE: aoe_print(ndo, p, length); return (1); case ETHERTYPE_MEDSA: medsa_print(ndo, p, length, caplen, src, dst); return (1); case ETHERTYPE_LAT: case ETHERTYPE_SCA: case ETHERTYPE_MOPRC: case ETHERTYPE_MOPDL: case ETHERTYPE_IEEE1905_1: /* default_print for now */ default: return (0); } } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_3
crossvul-cpp_data_bad_147_0
/* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */ #if 0 http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set #endif #include <string.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_asm.h> #include <r_anal.h> static RDESContext desctx; typedef struct _cpu_const_tag { const char *const key; ut8 type; ut32 value; ut8 size; } CPU_CONST; #define CPU_CONST_NONE 0 #define CPU_CONST_PARAM 1 #define CPU_CONST_REG 2 typedef struct _cpu_model_tag { const char *const model; int pc; char *inherit; struct _cpu_model_tag *inherit_cpu_p; CPU_CONST *consts[10]; } CPU_MODEL; typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu); typedef struct _opcodes_tag_ { const char *const name; int mask; int selector; inst_handler_t handler; int cycles; int size; ut64 type; } OPCODE_DESC; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu); #define CPU_MODEL_DECL(model, pc, consts) \ { \ model, \ pc, \ consts \ } #define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits)))) #define CPU_PC_MASK(cpu) MASK((cpu)->pc) #define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0)) #define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu) #define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T } #define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK } #define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu) #define INST_INVALID { *fail = 1; return; } #define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } } #define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__) #define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s)) // Following IO definitions are valid for: // ATmega8 // ATmega88 CPU_CONST cpu_reg_common[] = { { "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) }, { "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) }, { "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) }, { "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_common[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_xmega128a4u[] = { { "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_5_bits[] = { { "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_7_bits[] = { { "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_MODEL cpu_models[] = { { .model = "ATmega640", .pc = 15, .consts = { cpu_reg_common, cpu_memsize_m640_m1280m_m1281_m2560_m2561, cpu_pagesize_7_bits, NULL }, }, { .model = "ATxmega128a4u", .pc = 17, .consts = { cpu_reg_common, cpu_memsize_xmega128a4u, cpu_pagesize_7_bits, NULL } }, { .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega88", .pc = 8, .inherit = "ATmega8" }, // CPU_MODEL_DECL ("ATmega168", 13, 512, 512), // last model is the default AVR - ATmega8 forever! { .model = "ATmega8", .pc = 13, .consts = { cpu_reg_common, cpu_memsize_common, cpu_pagesize_5_bits, NULL } }, }; static CPU_MODEL *get_cpu_model(char *model); static CPU_MODEL *__get_cpu_model_recursive(char *model) { CPU_MODEL *cpu = NULL; for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) { if (!strcasecmp (model, cpu->model)) { break; } } // fix inheritance tree if (cpu->inherit && !cpu->inherit_cpu_p) { cpu->inherit_cpu_p = get_cpu_model (cpu->inherit); if (!cpu->inherit_cpu_p) { eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit); } } return cpu; } static CPU_MODEL *get_cpu_model(char *model) { static CPU_MODEL *cpu = NULL; // cached value? if (cpu && !strcasecmp (model, cpu->model)) return cpu; // do the real search cpu = __get_cpu_model_recursive (model); return cpu; } static ut32 const_get_value(CPU_CONST *c) { return c ? MASK (c->size * 8) & c->value : 0; } static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem->key; citem++) { if (!strcmp (c, citem->key) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_name (cpu->inherit_cpu_p, type, c); eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c); return NULL; } static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) { char *t = r_anal_esil_pop (esil); if (!t || !r_anal_esil_get_parm (esil, t, v)) { free (t); return false; } free (t); return true; } static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem && citem->key; citem++) { if (citem->value == (MASK (citem->size * 8) & v) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_value (cpu->inherit_cpu_p, type, v); return NULL; } static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) { RStrBuf *r = r_strbuf_new (""); CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port); if (c != NULL) { r_strbuf_set (r, c->key); if (write) { r_strbuf_append (r, ",="); } } else { r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : ""); } return r; } static void __generic_bitop_flags(RAnalOp *op) { ESIL_A ("0,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S } static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) { if (ireg) { // preincrement index register if (prepostdec < 0) { ESIL_A ("1,%c,-,%c,=,", ireg, ireg); } // set register index address ESIL_A ("%c,", ireg); // add offset if (offset != 0) { ESIL_A ("%d,+,", offset); } } else { ESIL_A ("%d,", offset); } if (use_ramp) { ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd'); } // set SRAM base address ESIL_A ("_%s,+,", mem); // read/write from SRAM ESIL_A ("%s[1],", st ? "=" : ""); // postincrement index register if (ireg && prepostdec > 0) { ESIL_A ("1,%c,+,%c,=,", ireg, ireg); } } static void __generic_pop(RAnalOp *op, int sz) { if (sz > 1) { ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1) ESIL_A ("[%d],", sz); // read value ESIL_A ("%d,sp,+=,", sz); // sp += item_size } else { ESIL_A ("1,sp,+=," // increment stack pointer "sp,_ram,+,[1],"); // load SRAM[sp] } } static void __generic_push(RAnalOp *op, int sz) { ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp) if (sz > 1) { ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz' } ESIL_A ("=[%d],", sz); // store value in stack ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer } static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) { __generic_add_update_flags(op, 'r', d, 'r', r); } static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&," "%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N if (carry) ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z else ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&," "%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) { __generic_sub_update_flags(op, 'r', d, 'r', r, carry); } static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) { __generic_sub_update_flags(op, 'r', d, 'k', k, carry); } INST_HANDLER (adc) { // ADC Rd, Rr // ROL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (add) { // ADD Rd, Rr // LSL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr // FLAGS: ESIL_A ("r%d,0x80,&,!," // V "0,RPICK,0x8000,&,!,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!,!," // C "0,RPICK,0x8000,&,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (and) { // AND Rd, Rr // TST Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (andi) { // ANDI Rd, K // CBR Rd, K (= ANDI Rd, 1-K) if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f); op->val = k; ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (asr) { // ASR Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7 ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (bclr) { // BCLR s // CLC // CLH // CLI // CLN // CLR // CLS // CLT // CLV // CLZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s); } INST_HANDLER (bld) { // BLD Rd, b if (len < 2) { return; } int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf); int b = buf[0] & 0x7; ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0 ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b } INST_HANDLER (brbx) { // BRBC s, k // BRBS s, k // BRBC/S 0: BRCC BRCS // BRSH BRLO // BRBC/S 1: BREQ BRNE // BRBC/S 2: BRPL BRMI // BRBC/S 3: BRVC BRVS // BRBC/S 4: BRGE BRLT // BRBC/S 5: BRHC BRHS // BRBC/S 6: BRTC BRTS // BRBC/S 7: BRID BRIE int s = buf[0] & 0x7; op->jump = op->addr + ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2)) | (buf[1] & 0x2 ? ~((int) 0x7f) : 0)) + 2; op->fail = op->addr + op->size; op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s) ESIL_A (buf[1] & 0x4 ? "!," // BRBC => branch if cleared : "!,!,"); // BRBS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (break) { // BREAK ESIL_A ("BREAK"); } INST_HANDLER (bset) { // BSET s // SEC // SEH // SEI // SEN // SER // SES // SET // SEV // SEZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("%d,1,<<,sreg,|=,", s); } INST_HANDLER (bst) { // BST Rd, b if (len < 2) { return; } ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r buf[0] & 0x7); // b } INST_HANDLER (call) { // CALL k if (len < 4) { return; } op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->fail = op->addr + op->size; op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // AT*mega optimizes one cycle } ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (cbi) { // CBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->family = R_ANAL_OP_FAMILY_IO; op->type2 = 1; op->val = a; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (com) { // COM Rd int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd // FLAGS: ESIL_A ("0,cf,=,"); // C __generic_bitop_flags (op); // ...rest... } INST_HANDLER (cp) { // CP Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) } INST_HANDLER (cpc) { // CPC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) } INST_HANDLER (cpi) { // CPI Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); ESIL_A ("%d,r%d,-,", k, d); // Rd - k __generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry) } INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op = {0}; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (dec) { // DEC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("-1,r%d,+,", d); // --Rd // FLAGS: ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (des) { // DES k if (desctx.round < 16) { //DES op->type = R_ANAL_OP_TYPE_CRYPTO; op->cycles = 1; //redo this r_strbuf_setf (&op->esil, "%d,des", desctx.round); } } INST_HANDLER (eijmp) { // EIJMP ut64 z, eind; // read z and eind for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = ((eind << 16) + z) << 1; // jump ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,"); // cycles op->cycles = 2; } INST_HANDLER (eicall) { // EICALL // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard EIJMP INST_CALL (eijmp); // fix cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4; } INST_HANDLER (elpm) { // ELPM // ELPM Rd // ELPM Rd, Z+ int d = ((buf[1] & 0xfe) == 0x90) ? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd : 0; // R0 ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z ESIL_A ("r%d,=,", d); // Rd = [1] if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) { ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z) } } INST_HANDLER (eor) { // EOR Rd, Rr // CLR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (fmul) { // FMUL Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmuls) { // FMULS Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmulsu) { // FMULSU Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d", r); // unsigned Rr ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (ijmp) { // IJMP k ut64 z; // read z for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = z << 1; op->cycles = 2; ESIL_A ("1,z,<<,pc,=,"); // jump! } INST_HANDLER (icall) { // ICALL k // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard IJMP INST_CALL (ijmp); // fix cycles if (!STR_BEGINS (cpu->model, "ATxmega")) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (in) { // IN Rd, A int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_src = __generic_io_dest (a, 0, cpu); op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r); r_strbuf_free (io_src); } INST_HANDLER (inc) { // INC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("1,r%d,+,", d); // ++Rd // FLAGS: ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (jmp) { // JMP k op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->cycles = 3; ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (lac) { // LAC Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (las) { // LAS Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,|,", d); // 0: (Z) | Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (lat) { // LAT Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (ld) { // LD Rd, X // LD Rd, X+ // LD Rd, -X // read memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post incremented : 0, // no increment 0, // offset always 0 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[0] & 0x3) == 0 ? 2 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z // LD Rd, Y+ LD Rd, Z+ // LD Rd, -Y LD Rd, -Z // LD Rd, Y+q LD Rd, Z+q // calculate offset (this value only has sense in some opcodes, // but we are optimistic and we calculate it always) int offset = (buf[1] & 0x20) | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7); // read memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? offset : 0, // offset or not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[1] & 0x10) == 0 ? (!offset ? 1 : 3) // LDD : (buf[0] & 0x3) == 0 ? 1 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldi) { // LDI Rd, K int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4); int d = ((buf[0] >> 4) & 0xf) + 16; op->val = k; ESIL_A ("0x%x,r%d,=,", k, d); } INST_HANDLER (lds) { // LDS Rd, k if (len < 4) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; // load value from RAMPD:k __generic_ld_st (op, "ram", 0, 1, 0, k, 0); ESIL_A ("r%d,=,", d); } INST_HANDLER (sts) { // STS k, Rr int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } #if 0 INST_HANDLER (lds16) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x30) | ((buf[1] << 4) & 0x40) | (~(buf[1] << 4) & 0x80); op->ptr = k; // load value from @k __generic_ld_st (op, "ram", 0, 0, 0, k, 0); ESIL_A ("r%d,=,", d); } #endif INST_HANDLER (lpm) { // LPM // LPM Rd, Z // LPM Rd, Z+ ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]); // read program memory __generic_ld_st ( op, "prog", 'z', // index register Y/Z 1, // use RAMP* registers (ins & 0xfe0f) == 0x9005 ? 1 // post incremented : 0, // no increment 0, // not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", (ins == 0x95c8) ? 0 // LPM (r0) : ((buf[0] >> 4) & 0xf) // LPM Rd | ((buf[1] & 0x1) << 4)); } INST_HANDLER (lsr) { // LSR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1) ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (mov) { // MOV Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,=,", r, d); } INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr int d = (buf[0] & 0xf0) >> 3; int r = (buf[0] & 0x0f) << 1; ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1); } INST_HANDLER (mul) { // MUL Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (muls) { // MULS Rd, Rr int d = (buf[0] >> 4 & 0x0f) + 16; int r = (buf[0] & 0x0f) + 16; ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (mulsu) { // MULSU Rd, Rr int d = (buf[0] >> 4 & 0x07) + 16; int r = (buf[0] & 0x07) + 16; ESIL_A ("r%d,", r); // unsigned Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (neg) { // NEG Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd) ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N ESIL_A ("DUP,!,zf,=,"); // Z ESIL_A ("DUP,!,!,cf,=,"); // C ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (nop) { // NOP ESIL_A (",,"); } INST_HANDLER (or) { // OR Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (ori) { // ORI Rd, K // SBR Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); op->val = k; ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (out) { // OUT A, Rr int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_dst = __generic_io_dest (a, 1, cpu); op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst)); r_strbuf_free (io_dst); } INST_HANDLER (pop) { // POP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); __generic_pop (op, 1); ESIL_A ("r%d,=,", d); // store in Rd } INST_HANDLER (push) { // PUSH Rr int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("r%d,", r); // load Rr __generic_push (op, 1); // push it into stack // cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 1 // AT*mega optimizes one cycle : 2; } INST_HANDLER (rcall) { // RCALL k // target address op->jump = (op->addr + (((((buf[1] & 0xf) << 8) | buf[0]) << 1) | (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0))) + 2) & CPU_PC_MASK (cpu); op->fail = op->addr + op->size; // esil ESIL_A ("pc,"); // esil already points to next // instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! // cycles if (!strncasecmp (cpu->model, "ATtiny", 6)) { op->cycles = 4; // ATtiny is always slow } else { // PC size decides required runtime! op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // ATxmega optimizes one cycle } } } INST_HANDLER (ret) { // RET op->eob = true; // esil __generic_pop (op, CPU_PC_SIZE (cpu)); ESIL_A ("pc,=,"); // jump! // cycles if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit op->cycles++; // (i.e. a 22-bit bus), add one extra cycle } } INST_HANDLER (reti) { // RETI //XXX: There are not privileged instructions in ATMEL/AVR op->family = R_ANAL_OP_FAMILY_PRIV; // first perform a standard 'ret' INST_CALL (ret); // RETI: The I-bit is cleared by hardware after an interrupt // has occurred, and is set by the RETI instruction to enable // subsequent interrupts ESIL_A ("1,if,=,"); } INST_HANDLER (rjmp) { // RJMP k op->jump = (op->addr #ifdef _MSC_VER #pragma message ("anal_avr.c: WARNING: Probably broken on windows") + ((((( buf[1] & 0xf) << 9) | (buf[0] << 1))) | (buf[1] & 0x8 ? ~(0x1fff) : 0)) #else + ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1))) | (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0)) #endif + 2) & CPU_PC_MASK (cpu); ESIL_A ("%"PFMT64d",pc,=,", op->jump); } INST_HANDLER (ror) { // ROR Rd int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7) ESIL_A ("r%d,1,&,cf,=,", d); // C ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (sbc) { // SBC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C) __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbci) { // SBCI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sub) { // SUB Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k) __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (subi) { // SUBI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbi) { // SBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (sbix) { // SBIC A, b // SBIS A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RAnalOp next_op; RStrBuf *io_port; op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBIC => branch if 0 : "!,!,"); // SBIS => branch if 1 ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp r_strbuf_free (io_port); } INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr) ESIL_A ("r%d,0x80,&,!,!," // V "0,RPICK,0x8000,&,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!," // C "0,RPICK,0x8000,&,!,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (sbrx) { // SBRC Rr, b // SBRS Rr, b int b = buf[0] & 0x7; int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4); RAnalOp next_op = {0}; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBRC => branch if cleared : "!,!,"); // SBRS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (sleep) { // SLEEP ESIL_A ("BREAK"); } INST_HANDLER (spm) { // SPM Z+ ut64 spmcsr; // read SPM Control Register (SPMCR) r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL); // clear SPMCSR ESIL_A ("0x7c,spmcsr,&=,"); // decide action depending on the old value of SPMCSR switch (spmcsr & 0x7f) { case 0x03: // PAGE ERASE // invoke SPM_CLEAR_PAGE (erases target page writing // the 0xff value ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_ERASE,"); // do magic break; case 0x01: // FILL TEMPORARY BUFFER ESIL_A ("r1,r0,"); // push data ESIL_A ("z,"); // push target address ESIL_A ("SPM_PAGE_FILL,"); // do magic break; case 0x05: // WRITE PAGE ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_WRITE,"); // do magic break; default: eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n", (unsigned int) spmcsr); } op->cycles = 1; // This is truly false. Datasheets do not publish how // many cycles this instruction uses in all its // operation modes and I am pretty sure that this value // can vary substantially from one MCU type to another. // So... one cycle is fine. } INST_HANDLER (st) { // ST X, Rr // ST X+, Rr // ST -X, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post increment : 0, // no increment 0, // offset always 0 1); // store operation (st) // // cycles // op->cycles = buf[0] & 0x3 == 0 // ? 2 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (std) { // ST Y, Rr ST Z, Rr // ST Y+, Rr ST Z+, Rr // ST -Y, Rr ST -Z, Rr // ST Y+q, Rr ST Z+q, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? (buf[1] & 0x20) // offset | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7) : 0, // no offset 1); // load operation (!st) // // cycles // op->cycles = // buf[1] & 0x1 == 0 // ? !(offset ? 1 : 3) // LDD // : buf[0] & 0x3 == 0 // ? 1 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (swap) { // SWAP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf ESIL_A ("|,", d); // S[0] | S[1] ESIL_A ("r%d,=,", d); // Rd = result } OPCODE_DESC opcodes[] = { // op mask select cycles size type INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ... INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+ INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+ INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+ INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+ INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A //INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr INST_LAST }; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; if (len < 2) { return NULL; } ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, ""); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, "1,$"); return NULL; } static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) { CPU_MODEL *cpu; ut64 offset; // init op if (!op) { return 2; } // select cpu info cpu = get_cpu_model (anal->cpu); // set memory layout registers if (anal->esil) { offset = 0; r_anal_esil_reg_write (anal->esil, "_prog", offset); offset += (1 << cpu->pc); r_anal_esil_reg_write (anal->esil, "_io", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start")); r_anal_esil_reg_write (anal->esil, "_sram", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size")); r_anal_esil_reg_write (anal->esil, "_eeprom", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size")); r_anal_esil_reg_write (anal->esil, "_page", offset); } // process opcode avr_op_analyze (anal, op, addr, buf, len, cpu); return op->size; } static int avr_custom_des (RAnalEsil *esil) { ut64 key, encrypt, text,des_round; ut32 key_lo, key_hi, buf_lo, buf_hi; if (!esil || !esil->anal || !esil->anal->reg) { return false; } if (!__esil_pop_argument (esil, &des_round)) { return false; } r_anal_esil_reg_read (esil, "hf", &encrypt, NULL); r_anal_esil_reg_read (esil, "deskey", &key, NULL); r_anal_esil_reg_read (esil, "text", &text, NULL); key_lo = key & UT32_MAX; key_hi = key >> 32; buf_lo = text & UT32_MAX; buf_hi = text >> 32; if (des_round != desctx.round) { desctx.round = des_round; } if (!desctx.round) { int i; //generating all round keys r_des_permute_key (&key_lo, &key_hi); for (i = 0; i < 16; i++) { r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi); } r_des_permute_block0 (&buf_lo, &buf_hi); } if (encrypt) { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]); } else { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]); } if (desctx.round == 15) { r_des_permute_block1 (&buf_hi, &buf_lo); desctx.round = 0; } else { desctx.round++; } r_anal_esil_reg_write (esil, "text", text); return true; } // ESIL operation SPM_PAGE_ERASE static int avr_custom_spm_page_erase(RAnalEsil *esil) { CPU_MODEL *cpu; ut8 c; ut64 addr, page_size_bits, i; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument(esil, &addr)) { return false; } // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align base address to page_size_bits addr &= ~(MASK (page_size_bits)); // perform erase //eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); c = 0xff; for (i = 0; i < (1ULL << page_size_bits); i++) { r_anal_esil_mem_write ( esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1); } return true; } // ESIL operation SPM_PAGE_FILL static int avr_custom_spm_page_fill(RAnalEsil *esil) { CPU_MODEL *cpu; ut64 addr, page_size_bits, i; ut8 r0, r1; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address, r0, r1 if (!__esil_pop_argument(esil, &addr)) { return false; } if (!__esil_pop_argument (esil, &i)) { return false; } r0 = i; if (!__esil_pop_argument (esil, &i)) { return false; } r1 = i; // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align and crop base address addr &= (MASK (page_size_bits) ^ 1); // perform write to temporary page //eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr); r_anal_esil_mem_write (esil, addr++, &r0, 1); r_anal_esil_mem_write (esil, addr++, &r1, 1); return true; } // ESIL operation SPM_PAGE_WRITE static int avr_custom_spm_page_write(RAnalEsil *esil) { CPU_MODEL *cpu; char *t = NULL; ut64 addr, page_size_bits, tmp_page; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument (esil, &addr)) { return false; } // get details about current MCU and fix input address and base address // of the internal temporary page cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL); // align base address to page_size_bits addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu)); // perform writing //eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); if (!(t = malloc (1 << page_size_bits))) { eprintf ("Cannot alloc a buffer for copying the temporary page.\n"); return false; } r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits); r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits); return true; } static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) { CPU_MODEL *cpu; if (!esil || !esil->anal) { return 0; } // select cpu info cpu = get_cpu_model (esil->anal->cpu); // crop registers and force certain values if (!strcmp (name, "pc")) { *val &= CPU_PC_MASK (cpu); } else if (!strcmp (name, "pcl")) { if (cpu->pc < 8) { *val &= MASK (8); } } else if (!strcmp (name, "pch")) { *val = cpu->pc > 8 ? *val & MASK (cpu->pc - 8) : 0; } return 0; } static int esil_avr_init(RAnalEsil *esil) { if (!esil) { return false; } desctx.round = 0; r_anal_esil_set_op (esil, "des", avr_custom_des); r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase); r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill); r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write); esil->cb.hook_reg_write = esil_avr_hook_reg_write; return true; } static int esil_avr_fini(RAnalEsil *esil) { return true; } static int set_reg_profile(RAnal *anal) { const char *p = "=PC pcl\n" "=SP sp\n" // explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html // and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file "=A0 r25\n" "=A1 r24\n" "=A2 r23\n" "=A3 r22\n" "=R0 r24\n" #if 0 PC: 16- or 22-bit program counter SP: 8- or 16-bit stack pointer SREG: 8-bit status register RAMPX, RAMPY, RAMPZ, RAMPD and EIND: #endif // 8bit registers x 32 "gpr r0 .8 0 0\n" "gpr r1 .8 1 0\n" "gpr r2 .8 2 0\n" "gpr r3 .8 3 0\n" "gpr r4 .8 4 0\n" "gpr r5 .8 5 0\n" "gpr r6 .8 6 0\n" "gpr r7 .8 7 0\n" "gpr text .64 0 0\n" "gpr r8 .8 8 0\n" "gpr r9 .8 9 0\n" "gpr r10 .8 10 0\n" "gpr r11 .8 11 0\n" "gpr r12 .8 12 0\n" "gpr r13 .8 13 0\n" "gpr r14 .8 14 0\n" "gpr r15 .8 15 0\n" "gpr deskey .64 8 0\n" "gpr r16 .8 16 0\n" "gpr r17 .8 17 0\n" "gpr r18 .8 18 0\n" "gpr r19 .8 19 0\n" "gpr r20 .8 20 0\n" "gpr r21 .8 21 0\n" "gpr r22 .8 22 0\n" "gpr r23 .8 23 0\n" "gpr r24 .8 24 0\n" "gpr r25 .8 25 0\n" "gpr r26 .8 26 0\n" "gpr r27 .8 27 0\n" "gpr r28 .8 28 0\n" "gpr r29 .8 29 0\n" "gpr r30 .8 30 0\n" "gpr r31 .8 31 0\n" // 16 bit overlapped registers for 16 bit math "gpr r17:r16 .16 16 0\n" "gpr r19:r18 .16 18 0\n" "gpr r21:r20 .16 20 0\n" "gpr r23:r22 .16 22 0\n" "gpr r25:r24 .16 24 0\n" "gpr r27:r26 .16 26 0\n" "gpr r29:r28 .16 28 0\n" "gpr r31:r30 .16 30 0\n" // 16 bit overlapped registers for memory addressing "gpr x .16 26 0\n" "gpr y .16 28 0\n" "gpr z .16 30 0\n" // program counter // NOTE: program counter size in AVR depends on the CPU model. It seems that // the PC may range from 16 bits to 22 bits. "gpr pc .32 32 0\n" "gpr pcl .16 32 0\n" "gpr pch .16 34 0\n" // special purpose registers "gpr sp .16 36 0\n" "gpr spl .8 36 0\n" "gpr sph .8 37 0\n" // status bit register (SREG) "gpr sreg .8 38 0\n" "gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts. "gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero. "gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result. "gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow. "gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison. "gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic. "gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit. "gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled. // 8bit segment registers to be added to X, Y, Z to get 24bit offsets "gpr rampx .8 39 0\n" "gpr rampy .8 40 0\n" "gpr rampz .8 41 0\n" "gpr rampd .8 42 0\n" "gpr eind .8 43 0\n" // memory mapping emulator registers // _prog // the program flash. It has its own address space. // _ram // _io // start of the data addres space. It is the same address of IO, // because IO is the first memory space addressable in the AVR. // _sram // start of the SRAM (this offset depends on IO size, and it is // inside the _ram address space) // _eeprom // this is another address space, outside ram and flash // _page // this is the temporary page used by the SPM instruction. This // memory is not directly addressable and it is used internally by // the CPU when autoflashing. "gpr _prog .32 44 0\n" "gpr _page .32 48 0\n" "gpr _eeprom .32 52 0\n" "gpr _ram .32 56 0\n" "gpr _io .32 56 0\n" "gpr _sram .32 60 0\n" // other important MCU registers // spmcsr/spmcr // Store Program Memory Control and Status Register (SPMCSR) "gpr spmcsr .8 64 0\n" ; return r_reg_set_profile_string (anal->reg, p); } static int archinfo(RAnal *anal, int q) { if (q == R_ANAL_ARCHINFO_ALIGN) return 2; if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE) return 4; if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE) return 2; return 2; // XXX } static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) { RAnalOp *op = NULL; ut8 *ret = NULL; int idx; if (!(op = r_anal_op_new ())) { return NULL; } if (!(ret = malloc (size))) { r_anal_op_free (op); return NULL; } memset (ret, 0xff, size); CPU_MODEL *cpu = get_cpu_model (anal->cpu); for (idx = 0; idx + 1 < size; idx += op->size) { OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu); if (op->size < 1) { break; } if (!opcode_desc) { // invalid instruction continue; } // the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching // (things like memory offsets or jump addresses) if (op->size == 4) { ret[idx + 2] = 0; ret[idx + 3] = 0; } if (op->ptr != UT64_MAX || op->jump != UT64_MAX) { ret[idx] = opcode_desc->mask; ret[idx + 1] = opcode_desc->mask >> 8; } } r_anal_op_free (op); return ret; } RAnalPlugin r_anal_plugin_avr = { .name = "avr", .desc = "AVR code analysis plugin", .license = "LGPL3", .arch = "avr", .esil = true, .archinfo = archinfo, .bits = 8 | 16, // 24 big regs conflicts .op = &avr_op, .set_reg_profile = &set_reg_profile, .esil_init = esil_avr_init, .esil_fini = esil_avr_fini, .anal_mask = anal_mask_avr, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_ANAL, .data = &r_anal_plugin_avr, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_147_0
crossvul-cpp_data_bad_977_0
/* * Copyright © 2001-2011 Stéphane Raimbault <stephane.raimbault@gmail.com> * * SPDX-License-Identifier: LGPL-2.1+ * * This library implements the Modbus protocol. * http://libmodbus.org/ */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <errno.h> #include <limits.h> #include <time.h> #ifndef _MSC_VER #include <unistd.h> #endif #include <config.h> #include "modbus.h" #include "modbus-private.h" /* Internal use */ #define MSG_LENGTH_UNDEFINED -1 /* Exported version */ const unsigned int libmodbus_version_major = LIBMODBUS_VERSION_MAJOR; const unsigned int libmodbus_version_minor = LIBMODBUS_VERSION_MINOR; const unsigned int libmodbus_version_micro = LIBMODBUS_VERSION_MICRO; /* Max between RTU and TCP max adu length (so TCP) */ #define MAX_MESSAGE_LENGTH 260 /* 3 steps are used to parse the query */ typedef enum { _STEP_FUNCTION, _STEP_META, _STEP_DATA } _step_t; const char *modbus_strerror(int errnum) { switch (errnum) { case EMBXILFUN: return "Illegal function"; case EMBXILADD: return "Illegal data address"; case EMBXILVAL: return "Illegal data value"; case EMBXSFAIL: return "Slave device or server failure"; case EMBXACK: return "Acknowledge"; case EMBXSBUSY: return "Slave device or server is busy"; case EMBXNACK: return "Negative acknowledge"; case EMBXMEMPAR: return "Memory parity error"; case EMBXGPATH: return "Gateway path unavailable"; case EMBXGTAR: return "Target device failed to respond"; case EMBBADCRC: return "Invalid CRC"; case EMBBADDATA: return "Invalid data"; case EMBBADEXC: return "Invalid exception code"; case EMBMDATA: return "Too many data"; case EMBBADSLAVE: return "Response not from requested slave"; default: return strerror(errnum); } } void _error_print(modbus_t *ctx, const char *context) { if (ctx->debug) { fprintf(stderr, "ERROR %s", modbus_strerror(errno)); if (context != NULL) { fprintf(stderr, ": %s\n", context); } else { fprintf(stderr, "\n"); } } } static void _sleep_response_timeout(modbus_t *ctx) { /* Response timeout is always positive */ #ifdef _WIN32 /* usleep doesn't exist on Windows */ Sleep((ctx->response_timeout.tv_sec * 1000) + (ctx->response_timeout.tv_usec / 1000)); #else /* usleep source code */ struct timespec request, remaining; request.tv_sec = ctx->response_timeout.tv_sec; request.tv_nsec = ((long int)ctx->response_timeout.tv_usec) * 1000; while (nanosleep(&request, &remaining) == -1 && errno == EINTR) { request = remaining; } #endif } int modbus_flush(modbus_t *ctx) { int rc; if (ctx == NULL) { errno = EINVAL; return -1; } rc = ctx->backend->flush(ctx); if (rc != -1 && ctx->debug) { /* Not all backends are able to return the number of bytes flushed */ printf("Bytes flushed (%d)\n", rc); } return rc; } /* Computes the length of the expected response */ static unsigned int compute_response_length_from_request(modbus_t *ctx, uint8_t *req) { int length; const int offset = ctx->backend->header_length; switch (req[offset]) { case MODBUS_FC_READ_COILS: case MODBUS_FC_READ_DISCRETE_INPUTS: { /* Header + nb values (code from write_bits) */ int nb = (req[offset + 3] << 8) | req[offset + 4]; length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0); } break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: case MODBUS_FC_READ_HOLDING_REGISTERS: case MODBUS_FC_READ_INPUT_REGISTERS: /* Header + 2 * nb values */ length = 2 + 2 * (req[offset + 3] << 8 | req[offset + 4]); break; case MODBUS_FC_READ_EXCEPTION_STATUS: length = 3; break; case MODBUS_FC_REPORT_SLAVE_ID: /* The response is device specific (the header provides the length) */ return MSG_LENGTH_UNDEFINED; case MODBUS_FC_MASK_WRITE_REGISTER: length = 7; break; default: length = 5; } return offset + length + ctx->backend->checksum_length; } /* Sends a request/response */ static int send_msg(modbus_t *ctx, uint8_t *msg, int msg_length) { int rc; int i; msg_length = ctx->backend->send_msg_pre(msg, msg_length); if (ctx->debug) { for (i = 0; i < msg_length; i++) printf("[%.2X]", msg[i]); printf("\n"); } /* In recovery mode, the write command will be issued until to be successful! Disabled by default. */ do { rc = ctx->backend->send(ctx, msg, msg_length); if (rc == -1) { _error_print(ctx, NULL); if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) { int saved_errno = errno; if ((errno == EBADF || errno == ECONNRESET || errno == EPIPE)) { modbus_close(ctx); _sleep_response_timeout(ctx); modbus_connect(ctx); } else { _sleep_response_timeout(ctx); modbus_flush(ctx); } errno = saved_errno; } } } while ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) && rc == -1); if (rc > 0 && rc != msg_length) { errno = EMBBADDATA; return -1; } return rc; } int modbus_send_raw_request(modbus_t *ctx, uint8_t *raw_req, int raw_req_length) { sft_t sft; uint8_t req[MAX_MESSAGE_LENGTH]; int req_length; if (ctx == NULL) { errno = EINVAL; return -1; } if (raw_req_length < 2 || raw_req_length > (MODBUS_MAX_PDU_LENGTH + 1)) { /* The raw request must contain function and slave at least and must not be longer than the maximum pdu length plus the slave address. */ errno = EINVAL; return -1; } sft.slave = raw_req[0]; sft.function = raw_req[1]; /* The t_id is left to zero */ sft.t_id = 0; /* This response function only set the header so it's convenient here */ req_length = ctx->backend->build_response_basis(&sft, req); if (raw_req_length > 2) { /* Copy data after function code */ memcpy(req + req_length, raw_req + 2, raw_req_length - 2); req_length += raw_req_length - 2; } return send_msg(ctx, req, req_length); } /* * ---------- Request Indication ---------- * | Client | ---------------------->| Server | * ---------- Confirmation Response ---------- */ /* Computes the length to read after the function received */ static uint8_t compute_meta_length_after_function(int function, msg_type_t msg_type) { int length; if (msg_type == MSG_INDICATION) { if (function <= MODBUS_FC_WRITE_SINGLE_REGISTER) { length = 4; } else if (function == MODBUS_FC_WRITE_MULTIPLE_COILS || function == MODBUS_FC_WRITE_MULTIPLE_REGISTERS) { length = 5; } else if (function == MODBUS_FC_MASK_WRITE_REGISTER) { length = 6; } else if (function == MODBUS_FC_WRITE_AND_READ_REGISTERS) { length = 9; } else { /* MODBUS_FC_READ_EXCEPTION_STATUS, MODBUS_FC_REPORT_SLAVE_ID */ length = 0; } } else { /* MSG_CONFIRMATION */ switch (function) { case MODBUS_FC_WRITE_SINGLE_COIL: case MODBUS_FC_WRITE_SINGLE_REGISTER: case MODBUS_FC_WRITE_MULTIPLE_COILS: case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: length = 4; break; case MODBUS_FC_MASK_WRITE_REGISTER: length = 6; break; default: length = 1; } } return length; } /* Computes the length to read after the meta information (address, count, etc) */ static int compute_data_length_after_meta(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type) { int function = msg[ctx->backend->header_length]; int length; if (msg_type == MSG_INDICATION) { switch (function) { case MODBUS_FC_WRITE_MULTIPLE_COILS: case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: length = msg[ctx->backend->header_length + 5]; break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: length = msg[ctx->backend->header_length + 9]; break; default: length = 0; } } else { /* MSG_CONFIRMATION */ if (function <= MODBUS_FC_READ_INPUT_REGISTERS || function == MODBUS_FC_REPORT_SLAVE_ID || function == MODBUS_FC_WRITE_AND_READ_REGISTERS) { length = msg[ctx->backend->header_length + 1]; } else { length = 0; } } length += ctx->backend->checksum_length; return length; } /* Waits a response from a modbus server or a request from a modbus client. This function blocks if there is no replies (3 timeouts). The function shall return the number of received characters and the received message in an array of uint8_t if successful. Otherwise it shall return -1 and errno is set to one of the values defined below: - ECONNRESET - EMBBADDATA - EMBUNKEXC - ETIMEDOUT - read() or recv() error codes */ int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type) { int rc; fd_set rset; struct timeval tv; struct timeval *p_tv; int length_to_read; int msg_length = 0; _step_t step; if (ctx->debug) { if (msg_type == MSG_INDICATION) { printf("Waiting for an indication...\n"); } else { printf("Waiting for a confirmation...\n"); } } /* Add a file descriptor to the set */ FD_ZERO(&rset); FD_SET(ctx->s, &rset); /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this * information. */ step = _STEP_FUNCTION; length_to_read = ctx->backend->header_length + 1; if (msg_type == MSG_INDICATION) { /* Wait for a message, we don't know when the message will be * received */ if (ctx->indication_timeout.tv_sec == 0 && ctx->indication_timeout.tv_usec == 0) { /* By default, the indication timeout isn't set */ p_tv = NULL; } else { /* Wait for an indication (name of a received request by a server, see schema) */ tv.tv_sec = ctx->indication_timeout.tv_sec; tv.tv_usec = ctx->indication_timeout.tv_usec; p_tv = &tv; } } else { tv.tv_sec = ctx->response_timeout.tv_sec; tv.tv_usec = ctx->response_timeout.tv_usec; p_tv = &tv; } while (length_to_read != 0) { rc = ctx->backend->select(ctx, &rset, p_tv, length_to_read); if (rc == -1) { _error_print(ctx, "select"); if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) { int saved_errno = errno; if (errno == ETIMEDOUT) { _sleep_response_timeout(ctx); modbus_flush(ctx); } else if (errno == EBADF) { modbus_close(ctx); modbus_connect(ctx); } errno = saved_errno; } return -1; } rc = ctx->backend->recv(ctx, msg + msg_length, length_to_read); if (rc == 0) { errno = ECONNRESET; rc = -1; } if (rc == -1) { _error_print(ctx, "read"); if ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) && (errno == ECONNRESET || errno == ECONNREFUSED || errno == EBADF)) { int saved_errno = errno; modbus_close(ctx); modbus_connect(ctx); /* Could be removed by previous calls */ errno = saved_errno; } return -1; } /* Display the hex code of each character received */ if (ctx->debug) { int i; for (i=0; i < rc; i++) printf("<%.2X>", msg[msg_length + i]); } /* Sums bytes received */ msg_length += rc; /* Computes remaining bytes */ length_to_read -= rc; if (length_to_read == 0) { switch (step) { case _STEP_FUNCTION: /* Function code position */ length_to_read = compute_meta_length_after_function( msg[ctx->backend->header_length], msg_type); if (length_to_read != 0) { step = _STEP_META; break; } /* else switches straight to the next step */ case _STEP_META: length_to_read = compute_data_length_after_meta( ctx, msg, msg_type); if ((msg_length + length_to_read) > (int)ctx->backend->max_adu_length) { errno = EMBBADDATA; _error_print(ctx, "too many data"); return -1; } step = _STEP_DATA; break; default: break; } } if (length_to_read > 0 && (ctx->byte_timeout.tv_sec > 0 || ctx->byte_timeout.tv_usec > 0)) { /* If there is no character in the buffer, the allowed timeout interval between two consecutive bytes is defined by byte_timeout */ tv.tv_sec = ctx->byte_timeout.tv_sec; tv.tv_usec = ctx->byte_timeout.tv_usec; p_tv = &tv; } /* else timeout isn't set again, the full response must be read before expiration of response timeout (for CONFIRMATION only) */ } if (ctx->debug) printf("\n"); return ctx->backend->check_integrity(ctx, msg, msg_length); } /* Receive the request from a modbus master */ int modbus_receive(modbus_t *ctx, uint8_t *req) { if (ctx == NULL) { errno = EINVAL; return -1; } return ctx->backend->receive(ctx, req); } /* Receives the confirmation. The function shall store the read response in rsp and return the number of values (bits or words). Otherwise, its shall return -1 and errno is set. The function doesn't check the confirmation is the expected response to the initial request. */ int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp) { if (ctx == NULL) { errno = EINVAL; return -1; } return _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); } static int check_confirmation(modbus_t *ctx, uint8_t *req, uint8_t *rsp, int rsp_length) { int rc; int rsp_length_computed; const int offset = ctx->backend->header_length; const int function = rsp[offset]; if (ctx->backend->pre_check_confirmation) { rc = ctx->backend->pre_check_confirmation(ctx, req, rsp, rsp_length); if (rc == -1) { if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { _sleep_response_timeout(ctx); modbus_flush(ctx); } return -1; } } rsp_length_computed = compute_response_length_from_request(ctx, req); /* Exception code */ if (function >= 0x80) { if (rsp_length == (offset + 2 + (int)ctx->backend->checksum_length) && req[offset] == (rsp[offset] - 0x80)) { /* Valid exception code received */ int exception_code = rsp[offset + 1]; if (exception_code < MODBUS_EXCEPTION_MAX) { errno = MODBUS_ENOBASE + exception_code; } else { errno = EMBBADEXC; } _error_print(ctx, NULL); return -1; } else { errno = EMBBADEXC; _error_print(ctx, NULL); return -1; } } /* Check length */ if ((rsp_length == rsp_length_computed || rsp_length_computed == MSG_LENGTH_UNDEFINED) && function < 0x80) { int req_nb_value; int rsp_nb_value; /* Check function code */ if (function != req[offset]) { if (ctx->debug) { fprintf(stderr, "Received function not corresponding to the request (0x%X != 0x%X)\n", function, req[offset]); } if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { _sleep_response_timeout(ctx); modbus_flush(ctx); } errno = EMBBADDATA; return -1; } /* Check the number of values is corresponding to the request */ switch (function) { case MODBUS_FC_READ_COILS: case MODBUS_FC_READ_DISCRETE_INPUTS: /* Read functions, 8 values in a byte (nb * of values in the request and byte count in * the response. */ req_nb_value = (req[offset + 3] << 8) + req[offset + 4]; req_nb_value = (req_nb_value / 8) + ((req_nb_value % 8) ? 1 : 0); rsp_nb_value = rsp[offset + 1]; break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: case MODBUS_FC_READ_HOLDING_REGISTERS: case MODBUS_FC_READ_INPUT_REGISTERS: /* Read functions 1 value = 2 bytes */ req_nb_value = (req[offset + 3] << 8) + req[offset + 4]; rsp_nb_value = (rsp[offset + 1] / 2); break; case MODBUS_FC_WRITE_MULTIPLE_COILS: case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: /* N Write functions */ req_nb_value = (req[offset + 3] << 8) + req[offset + 4]; rsp_nb_value = (rsp[offset + 3] << 8) | rsp[offset + 4]; break; case MODBUS_FC_REPORT_SLAVE_ID: /* Report slave ID (bytes received) */ req_nb_value = rsp_nb_value = rsp[offset + 1]; break; default: /* 1 Write functions & others */ req_nb_value = rsp_nb_value = 1; } if (req_nb_value == rsp_nb_value) { rc = rsp_nb_value; } else { if (ctx->debug) { fprintf(stderr, "Quantity not corresponding to the request (%d != %d)\n", rsp_nb_value, req_nb_value); } if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { _sleep_response_timeout(ctx); modbus_flush(ctx); } errno = EMBBADDATA; rc = -1; } } else { if (ctx->debug) { fprintf(stderr, "Message length not corresponding to the computed length (%d != %d)\n", rsp_length, rsp_length_computed); } if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { _sleep_response_timeout(ctx); modbus_flush(ctx); } errno = EMBBADDATA; rc = -1; } return rc; } static int response_io_status(uint8_t *tab_io_status, int address, int nb, uint8_t *rsp, int offset) { int shift = 0; /* Instead of byte (not allowed in Win32) */ int one_byte = 0; int i; for (i = address; i < address + nb; i++) { one_byte |= tab_io_status[i] << shift; if (shift == 7) { /* Byte is full */ rsp[offset++] = one_byte; one_byte = shift = 0; } else { shift++; } } if (shift != 0) rsp[offset++] = one_byte; return offset; } /* Build the exception response */ static int response_exception(modbus_t *ctx, sft_t *sft, int exception_code, uint8_t *rsp, unsigned int to_flush, const char* template, ...) { int rsp_length; /* Print debug message */ if (ctx->debug) { va_list ap; va_start(ap, template); vfprintf(stderr, template, ap); va_end(ap); } /* Flush if required */ if (to_flush) { _sleep_response_timeout(ctx); modbus_flush(ctx); } /* Build exception response */ sft->function = sft->function + 0x80; rsp_length = ctx->backend->build_response_basis(sft, rsp); rsp[rsp_length++] = exception_code; return rsp_length; } /* Send a response to the received request. Analyses the request and constructs a response. If an error occurs, this function construct the response accordingly. */ int modbus_reply(modbus_t *ctx, const uint8_t *req, int req_length, modbus_mapping_t *mb_mapping) { int offset; int slave; int function; uint16_t address; uint8_t rsp[MAX_MESSAGE_LENGTH]; int rsp_length = 0; sft_t sft; if (ctx == NULL) { errno = EINVAL; return -1; } offset = ctx->backend->header_length; slave = req[offset - 1]; function = req[offset]; address = (req[offset + 1] << 8) + req[offset + 2]; sft.slave = slave; sft.function = function; sft.t_id = ctx->backend->prepare_response_tid(req, &req_length); /* Data are flushed on illegal number of values errors. */ switch (function) { case MODBUS_FC_READ_COILS: case MODBUS_FC_READ_DISCRETE_INPUTS: { unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS); int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits; int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits; uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits; const char * const name = is_input ? "read_input_bits" : "read_bits"; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_bits; if (nb < 1 || MODBUS_MAX_READ_BITS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values %d in %s (max %d)\n", nb, name, MODBUS_MAX_READ_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in %s\n", mapping_address < 0 ? address : address + nb, name); } else { rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0); rsp_length = response_io_status(tab_bits, mapping_address, nb, rsp, rsp_length); } } break; case MODBUS_FC_READ_HOLDING_REGISTERS: case MODBUS_FC_READ_INPUT_REGISTERS: { unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS); int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers; int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers; uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers; const char * const name = is_input ? "read_input_registers" : "read_registers"; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_registers; if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values %d in %s (max %d)\n", nb, name, MODBUS_MAX_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in %s\n", mapping_address < 0 ? address : address + nb, name); } else { int i; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = tab_registers[i] >> 8; rsp[rsp_length++] = tab_registers[i] & 0xFF; } } } break; case MODBUS_FC_WRITE_SINGLE_COIL: { int mapping_address = address - mb_mapping->start_bits; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_bit\n", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; if (data == 0xFF00 || data == 0x0) { mb_mapping->tab_bits[mapping_address] = data ? ON : OFF; memcpy(rsp, req, req_length); rsp_length = req_length; } else { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE, "Illegal data value 0x%0X in write_bit request at address %0X\n", data, address); } } } break; case MODBUS_FC_WRITE_SINGLE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_register\n", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_MULTIPLE_COILS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_bits; if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) { /* May be the indication has been truncated on reading because of * invalid address (eg. nb is 0 but the request contains values to * write) so it's necessary to flush. */ rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal number of values %d in write_bits (max %d)\n", nb, MODBUS_MAX_WRITE_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_bits\n", mapping_address < 0 ? address : address + nb); } else { /* 6 = byte count */ modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb, &req[offset + 6]); rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the bit address (2) and the quantity of bits */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_registers; if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal number of values %d in write_registers (max %d)\n", nb, MODBUS_MAX_WRITE_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_registers\n", mapping_address < 0 ? address : address + nb); } else { int i, j; for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) { /* 6 and 7 = first value */ mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_REPORT_SLAVE_ID: { int str_len; int byte_count_pos; rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* Skip byte count for now */ byte_count_pos = rsp_length++; rsp[rsp_length++] = _REPORT_SLAVE_ID; /* Run indicator status to ON */ rsp[rsp_length++] = 0xFF; /* LMB + length of LIBMODBUS_VERSION_STRING */ str_len = 3 + strlen(LIBMODBUS_VERSION_STRING); memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len); rsp_length += str_len; rsp[byte_count_pos] = rsp_length - byte_count_pos - 1; } break; case MODBUS_FC_READ_EXCEPTION_STATUS: if (ctx->debug) { fprintf(stderr, "FIXME Not implemented\n"); } errno = ENOPROTOOPT; return -1; break; case MODBUS_FC_MASK_WRITE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_register\n", address); } else { uint16_t data = mb_mapping->tab_registers[mapping_address]; uint16_t and = (req[offset + 3] << 8) + req[offset + 4]; uint16_t or = (req[offset + 5] << 8) + req[offset + 6]; data = (data & and) | (or & (~and)); mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6]; int nb_write = (req[offset + 7] << 8) + req[offset + 8]; int nb_write_bytes = req[offset + 9]; int mapping_address = address - mb_mapping->start_registers; int mapping_address_write = address_write - mb_mapping->start_registers; if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb || nb_write_bytes != nb_write * 2) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n", nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers || mapping_address < 0 || (mapping_address_write + nb_write) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n", mapping_address < 0 ? address : address + nb, mapping_address_write < 0 ? address_write : address_write + nb_write); } else { int i, j; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; /* Write first. 10 and 11 are the offset of the first values to write */ for (i = mapping_address_write, j = 10; i < mapping_address_write + nb_write; i++, j += 2) { mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } /* and read the data for the response */ for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8; rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF; } } } break; default: rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE, "Unknown Modbus function code: 0x%0X\n", function); break; } /* Suppress any responses when the request was a broadcast */ return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU && slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length); } int modbus_reply_exception(modbus_t *ctx, const uint8_t *req, unsigned int exception_code) { int offset; int slave; int function; uint8_t rsp[MAX_MESSAGE_LENGTH]; int rsp_length; int dummy_length = 99; sft_t sft; if (ctx == NULL) { errno = EINVAL; return -1; } offset = ctx->backend->header_length; slave = req[offset - 1]; function = req[offset]; sft.slave = slave; sft.function = function + 0x80; sft.t_id = ctx->backend->prepare_response_tid(req, &dummy_length); rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* Positive exception code */ if (exception_code < MODBUS_EXCEPTION_MAX) { rsp[rsp_length++] = exception_code; return send_msg(ctx, rsp, rsp_length); } else { errno = EINVAL; return -1; } } /* Reads IO status */ static int read_io_status(modbus_t *ctx, int function, int addr, int nb, uint8_t *dest) { int rc; int req_length; uint8_t req[_MIN_REQ_LENGTH]; uint8_t rsp[MAX_MESSAGE_LENGTH]; req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req); rc = send_msg(ctx, req, req_length); if (rc > 0) { int i, temp, bit; int pos = 0; int offset; int offset_end; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); if (rc == -1) return -1; offset = ctx->backend->header_length + 2; offset_end = offset + rc; for (i = offset; i < offset_end; i++) { /* Shift reg hi_byte to temp */ temp = rsp[i]; for (bit = 0x01; (bit & 0xff) && (pos < nb);) { dest[pos++] = (temp & bit) ? TRUE : FALSE; bit = bit << 1; } } } return rc; } /* Reads the boolean status of bits and sets the array elements in the destination to TRUE or FALSE (single bits). */ int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest) { int rc; if (ctx == NULL) { errno = EINVAL; return -1; } if (nb > MODBUS_MAX_READ_BITS) { if (ctx->debug) { fprintf(stderr, "ERROR Too many bits requested (%d > %d)\n", nb, MODBUS_MAX_READ_BITS); } errno = EMBMDATA; return -1; } rc = read_io_status(ctx, MODBUS_FC_READ_COILS, addr, nb, dest); if (rc == -1) return -1; else return nb; } /* Same as modbus_read_bits but reads the remote device input table */ int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest) { int rc; if (ctx == NULL) { errno = EINVAL; return -1; } if (nb > MODBUS_MAX_READ_BITS) { if (ctx->debug) { fprintf(stderr, "ERROR Too many discrete inputs requested (%d > %d)\n", nb, MODBUS_MAX_READ_BITS); } errno = EMBMDATA; return -1; } rc = read_io_status(ctx, MODBUS_FC_READ_DISCRETE_INPUTS, addr, nb, dest); if (rc == -1) return -1; else return nb; } /* Reads the data from a remove device and put that data into an array */ static int read_registers(modbus_t *ctx, int function, int addr, int nb, uint16_t *dest) { int rc; int req_length; uint8_t req[_MIN_REQ_LENGTH]; uint8_t rsp[MAX_MESSAGE_LENGTH]; if (nb > MODBUS_MAX_READ_REGISTERS) { if (ctx->debug) { fprintf(stderr, "ERROR Too many registers requested (%d > %d)\n", nb, MODBUS_MAX_READ_REGISTERS); } errno = EMBMDATA; return -1; } req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req); rc = send_msg(ctx, req, req_length); if (rc > 0) { int offset; int i; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); if (rc == -1) return -1; offset = ctx->backend->header_length; for (i = 0; i < rc; i++) { /* shift reg hi_byte to temp OR with lo_byte */ dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | rsp[offset + 3 + (i << 1)]; } } return rc; } /* Reads the holding registers of remote device and put the data into an array */ int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest) { int status; if (ctx == NULL) { errno = EINVAL; return -1; } if (nb > MODBUS_MAX_READ_REGISTERS) { if (ctx->debug) { fprintf(stderr, "ERROR Too many registers requested (%d > %d)\n", nb, MODBUS_MAX_READ_REGISTERS); } errno = EMBMDATA; return -1; } status = read_registers(ctx, MODBUS_FC_READ_HOLDING_REGISTERS, addr, nb, dest); return status; } /* Reads the input registers of remote device and put the data into an array */ int modbus_read_input_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest) { int status; if (ctx == NULL) { errno = EINVAL; return -1; } if (nb > MODBUS_MAX_READ_REGISTERS) { fprintf(stderr, "ERROR Too many input registers requested (%d > %d)\n", nb, MODBUS_MAX_READ_REGISTERS); errno = EMBMDATA; return -1; } status = read_registers(ctx, MODBUS_FC_READ_INPUT_REGISTERS, addr, nb, dest); return status; } /* Write a value to the specified register of the remote device. Used by write_bit and write_register */ static int write_single(modbus_t *ctx, int function, int addr, int value) { int rc; int req_length; uint8_t req[_MIN_REQ_LENGTH]; if (ctx == NULL) { errno = EINVAL; return -1; } req_length = ctx->backend->build_request_basis(ctx, function, addr, value, req); rc = send_msg(ctx, req, req_length); if (rc > 0) { /* Used by write_bit and write_register */ uint8_t rsp[MAX_MESSAGE_LENGTH]; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); } return rc; } /* Turns ON or OFF a single bit of the remote device */ int modbus_write_bit(modbus_t *ctx, int addr, int status) { if (ctx == NULL) { errno = EINVAL; return -1; } return write_single(ctx, MODBUS_FC_WRITE_SINGLE_COIL, addr, status ? 0xFF00 : 0); } /* Writes a value in one register of the remote device */ int modbus_write_register(modbus_t *ctx, int addr, int value) { if (ctx == NULL) { errno = EINVAL; return -1; } return write_single(ctx, MODBUS_FC_WRITE_SINGLE_REGISTER, addr, value); } /* Write the bits of the array in the remote device */ int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *src) { int rc; int i; int byte_count; int req_length; int bit_check = 0; int pos = 0; uint8_t req[MAX_MESSAGE_LENGTH]; if (ctx == NULL) { errno = EINVAL; return -1; } if (nb > MODBUS_MAX_WRITE_BITS) { if (ctx->debug) { fprintf(stderr, "ERROR Writing too many bits (%d > %d)\n", nb, MODBUS_MAX_WRITE_BITS); } errno = EMBMDATA; return -1; } req_length = ctx->backend->build_request_basis(ctx, MODBUS_FC_WRITE_MULTIPLE_COILS, addr, nb, req); byte_count = (nb / 8) + ((nb % 8) ? 1 : 0); req[req_length++] = byte_count; for (i = 0; i < byte_count; i++) { int bit; bit = 0x01; req[req_length] = 0; while ((bit & 0xFF) && (bit_check++ < nb)) { if (src[pos++]) req[req_length] |= bit; else req[req_length] &=~ bit; bit = bit << 1; } req_length++; } rc = send_msg(ctx, req, req_length); if (rc > 0) { uint8_t rsp[MAX_MESSAGE_LENGTH]; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); } return rc; } /* Write the values from the array to the registers of the remote device */ int modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *src) { int rc; int i; int req_length; int byte_count; uint8_t req[MAX_MESSAGE_LENGTH]; if (ctx == NULL) { errno = EINVAL; return -1; } if (nb > MODBUS_MAX_WRITE_REGISTERS) { if (ctx->debug) { fprintf(stderr, "ERROR Trying to write to too many registers (%d > %d)\n", nb, MODBUS_MAX_WRITE_REGISTERS); } errno = EMBMDATA; return -1; } req_length = ctx->backend->build_request_basis(ctx, MODBUS_FC_WRITE_MULTIPLE_REGISTERS, addr, nb, req); byte_count = nb * 2; req[req_length++] = byte_count; for (i = 0; i < nb; i++) { req[req_length++] = src[i] >> 8; req[req_length++] = src[i] & 0x00FF; } rc = send_msg(ctx, req, req_length); if (rc > 0) { uint8_t rsp[MAX_MESSAGE_LENGTH]; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); } return rc; } int modbus_mask_write_register(modbus_t *ctx, int addr, uint16_t and_mask, uint16_t or_mask) { int rc; int req_length; /* The request length can not exceed _MIN_REQ_LENGTH - 2 and 4 bytes to * store the masks. The ugly substraction is there to remove the 'nb' value * (2 bytes) which is not used. */ uint8_t req[_MIN_REQ_LENGTH + 2]; req_length = ctx->backend->build_request_basis(ctx, MODBUS_FC_MASK_WRITE_REGISTER, addr, 0, req); /* HACKISH, count is not used */ req_length -= 2; req[req_length++] = and_mask >> 8; req[req_length++] = and_mask & 0x00ff; req[req_length++] = or_mask >> 8; req[req_length++] = or_mask & 0x00ff; rc = send_msg(ctx, req, req_length); if (rc > 0) { /* Used by write_bit and write_register */ uint8_t rsp[MAX_MESSAGE_LENGTH]; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); } return rc; } /* Write multiple registers from src array to remote device and read multiple registers from remote device to dest array. */ int modbus_write_and_read_registers(modbus_t *ctx, int write_addr, int write_nb, const uint16_t *src, int read_addr, int read_nb, uint16_t *dest) { int rc; int req_length; int i; int byte_count; uint8_t req[MAX_MESSAGE_LENGTH]; uint8_t rsp[MAX_MESSAGE_LENGTH]; if (ctx == NULL) { errno = EINVAL; return -1; } if (write_nb > MODBUS_MAX_WR_WRITE_REGISTERS) { if (ctx->debug) { fprintf(stderr, "ERROR Too many registers to write (%d > %d)\n", write_nb, MODBUS_MAX_WR_WRITE_REGISTERS); } errno = EMBMDATA; return -1; } if (read_nb > MODBUS_MAX_WR_READ_REGISTERS) { if (ctx->debug) { fprintf(stderr, "ERROR Too many registers requested (%d > %d)\n", read_nb, MODBUS_MAX_WR_READ_REGISTERS); } errno = EMBMDATA; return -1; } req_length = ctx->backend->build_request_basis(ctx, MODBUS_FC_WRITE_AND_READ_REGISTERS, read_addr, read_nb, req); req[req_length++] = write_addr >> 8; req[req_length++] = write_addr & 0x00ff; req[req_length++] = write_nb >> 8; req[req_length++] = write_nb & 0x00ff; byte_count = write_nb * 2; req[req_length++] = byte_count; for (i = 0; i < write_nb; i++) { req[req_length++] = src[i] >> 8; req[req_length++] = src[i] & 0x00FF; } rc = send_msg(ctx, req, req_length); if (rc > 0) { int offset; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); if (rc == -1) return -1; offset = ctx->backend->header_length; for (i = 0; i < rc; i++) { /* shift reg hi_byte to temp OR with lo_byte */ dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | rsp[offset + 3 + (i << 1)]; } } return rc; } /* Send a request to get the slave ID of the device (only available in serial communication). */ int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest) { int rc; int req_length; uint8_t req[_MIN_REQ_LENGTH]; if (ctx == NULL || max_dest <= 0) { errno = EINVAL; return -1; } req_length = ctx->backend->build_request_basis(ctx, MODBUS_FC_REPORT_SLAVE_ID, 0, 0, req); /* HACKISH, addr and count are not used */ req_length -= 4; rc = send_msg(ctx, req, req_length); if (rc > 0) { int i; int offset; uint8_t rsp[MAX_MESSAGE_LENGTH]; rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); if (rc == -1) return -1; rc = check_confirmation(ctx, req, rsp, rc); if (rc == -1) return -1; offset = ctx->backend->header_length + 2; /* Byte count, slave id, run indicator status and additional data. Truncate copy to max_dest. */ for (i=0; i < rc && i < max_dest; i++) { dest[i] = rsp[offset + i]; } } return rc; } void _modbus_init_common(modbus_t *ctx) { /* Slave and socket are initialized to -1 */ ctx->slave = -1; ctx->s = -1; ctx->debug = FALSE; ctx->error_recovery = MODBUS_ERROR_RECOVERY_NONE; ctx->response_timeout.tv_sec = 0; ctx->response_timeout.tv_usec = _RESPONSE_TIMEOUT; ctx->byte_timeout.tv_sec = 0; ctx->byte_timeout.tv_usec = _BYTE_TIMEOUT; ctx->indication_timeout.tv_sec = 0; ctx->indication_timeout.tv_usec = 0; } /* Define the slave number */ int modbus_set_slave(modbus_t *ctx, int slave) { if (ctx == NULL) { errno = EINVAL; return -1; } return ctx->backend->set_slave(ctx, slave); } int modbus_get_slave(modbus_t *ctx) { if (ctx == NULL) { errno = EINVAL; return -1; } return ctx->slave; } int modbus_set_error_recovery(modbus_t *ctx, modbus_error_recovery_mode error_recovery) { if (ctx == NULL) { errno = EINVAL; return -1; } /* The type of modbus_error_recovery_mode is unsigned enum */ ctx->error_recovery = (uint8_t) error_recovery; return 0; } int modbus_set_socket(modbus_t *ctx, int s) { if (ctx == NULL) { errno = EINVAL; return -1; } ctx->s = s; return 0; } int modbus_get_socket(modbus_t *ctx) { if (ctx == NULL) { errno = EINVAL; return -1; } return ctx->s; } /* Get the timeout interval used to wait for a response */ int modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec) { if (ctx == NULL) { errno = EINVAL; return -1; } *to_sec = ctx->response_timeout.tv_sec; *to_usec = ctx->response_timeout.tv_usec; return 0; } int modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec) { if (ctx == NULL || (to_sec == 0 && to_usec == 0) || to_usec > 999999) { errno = EINVAL; return -1; } ctx->response_timeout.tv_sec = to_sec; ctx->response_timeout.tv_usec = to_usec; return 0; } /* Get the timeout interval between two consecutive bytes of a message */ int modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec) { if (ctx == NULL) { errno = EINVAL; return -1; } *to_sec = ctx->byte_timeout.tv_sec; *to_usec = ctx->byte_timeout.tv_usec; return 0; } int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec) { /* Byte timeout can be disabled when both values are zero */ if (ctx == NULL || to_usec > 999999) { errno = EINVAL; return -1; } ctx->byte_timeout.tv_sec = to_sec; ctx->byte_timeout.tv_usec = to_usec; return 0; } /* Get the timeout interval used by the server to wait for an indication from a client */ int modbus_get_indication_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec) { if (ctx == NULL) { errno = EINVAL; return -1; } *to_sec = ctx->indication_timeout.tv_sec; *to_usec = ctx->indication_timeout.tv_usec; return 0; } int modbus_set_indication_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec) { /* Indication timeout can be disabled when both values are zero */ if (ctx == NULL || to_usec > 999999) { errno = EINVAL; return -1; } ctx->indication_timeout.tv_sec = to_sec; ctx->indication_timeout.tv_usec = to_usec; return 0; } int modbus_get_header_length(modbus_t *ctx) { if (ctx == NULL) { errno = EINVAL; return -1; } return ctx->backend->header_length; } int modbus_connect(modbus_t *ctx) { if (ctx == NULL) { errno = EINVAL; return -1; } return ctx->backend->connect(ctx); } void modbus_close(modbus_t *ctx) { if (ctx == NULL) return; ctx->backend->close(ctx); } void modbus_free(modbus_t *ctx) { if (ctx == NULL) return; ctx->backend->free(ctx); } int modbus_set_debug(modbus_t *ctx, int flag) { if (ctx == NULL) { errno = EINVAL; return -1; } ctx->debug = flag; return 0; } /* Allocates 4 arrays to store bits, input bits, registers and inputs registers. The pointers are stored in modbus_mapping structure. The modbus_mapping_new_start_address() function shall return the new allocated structure if successful. Otherwise it shall return NULL and set errno to ENOMEM. */ modbus_mapping_t* modbus_mapping_new_start_address( unsigned int start_bits, unsigned int nb_bits, unsigned int start_input_bits, unsigned int nb_input_bits, unsigned int start_registers, unsigned int nb_registers, unsigned int start_input_registers, unsigned int nb_input_registers) { modbus_mapping_t *mb_mapping; mb_mapping = (modbus_mapping_t *)malloc(sizeof(modbus_mapping_t)); if (mb_mapping == NULL) { return NULL; } /* 0X */ mb_mapping->nb_bits = nb_bits; mb_mapping->start_bits = start_bits; if (nb_bits == 0) { mb_mapping->tab_bits = NULL; } else { /* Negative number raises a POSIX error */ mb_mapping->tab_bits = (uint8_t *) malloc(nb_bits * sizeof(uint8_t)); if (mb_mapping->tab_bits == NULL) { free(mb_mapping); return NULL; } memset(mb_mapping->tab_bits, 0, nb_bits * sizeof(uint8_t)); } /* 1X */ mb_mapping->nb_input_bits = nb_input_bits; mb_mapping->start_input_bits = start_input_bits; if (nb_input_bits == 0) { mb_mapping->tab_input_bits = NULL; } else { mb_mapping->tab_input_bits = (uint8_t *) malloc(nb_input_bits * sizeof(uint8_t)); if (mb_mapping->tab_input_bits == NULL) { free(mb_mapping->tab_bits); free(mb_mapping); return NULL; } memset(mb_mapping->tab_input_bits, 0, nb_input_bits * sizeof(uint8_t)); } /* 4X */ mb_mapping->nb_registers = nb_registers; mb_mapping->start_registers = start_registers; if (nb_registers == 0) { mb_mapping->tab_registers = NULL; } else { mb_mapping->tab_registers = (uint16_t *) malloc(nb_registers * sizeof(uint16_t)); if (mb_mapping->tab_registers == NULL) { free(mb_mapping->tab_input_bits); free(mb_mapping->tab_bits); free(mb_mapping); return NULL; } memset(mb_mapping->tab_registers, 0, nb_registers * sizeof(uint16_t)); } /* 3X */ mb_mapping->nb_input_registers = nb_input_registers; mb_mapping->start_input_registers = start_input_registers; if (nb_input_registers == 0) { mb_mapping->tab_input_registers = NULL; } else { mb_mapping->tab_input_registers = (uint16_t *) malloc(nb_input_registers * sizeof(uint16_t)); if (mb_mapping->tab_input_registers == NULL) { free(mb_mapping->tab_registers); free(mb_mapping->tab_input_bits); free(mb_mapping->tab_bits); free(mb_mapping); return NULL; } memset(mb_mapping->tab_input_registers, 0, nb_input_registers * sizeof(uint16_t)); } return mb_mapping; } modbus_mapping_t* modbus_mapping_new(int nb_bits, int nb_input_bits, int nb_registers, int nb_input_registers) { return modbus_mapping_new_start_address( 0, nb_bits, 0, nb_input_bits, 0, nb_registers, 0, nb_input_registers); } /* Frees the 4 arrays */ void modbus_mapping_free(modbus_mapping_t *mb_mapping) { if (mb_mapping == NULL) { return; } free(mb_mapping->tab_input_registers); free(mb_mapping->tab_registers); free(mb_mapping->tab_input_bits); free(mb_mapping->tab_bits); free(mb_mapping); } #ifndef HAVE_STRLCPY /* * Function strlcpy was originally developed by * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code. * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3 * for more information. * * Thank you Ulrich Drepper... not! * * Copy src to string dest of size dest_size. At most dest_size-1 characters * will be copied. Always NUL terminates (unless dest_size == 0). Returns * strlen(src); if retval >= dest_size, truncation occurred. */ size_t strlcpy(char *dest, const char *src, size_t dest_size) { register char *d = dest; register const char *s = src; register size_t n = dest_size; /* Copy as many bytes as will fit */ if (n != 0 && --n != 0) { do { if ((*d++ = *s++) == 0) break; } while (--n != 0); } /* Not enough room in dest, add NUL and traverse rest of src */ if (n == 0) { if (dest_size != 0) *d = '\0'; /* NUL-terminate dest */ while (*s++) ; } return (s - src - 1); /* count does not include NUL */ } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_977_0
crossvul-cpp_data_bad_768_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L OOO CCCC AAA L EEEEE % % L O O C A A L E % % L O O C AAAAA L EEE % % L O O C A A L E % % LLLLL OOO CCCC A A LLLLL EEEEE % % % % % % MagickCore Image Locale Methods % % % % Software Design % % Cristy % % July 2003 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/client.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image-private.h" #include "MagickCore/linked-list.h" #include "MagickCore/locale_.h" #include "MagickCore/locale-private.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* Define declarations. */ #if defined(MAGICKCORE_HAVE_NEWLOCALE) || defined(MAGICKCORE_WINDOWS_SUPPORT) # define MAGICKCORE_LOCALE_SUPPORT #endif #define LocaleFilename "locale.xml" /* Static declarations. */ static const char *LocaleMap = "<?xml version=\"1.0\"?>" "<localemap>" " <locale name=\"C\">" " <Exception>" " <Message name=\"\">" " </Message>" " </Exception>" " </locale>" "</localemap>"; #ifdef __VMS #define asciimap AsciiMap #endif #if !defined(MAGICKCORE_HAVE_STRCASECMP) || !defined(MAGICKCORE_HAVE_STRNCASECMP) static const unsigned char AsciiMap[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xe1, 0xe2, 0xe3, 0xe4, 0xc5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, }; #endif static SemaphoreInfo *locale_semaphore = (SemaphoreInfo *) NULL; static SplayTreeInfo *locale_cache = (SplayTreeInfo *) NULL; #if defined(MAGICKCORE_LOCALE_SUPPORT) static volatile locale_t c_locale = (locale_t) NULL; #endif /* Forward declarations. */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *), LoadLocaleCache(SplayTreeInfo *,const char *,const char *,const char *, const size_t,ExceptionInfo *); #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCLocale() allocates the C locale object, or (locale_t) 0 with % errno set if it cannot be acquired. % % The format of the AcquireCLocale method is: % % locale_t AcquireCLocale(void) % */ static locale_t AcquireCLocale(void) { #if defined(MAGICKCORE_HAVE_NEWLOCALE) if (c_locale == (locale_t) NULL) c_locale=newlocale(LC_ALL_MASK,"C",(locale_t) 0); #elif defined(MAGICKCORE_WINDOWS_SUPPORT) && !defined(__MINGW32__) if (c_locale == (locale_t) NULL) c_locale=_create_locale(LC_ALL,"C"); #endif return(c_locale); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e L o c a l e S p l a y T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireLocaleSplayTree() caches one or more locale configurations which % provides a mapping between locale attributes and a locale tag. % % The format of the AcquireLocaleSplayTree method is: % % SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the font file tag. % % o locale: the actual locale. % % o exception: return any errors or warnings in this structure. % */ static void *DestroyLocaleNode(void *locale_info) { register LocaleInfo *p; p=(LocaleInfo *) locale_info; if (p->path != (char *) NULL) p->path=DestroyString(p->path); if (p->tag != (char *) NULL) p->tag=DestroyString(p->tag); if (p->message != (char *) NULL) p->message=DestroyString(p->message); return(RelinquishMagickMemory(p)); } static SplayTreeInfo *AcquireLocaleSplayTree(const char *filename, const char *locale,ExceptionInfo *exception) { MagickStatusType status; SplayTreeInfo *cache; cache=NewSplayTree(CompareSplayTreeString,(void *(*)(void *)) NULL, DestroyLocaleNode); status=MagickTrue; #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) { const StringInfo *option; LinkedListInfo *options; options=GetLocaleOptions(filename,exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); if (GetNumberOfNodesInSplayTree(cache) == 0) { options=GetLocaleOptions("english.xml",exception); option=(const StringInfo *) GetNextValueInLinkedList(options); while (option != (const StringInfo *) NULL) { status&=LoadLocaleCache(cache,(const char *) GetStringInfoDatum(option),GetStringInfoPath(option),locale,0, exception); option=(const StringInfo *) GetNextValueInLinkedList(options); } options=DestroyLocaleOptions(options); } } #endif if (GetNumberOfNodesInSplayTree(cache) == 0) status&=LoadLocaleCache(cache,LocaleMap,"built-in",locale,0, exception); return(cache); } #if defined(MAGICKCORE_LOCALE_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C L o c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCLocale() releases the resources allocated for a locale object % returned by a call to the AcquireCLocale() method. % % The format of the DestroyCLocale method is: % % void DestroyCLocale(void) % */ static void DestroyCLocale(void) { if (c_locale != (locale_t) NULL) freelocale(c_locale); c_locale=(locale_t) NULL; } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyLocaleOptions() releases memory associated with an locale % messages. % % The format of the DestroyProfiles method is: % % LinkedListInfo *DestroyLocaleOptions(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *DestroyOptions(void *message) { return(DestroyStringInfo((StringInfo *) message)); } MagickExport LinkedListInfo *DestroyLocaleOptions(LinkedListInfo *messages) { assert(messages != (LinkedListInfo *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); return(DestroyLinkedList(messages,DestroyOptions)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleFile() prints formatted output of a variable argument list to a % file in the "C" locale. % % The format of the FormatLocaleFile method is: % % ssize_t FormatLocaleFile(FILE *file,const char *format,...) % % A description of each parameter follows. % % o file: the file. % % o format: A file describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleFileList(FILE *file, const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VFPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vfprintf_l(file,format,locale,operands); #else n=(ssize_t) vfprintf_l(file,locale,format,operands); #endif } #else #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vfprintf(file,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vfprintf(file,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vfprintf(file,format,operands); #endif #endif return(n); } MagickExport ssize_t FormatLocaleFile(FILE *file, const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleFileList(file,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F o r m a t L o c a l e S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatLocaleString() prints formatted output of a variable argument list to % a string buffer in the "C" locale. % % The format of the FormatLocaleString method is: % % ssize_t FormatLocaleString(char *string,const size_t length, % const char *format,...) % % A description of each parameter follows. % % o string: FormatLocaleString() returns the formatted string in this % character buffer. % % o length: the maximum length of the string. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickPrivate ssize_t FormatLocaleStringList(char *magick_restrict string, const size_t length,const char *magick_restrict format,va_list operands) { ssize_t n; #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VSNPRINTF_L) { locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else #if defined(MAGICKCORE_WINDOWS_SUPPORT) n=(ssize_t) vsnprintf_l(string,length,format,locale,operands); #else n=(ssize_t) vsnprintf_l(string,length,locale,format,operands); #endif } #elif defined(MAGICKCORE_HAVE_VSNPRINTF) #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE) { locale_t locale, previous_locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) n=(ssize_t) vsnprintf(string,length,format,operands); else { previous_locale=uselocale(locale); n=(ssize_t) vsnprintf(string,length,format,operands); uselocale(previous_locale); } } #else n=(ssize_t) vsnprintf(string,length,format,operands); #endif #else n=(ssize_t) vsprintf(string,format,operands); #endif if (n < 0) string[length-1]='\0'; return(n); } MagickExport ssize_t FormatLocaleString(char *magick_restrict string, const size_t length,const char *magick_restrict format,...) { ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(string,length,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t L o c a l e I n f o _ % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfo_() searches the locale list for the specified tag and if % found returns attributes for that element. % % The format of the GetLocaleInfo method is: % % const LocaleInfo *GetLocaleInfo_(const char *tag, % ExceptionInfo *exception) % % A description of each parameter follows: % % o tag: the locale tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport const LocaleInfo *GetLocaleInfo_(const char *tag, ExceptionInfo *exception) { const LocaleInfo *locale_info; assert(exception != (ExceptionInfo *) NULL); if (IsLocaleTreeInstantiated(exception) == MagickFalse) return((const LocaleInfo *) NULL); LockSemaphoreInfo(locale_semaphore); if ((tag == (const char *) NULL) || (LocaleCompare(tag,"*") == 0)) { ResetSplayTreeIterator(locale_cache); locale_info=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } locale_info=(const LocaleInfo *) GetValueFromSplayTree(locale_cache,tag); UnlockSemaphoreInfo(locale_semaphore); return(locale_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e I n f o L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleInfoList() returns any locale messages that match the % specified pattern. % % The format of the GetLocaleInfoList function is: % % const LocaleInfo **GetLocaleInfoList(const char *pattern, % size_t *number_messages,ExceptionInfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of locale messages in % the list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleInfoCompare(const void *x,const void *y) { const LocaleInfo **p, **q; p=(const LocaleInfo **) x, q=(const LocaleInfo **) y; if (LocaleCompare((*p)->path,(*q)->path) == 0) return(LocaleCompare((*p)->tag,(*q)->tag)); return(LocaleCompare((*p)->path,(*q)->path)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport const LocaleInfo **GetLocaleInfoList(const char *pattern, size_t *number_messages,ExceptionInfo *exception) { const LocaleInfo **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((const LocaleInfo **) NULL); messages=(const LocaleInfo **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (const LocaleInfo **) NULL) return((const LocaleInfo **) NULL); /* Generate locale list. */ LockSemaphoreInfo(locale_semaphore); ResetSplayTreeIterator(locale_cache); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=p; p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleInfoCompare); messages[i]=(LocaleInfo *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleList() returns any locale messages that match the specified % pattern. % % The format of the GetLocaleList function is: % % char **GetLocaleList(const char *pattern,size_t *number_messages, % Exceptioninfo *exception) % % A description of each parameter follows: % % o pattern: Specifies a pointer to a text string containing a pattern. % % o number_messages: This integer returns the number of messages in the % list. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int LocaleTagCompare(const void *x,const void *y) { register char **p, **q; p=(char **) x; q=(char **) y; return(LocaleCompare(*p,*q)); } #if defined(__cplusplus) || defined(c_plusplus) } #endif MagickExport char **GetLocaleList(const char *pattern,size_t *number_messages, ExceptionInfo *exception) { char **messages; register const LocaleInfo *p; register ssize_t i; /* Allocate locale list. */ assert(pattern != (char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern); assert(number_messages != (size_t *) NULL); *number_messages=0; p=GetLocaleInfo_("*",exception); if (p == (const LocaleInfo *) NULL) return((char **) NULL); messages=(char **) AcquireQuantumMemory((size_t) GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages)); if (messages == (char **) NULL) return((char **) NULL); LockSemaphoreInfo(locale_semaphore); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); for (i=0; p != (const LocaleInfo *) NULL; ) { if ((p->stealth == MagickFalse) && (GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse)) messages[i++]=ConstantString(p->tag); p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache); } UnlockSemaphoreInfo(locale_semaphore); qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleTagCompare); messages[i]=(char *) NULL; *number_messages=(size_t) i; return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e M e s s a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleMessage() returns a message in the current locale that matches the % supplied tag. % % The format of the GetLocaleMessage method is: % % const char *GetLocaleMessage(const char *tag) % % A description of each parameter follows: % % o tag: Return a message that matches this tag in the current locale. % */ MagickExport const char *GetLocaleMessage(const char *tag) { char name[MagickLocaleExtent]; const LocaleInfo *locale_info; ExceptionInfo *exception; if ((tag == (const char *) NULL) || (*tag == '\0')) return(tag); exception=AcquireExceptionInfo(); (void) FormatLocaleString(name,MagickLocaleExtent,"%s/",tag); locale_info=GetLocaleInfo_(name,exception); exception=DestroyExceptionInfo(exception); if (locale_info != (const LocaleInfo *) NULL) return(locale_info->message); return(tag); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleOptions() returns any Magick configuration messages associated % with the specified filename. % % The format of the GetLocaleOptions method is: % % LinkedListInfo *GetLocaleOptions(const char *filename, % ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the locale file tag. % % o exception: return any errors or warnings in this structure. % */ MagickExport LinkedListInfo *GetLocaleOptions(const char *filename, ExceptionInfo *exception) { char path[MagickPathExtent]; const char *element; LinkedListInfo *messages, *paths; StringInfo *xml; assert(filename != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename); assert(exception != (ExceptionInfo *) NULL); (void) CopyMagickString(path,filename,MagickPathExtent); /* Load XML from configuration files to linked-list. */ messages=NewLinkedList(0); paths=GetConfigurePaths(filename,exception); if (paths != (LinkedListInfo *) NULL) { ResetLinkedListIterator(paths); element=(const char *) GetNextValueInLinkedList(paths); while (element != (const char *) NULL) { (void) FormatLocaleString(path,MagickPathExtent,"%s%s",element, filename); (void) LogMagickEvent(LocaleEvent,GetMagickModule(), "Searching for locale file: \"%s\"",path); xml=ConfigureFileToStringInfo(path); if (xml != (StringInfo *) NULL) (void) AppendValueToLinkedList(messages,xml); element=(const char *) GetNextValueInLinkedList(paths); } paths=DestroyLinkedList(paths,RelinquishMagickMemory); } #if defined(MAGICKCORE_WINDOWS_SUPPORT) { char *blob; blob=(char *) NTResourceToBlob(filename); if (blob != (char *) NULL) { xml=AcquireStringInfo(0); SetStringInfoLength(xml,strlen(blob)+1); SetStringInfoDatum(xml,(const unsigned char *) blob); blob=(char *) RelinquishMagickMemory(blob); SetStringInfoPath(xml,filename); (void) AppendValueToLinkedList(messages,xml); } } #endif ResetLinkedListIterator(messages); return(messages); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetLocaleValue() returns the message associated with the locale info. % % The format of the GetLocaleValue method is: % % const char *GetLocaleValue(const LocaleInfo *locale_info) % % A description of each parameter follows: % % o locale_info: The locale info. % */ MagickExport const char *GetLocaleValue(const LocaleInfo *locale_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(locale_info != (LocaleInfo *) NULL); assert(locale_info->signature == MagickCoreSignature); return(locale_info->message); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s L o c a l e T r e e I n s t a n t i a t e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsLocaleTreeInstantiated() determines if the locale tree is instantiated. % If not, it instantiates the tree and returns it. % % The format of the IsLocaleInstantiated method is: % % MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) % % A description of each parameter follows. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception) { if (locale_cache == (SplayTreeInfo *) NULL) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache == (SplayTreeInfo *) NULL) { char *locale; register const char *p; locale=(char *) NULL; p=setlocale(LC_CTYPE,(const char *) NULL); if (p != (const char *) NULL) locale=ConstantString(p); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_ALL"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_MESSAGES"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LC_CTYPE"); if (locale == (char *) NULL) locale=GetEnvironmentValue("LANG"); if (locale == (char *) NULL) locale=ConstantString("C"); locale_cache=AcquireLocaleSplayTree(LocaleFilename,locale,exception); locale=DestroyString(locale); } UnlockSemaphoreInfo(locale_semaphore); } return(locale_cache != (SplayTreeInfo *) NULL ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n t e r p r e t L o c a l e V a l u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretLocaleValue() interprets the string as a floating point number in % the "C" locale and returns its value as a double. If sentinal is not a null % pointer, the method also sets the value pointed by sentinal to point to the % first character after the number. % % The format of the InterpretLocaleValue method is: % % double InterpretLocaleValue(const char *value,char **sentinal) % % A description of each parameter follows: % % o value: the string value. % % o sentinal: if sentinal is not NULL, a pointer to the character after the % last character used in the conversion is stored in the location % referenced by sentinal. % */ MagickExport double InterpretLocaleValue(const char *magick_restrict string, char **magick_restrict sentinal) { char *q; double value; if ((*string == '0') && ((string[1] | 0x20)=='x')) value=(double) strtoul(string,&q,16); else { #if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_STRTOD_L) locale_t locale; locale=AcquireCLocale(); if (locale == (locale_t) NULL) value=strtod(string,&q); else value=strtod_l(string,&q,locale); #else value=strtod(string,&q); #endif } if (sentinal != (char **) NULL) *sentinal=q; return(value); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t L o c a l e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListLocaleInfo() lists the locale info to a file. % % The format of the ListLocaleInfo method is: % % MagickBooleanType ListLocaleInfo(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to a FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListLocaleInfo(FILE *file, ExceptionInfo *exception) { const char *path; const LocaleInfo **locale_info; register ssize_t i; size_t number_messages; if (file == (const FILE *) NULL) file=stdout; number_messages=0; locale_info=GetLocaleInfoList("*",&number_messages,exception); if (locale_info == (const LocaleInfo **) NULL) return(MagickFalse); path=(const char *) NULL; for (i=0; i < (ssize_t) number_messages; i++) { if (locale_info[i]->stealth != MagickFalse) continue; if ((path == (const char *) NULL) || (LocaleCompare(path,locale_info[i]->path) != 0)) { if (locale_info[i]->path != (char *) NULL) (void) FormatLocaleFile(file,"\nPath: %s\n\n",locale_info[i]->path); (void) FormatLocaleFile(file,"Tag/Message\n"); (void) FormatLocaleFile(file, "-------------------------------------------------" "------------------------------\n"); } path=locale_info[i]->path; (void) FormatLocaleFile(file,"%s\n",locale_info[i]->tag); if (locale_info[i]->message != (char *) NULL) (void) FormatLocaleFile(file," %s",locale_info[i]->message); (void) FormatLocaleFile(file,"\n"); } (void) fflush(file); locale_info=(const LocaleInfo **) RelinquishMagickMemory((void *) locale_info); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o a d L o c a l e C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LoadLocaleCache() loads the locale configurations which provides a mapping % between locale attributes and a locale name. % % The format of the LoadLocaleCache method is: % % MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, % const char *filename,const size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o xml: The locale list in XML format. % % o filename: The locale list filename. % % o depth: depth of <include /> statements. % % o exception: return any errors or warnings in this structure. % */ static void ChopLocaleComponents(char *path,const size_t components) { register char *p; ssize_t count; if (*path == '\0') return; p=path+strlen(path)-1; if (*p == '/') *p='\0'; for (count=0; (count < (ssize_t) components) && (p > path); p--) if (*p == '/') { *p='\0'; count++; } if (count < (ssize_t) components) *path='\0'; } static void LocaleFatalErrorHandler( const ExceptionType magick_unused(severity), const char *reason,const char *description) { magick_unreferenced(severity); if (reason == (char *) NULL) return; (void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason); if (description != (char *) NULL) (void) FormatLocaleFile(stderr," (%s)",description); (void) FormatLocaleFile(stderr,".\n"); (void) fflush(stderr); exit(1); } static MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, const char *filename,const char *locale,const size_t depth,ExceptionInfo *exception) { char keyword[MagickLocaleExtent], message[MagickLocaleExtent], tag[MagickLocaleExtent], *token; const char *q; FatalErrorHandler fatal_handler; LocaleInfo *locale_info; MagickStatusType status; register char *p; size_t extent; /* Read the locale configure file. */ (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading locale configure file \"%s\" ...",filename); if (xml == (const char *) NULL) return(MagickFalse); status=MagickTrue; locale_info=(LocaleInfo *) NULL; *tag='\0'; *message='\0'; *keyword='\0'; fatal_handler=SetFatalErrorHandler(LocaleFatalErrorHandler); token=AcquireString(xml); extent=strlen(token)+MagickPathExtent; for (q=(char *) xml; *q != '\0'; ) { /* Interpret XML. */ GetNextToken(q,&q,extent,token); if (*token == '\0') break; (void) CopyMagickString(keyword,token,MagickLocaleExtent); if (LocaleNCompare(keyword,"<!DOCTYPE",9) == 0) { /* Doctype element. */ while ((LocaleNCompare(q,"]>",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleNCompare(keyword,"<!--",4) == 0) { /* Comment element. */ while ((LocaleNCompare(q,"->",2) != 0) && (*q != '\0')) { GetNextToken(q,&q,extent,token); while (isspace((int) ((unsigned char) *q)) != 0) q++; } continue; } if (LocaleCompare(keyword,"<include") == 0) { /* Include element. */ while (((*token != '/') && (*(token+1) != '>')) && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"locale") == 0) { if (LocaleCompare(locale,token) != 0) break; continue; } if (LocaleCompare(keyword,"file") == 0) { if (depth > MagickMaxRecursionDepth) (void) ThrowMagickException(exception,GetMagickModule(), ConfigureError,"IncludeElementNestedTooDeeply","`%s'",token); else { char path[MagickPathExtent], *file_xml; *path='\0'; GetPathComponent(filename,HeadPath,path); if (*path != '\0') (void) ConcatenateMagickString(path,DirectorySeparator, MagickPathExtent); if (*token == *DirectorySeparator) (void) CopyMagickString(path,token,MagickPathExtent); else (void) ConcatenateMagickString(path,token,MagickPathExtent); file_xml=FileToXML(path,~0UL); if (file_xml != (char *) NULL) { status&=LoadLocaleCache(cache,file_xml,path,locale, depth+1,exception); file_xml=DestroyString(file_xml); } } } } continue; } if (LocaleCompare(keyword,"<locale") == 0) { /* Locale element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); } continue; } if (LocaleCompare(keyword,"</locale>") == 0) { ChopLocaleComponents(tag,1); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (LocaleCompare(keyword,"<localemap>") == 0) continue; if (LocaleCompare(keyword,"</localemap>") == 0) continue; if (LocaleCompare(keyword,"<message") == 0) { /* Message element. */ while ((*token != '>') && (*q != '\0')) { (void) CopyMagickString(keyword,token,MagickLocaleExtent); GetNextToken(q,&q,extent,token); if (*token != '=') continue; GetNextToken(q,&q,extent,token); if (LocaleCompare(keyword,"name") == 0) { (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); } } for (p=(char *) q; (*q != '<') && (*q != '\0'); q++) ; while (isspace((int) ((unsigned char) *p)) != 0) p++; q--; while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p)) q--; (void) CopyMagickString(message,p,MagickMin((size_t) (q-p+2), MagickLocaleExtent)); locale_info=(LocaleInfo *) AcquireCriticalMemory(sizeof(*locale_info)); (void) memset(locale_info,0,sizeof(*locale_info)); locale_info->path=ConstantString(filename); locale_info->tag=ConstantString(tag); locale_info->message=ConstantString(message); locale_info->signature=MagickCoreSignature; status=AddValueToSplayTree(cache,locale_info->tag,locale_info); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", locale_info->tag); (void) ConcatenateMagickString(tag,message,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"\n",MagickLocaleExtent); q++; continue; } if (LocaleCompare(keyword,"</message>") == 0) { ChopLocaleComponents(tag,2); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } if (*keyword == '<') { /* Subpath element. */ if (*(keyword+1) == '?') continue; if (*(keyword+1) == '/') { ChopLocaleComponents(tag,1); if (*tag != '\0') (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } token[strlen(token)-1]='\0'; (void) CopyMagickString(token,token+1,MagickLocaleExtent); (void) ConcatenateMagickString(tag,token,MagickLocaleExtent); (void) ConcatenateMagickString(tag,"/",MagickLocaleExtent); continue; } GetNextToken(q,(const char **) NULL,extent,token); if (*token != '=') continue; } token=(char *) RelinquishMagickMemory(token); (void) SetFatalErrorHandler(fatal_handler); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % LocaleCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The format of the LocaleCompare method is: % % int LocaleCompare(const char *p,const char *q) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % */ MagickExport int LocaleCompare(const char *p,const char *q) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRCASECMP) return(strcasecmp(p,q)); #else { register int c, d; for ( ; ; ) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if ((c == 0) || (AsciiMap[c] != AsciiMap[d])) break; p++; q++; } return(AsciiMap[c]-(int) AsciiMap[d]); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLower() transforms all of the characters in the supplied % null-terminated string, changing all uppercase letters to lowercase. % % The format of the LocaleLower method is: % % void LocaleLower(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to lower-case Locale. % */ MagickExport void LocaleLower(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleLowercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e L o w e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleLowercase() convert to lowercase. % % The format of the LocaleLowercase method is: % % void LocaleLowercase(const int c) % % A description of each parameter follows: % % o If c is a uppercase letter, return its lowercase equivalent. % */ MagickExport int LocaleLowercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e N C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleNCompare() performs a case-insensitive comparison of two strings % byte-by-byte, according to the ordering of the current locale encoding. % % LocaleNCompare returns an integer greater than, equal to, or less than 0, % if the string pointed to by p is greater than, equal to, or less than the % string pointed to by q respectively. The sign of a non-zero return value % is determined by the sign of the difference between the values of the first % pair of bytes that differ in the strings being compared. % % The LocaleNCompare method makes the same comparison as LocaleCompare but % looks at a maximum of n bytes. Bytes following a null byte are not % compared. % % The format of the LocaleNCompare method is: % % int LocaleNCompare(const char *p,const char *q,const size_t n) % % A description of each parameter follows: % % o p: A pointer to a character string. % % o q: A pointer to a character string to compare to p. % % o length: the number of characters to compare in strings p and q. % */ MagickExport int LocaleNCompare(const char *p,const char *q,const size_t length) { if (p == (char *) NULL) { if (q == (char *) NULL) return(0); return(-1); } if (q == (char *) NULL) return(1); #if defined(MAGICKCORE_HAVE_STRNCASECMP) return(strncasecmp(p,q,length)); #else { register int c, d; register size_t i; for (i=length; i != 0; i--) { c=(int) *((unsigned char *) p); d=(int) *((unsigned char *) q); if (AsciiMap[c] != AsciiMap[d]) return(AsciiMap[c]-(int) AsciiMap[d]); if (c == 0) return(0); p++; q++; } return(0); } #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUpper() transforms all of the characters in the supplied % null-terminated string, changing all lowercase letters to uppercase. % % The format of the LocaleUpper method is: % % void LocaleUpper(char *string) % % A description of each parameter follows: % % o string: A pointer to the string to convert to upper-case Locale. % */ MagickExport void LocaleUpper(char *string) { register char *q; assert(string != (char *) NULL); for (q=string; *q != '\0'; q++) *q=(char) LocaleUppercase((int) *q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l e U p p e r c a s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleUppercase() convert to uppercase. % % The format of the LocaleUppercase method is: % % void LocaleUppercase(const int c) % % A description of each parameter follows: % % o If c is a lowercase letter, return its uppercase equivalent. % */ MagickExport int LocaleUppercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l((int) ((unsigned char) c),c_locale)); #endif return(toupper((int) ((unsigned char) c))); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentGenesis() instantiates the locale component. % % The format of the LocaleComponentGenesis method is: % % MagickBooleanType LocaleComponentGenesis(void) % */ MagickPrivate MagickBooleanType LocaleComponentGenesis(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) locale_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L o c a l e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocaleComponentTerminus() destroys the locale component. % % The format of the LocaleComponentTerminus method is: % % LocaleComponentTerminus(void) % */ MagickPrivate void LocaleComponentTerminus(void) { if (locale_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&locale_semaphore); LockSemaphoreInfo(locale_semaphore); if (locale_cache != (SplayTreeInfo *) NULL) locale_cache=DestroySplayTree(locale_cache); #if defined(MAGICKCORE_LOCALE_SUPPORT) DestroyCLocale(); #endif UnlockSemaphoreInfo(locale_semaphore); RelinquishSemaphoreInfo(&locale_semaphore); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_768_1
crossvul-cpp_data_bad_3911_1
/** * FreeRDP: A Remote Desktop Protocol Implementation * Auto-Detect PDUs * * Copyright 2014 Dell Software <Mike.McDonald@software.dell.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crypto.h> #include "autodetect.h" #define RDP_RTT_REQUEST_TYPE_CONTINUOUS 0x0001 #define RDP_RTT_REQUEST_TYPE_CONNECTTIME 0x1001 #define RDP_RTT_RESPONSE_TYPE 0x0000 #define RDP_BW_START_REQUEST_TYPE_CONTINUOUS 0x0014 #define RDP_BW_START_REQUEST_TYPE_TUNNEL 0x0114 #define RDP_BW_START_REQUEST_TYPE_CONNECTTIME 0x1014 #define RDP_BW_PAYLOAD_REQUEST_TYPE 0x0002 #define RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME 0x002B #define RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS 0x0429 #define RDP_BW_STOP_REQUEST_TYPE_TUNNEL 0x0629 #define RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME 0x0003 #define RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS 0x000B #define RDP_NETCHAR_SYNC_RESPONSE_TYPE 0x0018 typedef struct { UINT8 headerLength; UINT8 headerTypeId; UINT16 sequenceNumber; UINT16 requestType; } AUTODETECT_REQ_PDU; typedef struct { UINT8 headerLength; UINT8 headerTypeId; UINT16 sequenceNumber; UINT16 responseType; } AUTODETECT_RSP_PDU; static BOOL autodetect_send_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber, UINT16 requestType) { wStream* s; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending RTT Measure Request PDU"); Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */ context->rdp->autodetect->rttMeasureStartTime = GetTickCount64(); return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); } static BOOL autodetect_send_continuous_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_rtt_measure_request(context, sequenceNumber, RDP_RTT_REQUEST_TYPE_CONTINUOUS); } BOOL autodetect_send_connecttime_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_rtt_measure_request(context, sequenceNumber, RDP_RTT_REQUEST_TYPE_CONNECTTIME); } static BOOL autodetect_send_rtt_measure_response(rdpRdp* rdp, UINT16 sequenceNumber) { wStream* s; /* Send the response PDU to the server */ s = rdp_message_channel_pdu_init(rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending RTT Measure Response PDU"); Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, RDP_RTT_RESPONSE_TYPE); /* responseType (1 byte) */ return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP); } static BOOL autodetect_send_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber, UINT16 requestType) { wStream* s; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Start PDU"); Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */ return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); } static BOOL autodetect_send_continuous_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_start(context, sequenceNumber, RDP_BW_START_REQUEST_TYPE_CONTINUOUS); } BOOL autodetect_send_connecttime_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_start(context, sequenceNumber, RDP_BW_START_REQUEST_TYPE_CONNECTTIME); } BOOL autodetect_send_bandwidth_measure_payload(rdpContext* context, UINT16 payloadLength, UINT16 sequenceNumber) { wStream* s; UCHAR* buffer = NULL; BOOL bResult = FALSE; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Payload PDU -> payloadLength=%" PRIu16 "", payloadLength); /* 4-bytes aligned */ payloadLength &= ~3; if (!Stream_EnsureRemainingCapacity(s, 8 + payloadLength)) { Stream_Release(s); return FALSE; } Stream_Write_UINT8(s, 0x08); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, RDP_BW_PAYLOAD_REQUEST_TYPE); /* requestType (2 bytes) */ Stream_Write_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ /* Random data (better measurement in case the line is compressed) */ buffer = (UCHAR*)malloc(payloadLength); if (NULL == buffer) { Stream_Release(s); return FALSE; } winpr_RAND(buffer, payloadLength); Stream_Write(s, buffer, payloadLength); bResult = rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); free(buffer); return bResult; } static BOOL autodetect_send_bandwidth_measure_stop(rdpContext* context, UINT16 payloadLength, UINT16 sequenceNumber, UINT16 requestType) { wStream* s; UCHAR* buffer = NULL; BOOL bResult = FALSE; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Stop PDU -> payloadLength=%" PRIu16 "", payloadLength); /* 4-bytes aligned */ payloadLength &= ~3; Stream_Write_UINT8(s, requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME ? 0x08 : 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */ if (requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME) { Stream_Write_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ if (payloadLength > 0) { if (!Stream_EnsureRemainingCapacity(s, payloadLength)) { Stream_Release(s); return FALSE; } /* Random data (better measurement in case the line is compressed) */ buffer = malloc(payloadLength); if (NULL == buffer) { Stream_Release(s); return FALSE; } winpr_RAND(buffer, payloadLength); Stream_Write(s, buffer, payloadLength); } } bResult = rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); free(buffer); return bResult; } static BOOL autodetect_send_continuous_bandwidth_measure_stop(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_stop(context, 0, sequenceNumber, RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS); } BOOL autodetect_send_connecttime_bandwidth_measure_stop(rdpContext* context, UINT16 payloadLength, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_stop(context, payloadLength, sequenceNumber, RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME); } static BOOL autodetect_send_bandwidth_measure_results(rdpRdp* rdp, UINT16 responseType, UINT16 sequenceNumber) { BOOL success = TRUE; wStream* s; UINT64 timeDelta; /* Compute the total time */ timeDelta = GetTickCount64() - rdp->autodetect->bandwidthMeasureStartTime; /* Send the result PDU to the server */ s = rdp_message_channel_pdu_init(rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Results PDU -> timeDelta=%" PRIu32 ", byteCount=%" PRIu32 "", timeDelta, rdp->autodetect->bandwidthMeasureByteCount); Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, responseType); /* responseType (1 byte) */ Stream_Write_UINT32(s, timeDelta); /* timeDelta (4 bytes) */ Stream_Write_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ IFCALLRET(rdp->autodetect->ClientBandwidthMeasureResult, success, rdp->context, rdp->autodetect); if (!success) return FALSE; return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP); } static BOOL autodetect_send_netchar_result(rdpContext* context, UINT16 sequenceNumber) { wStream* s; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Network Characteristics Result PDU"); if (context->rdp->autodetect->netCharBandwidth > 0) { Stream_Write_UINT8(s, 0x12); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, 0x08C0); /* requestType (2 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ } else { Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, 0x0840); /* requestType (2 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ } return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); } static BOOL autodetect_send_netchar_sync(rdpRdp* rdp, UINT16 sequenceNumber) { wStream* s; /* Send the response PDU to the server */ s = rdp_message_channel_pdu_init(rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Network Characteristics Sync PDU -> bandwidth=%" PRIu32 ", rtt=%" PRIu32 "", rdp->autodetect->netCharBandwidth, rdp->autodetect->netCharAverageRTT); Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, RDP_NETCHAR_SYNC_RESPONSE_TYPE); /* responseType (1 byte) */ Stream_Write_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Write_UINT32(s, rdp->autodetect->netCharAverageRTT); /* rtt (4 bytes) */ return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP); } static BOOL autodetect_recv_rtt_measure_request(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { if (autodetectReqPdu->headerLength != 0x06) return FALSE; WLog_VRB(AUTODETECT_TAG, "received RTT Measure Request PDU"); /* Send a response to the server */ return autodetect_send_rtt_measure_response(rdp, autodetectReqPdu->sequenceNumber); } static BOOL autodetect_recv_rtt_measure_response(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x06) return FALSE; WLog_VRB(AUTODETECT_TAG, "received RTT Measure Response PDU"); rdp->autodetect->netCharAverageRTT = GetTickCount64() - rdp->autodetect->rttMeasureStartTime; if (rdp->autodetect->netCharBaseRTT == 0 || rdp->autodetect->netCharBaseRTT > rdp->autodetect->netCharAverageRTT) rdp->autodetect->netCharBaseRTT = rdp->autodetect->netCharAverageRTT; IFCALLRET(rdp->autodetect->RTTMeasureResponse, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; } static BOOL autodetect_recv_bandwidth_measure_start(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { if (autodetectReqPdu->headerLength != 0x06) return FALSE; WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Start PDU - time=%" PRIu64 "", GetTickCount64()); /* Initialize bandwidth measurement parameters */ rdp->autodetect->bandwidthMeasureStartTime = GetTickCount64(); rdp->autodetect->bandwidthMeasureByteCount = 0; /* Continuous Auto-Detection: mark the start of the measurement */ if (autodetectReqPdu->requestType == RDP_BW_START_REQUEST_TYPE_CONTINUOUS) { rdp->autodetect->bandwidthMeasureStarted = TRUE; } return TRUE; } static BOOL autodetect_recv_bandwidth_measure_payload(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { UINT16 payloadLength; if (autodetectReqPdu->headerLength != 0x08) return FALSE; if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ if (!Stream_SafeSeek(s, payloadLength)) return FALSE; WLog_DBG(AUTODETECT_TAG, "received Bandwidth Measure Payload PDU -> payloadLength=%" PRIu16 "", payloadLength); /* Add the payload length to the bandwidth measurement parameters */ rdp->autodetect->bandwidthMeasureByteCount += payloadLength; return TRUE; } static BOOL autodetect_recv_bandwidth_measure_stop(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { UINT16 payloadLength; UINT16 responseType; if (autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME) { if (autodetectReqPdu->headerLength != 0x08) return FALSE; if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ } else { if (autodetectReqPdu->headerLength != 0x06) return FALSE; payloadLength = 0; } if (!Stream_SafeSeek(s, payloadLength)) return FALSE; WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Stop PDU -> payloadLength=%" PRIu16 "", payloadLength); /* Add the payload length to the bandwidth measurement parameters */ rdp->autodetect->bandwidthMeasureByteCount += payloadLength; /* Continuous Auto-Detection: mark the stop of the measurement */ if (autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS) { rdp->autodetect->bandwidthMeasureStarted = FALSE; } /* Send a response the server */ responseType = autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME ? RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME : RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS; return autodetect_send_bandwidth_measure_results(rdp, responseType, autodetectReqPdu->sequenceNumber); } static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x0E) return FALSE; WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Results PDU"); Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ if (rdp->autodetect->bandwidthMeasureTimeDelta > 0) rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 / rdp->autodetect->bandwidthMeasureTimeDelta; else rdp->autodetect->netCharBandwidth = 0; IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; } static BOOL autodetect_recv_netchar_result(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { BOOL success = TRUE; switch (autodetectReqPdu->requestType) { case 0x0840: /* baseRTT and averageRTT fields are present (bandwidth field is not) */ if ((autodetectReqPdu->headerLength != 0x0E) || (Stream_GetRemainingLength(s) < 8)) return FALSE; Stream_Read_UINT32(s, rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ break; case 0x0880: /* bandwidth and averageRTT fields are present (baseRTT field is not) */ if ((autodetectReqPdu->headerLength != 0x0E) || (Stream_GetRemainingLength(s) < 8)) return FALSE; Stream_Read_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ break; case 0x08C0: /* baseRTT, bandwidth, and averageRTT fields are present */ if ((autodetectReqPdu->headerLength != 0x12) || (Stream_GetRemainingLength(s) < 12)) return FALSE; Stream_Read_UINT32(s, rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ break; } WLog_VRB(AUTODETECT_TAG, "received Network Characteristics Result PDU -> baseRTT=%" PRIu32 ", bandwidth=%" PRIu32 ", averageRTT=%" PRIu32 "", rdp->autodetect->netCharBaseRTT, rdp->autodetect->netCharBandwidth, rdp->autodetect->netCharAverageRTT); IFCALLRET(rdp->autodetect->NetworkCharacteristicsResult, success, rdp->context, autodetectReqPdu->sequenceNumber); return success; } int rdp_recv_autodetect_request_packet(rdpRdp* rdp, wStream* s) { AUTODETECT_REQ_PDU autodetectReqPdu; BOOL success = FALSE; if (Stream_GetRemainingLength(s) < 6) return -1; Stream_Read_UINT8(s, autodetectReqPdu.headerLength); /* headerLength (1 byte) */ Stream_Read_UINT8(s, autodetectReqPdu.headerTypeId); /* headerTypeId (1 byte) */ Stream_Read_UINT16(s, autodetectReqPdu.sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Read_UINT16(s, autodetectReqPdu.requestType); /* requestType (2 bytes) */ WLog_VRB(AUTODETECT_TAG, "rdp_recv_autodetect_request_packet: headerLength=%" PRIu8 ", headerTypeId=%" PRIu8 ", sequenceNumber=%" PRIu16 ", requestType=%04" PRIx16 "", autodetectReqPdu.headerLength, autodetectReqPdu.headerTypeId, autodetectReqPdu.sequenceNumber, autodetectReqPdu.requestType); if (autodetectReqPdu.headerTypeId != TYPE_ID_AUTODETECT_REQUEST) return -1; switch (autodetectReqPdu.requestType) { case RDP_RTT_REQUEST_TYPE_CONTINUOUS: case RDP_RTT_REQUEST_TYPE_CONNECTTIME: /* RTT Measure Request (RDP_RTT_REQUEST) - MS-RDPBCGR 2.2.14.1.1 */ success = autodetect_recv_rtt_measure_request(rdp, s, &autodetectReqPdu); break; case RDP_BW_START_REQUEST_TYPE_CONTINUOUS: case RDP_BW_START_REQUEST_TYPE_TUNNEL: case RDP_BW_START_REQUEST_TYPE_CONNECTTIME: /* Bandwidth Measure Start (RDP_BW_START) - MS-RDPBCGR 2.2.14.1.2 */ success = autodetect_recv_bandwidth_measure_start(rdp, s, &autodetectReqPdu); break; case RDP_BW_PAYLOAD_REQUEST_TYPE: /* Bandwidth Measure Payload (RDP_BW_PAYLOAD) - MS-RDPBCGR 2.2.14.1.3 */ success = autodetect_recv_bandwidth_measure_payload(rdp, s, &autodetectReqPdu); break; case RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME: case RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS: case RDP_BW_STOP_REQUEST_TYPE_TUNNEL: /* Bandwidth Measure Stop (RDP_BW_STOP) - MS-RDPBCGR 2.2.14.1.4 */ success = autodetect_recv_bandwidth_measure_stop(rdp, s, &autodetectReqPdu); break; case 0x0840: case 0x0880: case 0x08C0: /* Network Characteristics Result (RDP_NETCHAR_RESULT) - MS-RDPBCGR 2.2.14.1.5 */ success = autodetect_recv_netchar_result(rdp, s, &autodetectReqPdu); break; default: break; } return success ? 0 : -1; } int rdp_recv_autodetect_response_packet(rdpRdp* rdp, wStream* s) { AUTODETECT_RSP_PDU autodetectRspPdu; BOOL success = FALSE; if (Stream_GetRemainingLength(s) < 6) return -1; Stream_Read_UINT8(s, autodetectRspPdu.headerLength); /* headerLength (1 byte) */ Stream_Read_UINT8(s, autodetectRspPdu.headerTypeId); /* headerTypeId (1 byte) */ Stream_Read_UINT16(s, autodetectRspPdu.sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Read_UINT16(s, autodetectRspPdu.responseType); /* responseType (2 bytes) */ WLog_VRB(AUTODETECT_TAG, "rdp_recv_autodetect_response_packet: headerLength=%" PRIu8 ", headerTypeId=%" PRIu8 ", sequenceNumber=%" PRIu16 ", requestType=%04" PRIx16 "", autodetectRspPdu.headerLength, autodetectRspPdu.headerTypeId, autodetectRspPdu.sequenceNumber, autodetectRspPdu.responseType); if (autodetectRspPdu.headerTypeId != TYPE_ID_AUTODETECT_RESPONSE) return -1; switch (autodetectRspPdu.responseType) { case RDP_RTT_RESPONSE_TYPE: /* RTT Measure Response (RDP_RTT_RESPONSE) - MS-RDPBCGR 2.2.14.2.1 */ success = autodetect_recv_rtt_measure_response(rdp, s, &autodetectRspPdu); break; case RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME: case RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS: /* Bandwidth Measure Results (RDP_BW_RESULTS) - MS-RDPBCGR 2.2.14.2.2 */ success = autodetect_recv_bandwidth_measure_results(rdp, s, &autodetectRspPdu); break; default: break; } return success ? 0 : -1; } rdpAutoDetect* autodetect_new(void) { rdpAutoDetect* autoDetect = (rdpAutoDetect*)calloc(1, sizeof(rdpAutoDetect)); if (autoDetect) { } return autoDetect; } void autodetect_free(rdpAutoDetect* autoDetect) { free(autoDetect); } void autodetect_register_server_callbacks(rdpAutoDetect* autodetect) { autodetect->RTTMeasureRequest = autodetect_send_continuous_rtt_measure_request; autodetect->BandwidthMeasureStart = autodetect_send_continuous_bandwidth_measure_start; autodetect->BandwidthMeasureStop = autodetect_send_continuous_bandwidth_measure_stop; autodetect->NetworkCharacteristicsResult = autodetect_send_netchar_result; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3911_1
crossvul-cpp_data_bad_2680_0
/* NetBSD: print-juniper.c,v 1.2 2007/07/24 11:53:45 drochner Exp */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: DLT_JUNIPER_* printers */ #ifndef lint #else __RCSID("NetBSD: print-juniper.c,v 1.3 2007/07/25 06:31:32 dogcow Exp "); #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ppp.h" #include "llc.h" #include "nlpid.h" #include "ethertype.h" #include "atm.h" #define JUNIPER_BPF_OUT 0 /* Outgoing packet */ #define JUNIPER_BPF_IN 1 /* Incoming packet */ #define JUNIPER_BPF_PKT_IN 0x1 /* Incoming packet */ #define JUNIPER_BPF_NO_L2 0x2 /* L2 header stripped */ #define JUNIPER_BPF_IIF 0x4 /* IIF is valid */ #define JUNIPER_BPF_FILTER 0x40 /* BPF filtering is supported */ #define JUNIPER_BPF_EXT 0x80 /* extensions present */ #define JUNIPER_MGC_NUMBER 0x4d4743 /* = "MGC" */ #define JUNIPER_LSQ_COOKIE_RE (1 << 3) #define JUNIPER_LSQ_COOKIE_DIR (1 << 2) #define JUNIPER_LSQ_L3_PROTO_SHIFT 4 #define JUNIPER_LSQ_L3_PROTO_MASK (0x17 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_IPV4 (0 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_IPV6 (1 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_MPLS (2 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_ISO (3 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define AS_PIC_COOKIE_LEN 8 #define JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE 1 #define JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE 2 #define JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE 3 #define JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE 4 #define JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE 5 static const struct tok juniper_ipsec_type_values[] = { { JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE, "ESP ENCR-AUTH" }, { JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE, "ESP ENCR-AH AUTH" }, { JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE, "ESP AUTH" }, { JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE, "AH AUTH" }, { JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE, "ESP ENCR" }, { 0, NULL} }; static const struct tok juniper_direction_values[] = { { JUNIPER_BPF_IN, "In"}, { JUNIPER_BPF_OUT, "Out"}, { 0, NULL} }; /* codepoints for encoding extensions to a .pcap file */ enum { JUNIPER_EXT_TLV_IFD_IDX = 1, JUNIPER_EXT_TLV_IFD_NAME = 2, JUNIPER_EXT_TLV_IFD_MEDIATYPE = 3, JUNIPER_EXT_TLV_IFL_IDX = 4, JUNIPER_EXT_TLV_IFL_UNIT = 5, JUNIPER_EXT_TLV_IFL_ENCAPS = 6, JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE = 7, JUNIPER_EXT_TLV_TTP_IFL_ENCAPS = 8 }; /* 1 byte type and 1-byte length */ #define JUNIPER_EXT_TLV_OVERHEAD 2U static const struct tok jnx_ext_tlv_values[] = { { JUNIPER_EXT_TLV_IFD_IDX, "Device Interface Index" }, { JUNIPER_EXT_TLV_IFD_NAME,"Device Interface Name" }, { JUNIPER_EXT_TLV_IFD_MEDIATYPE, "Device Media Type" }, { JUNIPER_EXT_TLV_IFL_IDX, "Logical Interface Index" }, { JUNIPER_EXT_TLV_IFL_UNIT,"Logical Unit Number" }, { JUNIPER_EXT_TLV_IFL_ENCAPS, "Logical Interface Encapsulation" }, { JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE, "TTP derived Device Media Type" }, { JUNIPER_EXT_TLV_TTP_IFL_ENCAPS, "TTP derived Logical Interface Encapsulation" }, { 0, NULL } }; static const struct tok jnx_flag_values[] = { { JUNIPER_BPF_EXT, "Ext" }, { JUNIPER_BPF_FILTER, "Filter" }, { JUNIPER_BPF_IIF, "IIF" }, { JUNIPER_BPF_NO_L2, "no-L2" }, { JUNIPER_BPF_PKT_IN, "In" }, { 0, NULL } }; #define JUNIPER_IFML_ETHER 1 #define JUNIPER_IFML_FDDI 2 #define JUNIPER_IFML_TOKENRING 3 #define JUNIPER_IFML_PPP 4 #define JUNIPER_IFML_FRAMERELAY 5 #define JUNIPER_IFML_CISCOHDLC 6 #define JUNIPER_IFML_SMDSDXI 7 #define JUNIPER_IFML_ATMPVC 8 #define JUNIPER_IFML_PPP_CCC 9 #define JUNIPER_IFML_FRAMERELAY_CCC 10 #define JUNIPER_IFML_IPIP 11 #define JUNIPER_IFML_GRE 12 #define JUNIPER_IFML_PIM 13 #define JUNIPER_IFML_PIMD 14 #define JUNIPER_IFML_CISCOHDLC_CCC 15 #define JUNIPER_IFML_VLAN_CCC 16 #define JUNIPER_IFML_MLPPP 17 #define JUNIPER_IFML_MLFR 18 #define JUNIPER_IFML_ML 19 #define JUNIPER_IFML_LSI 20 #define JUNIPER_IFML_DFE 21 #define JUNIPER_IFML_ATM_CELLRELAY_CCC 22 #define JUNIPER_IFML_CRYPTO 23 #define JUNIPER_IFML_GGSN 24 #define JUNIPER_IFML_LSI_PPP 25 #define JUNIPER_IFML_LSI_CISCOHDLC 26 #define JUNIPER_IFML_PPP_TCC 27 #define JUNIPER_IFML_FRAMERELAY_TCC 28 #define JUNIPER_IFML_CISCOHDLC_TCC 29 #define JUNIPER_IFML_ETHERNET_CCC 30 #define JUNIPER_IFML_VT 31 #define JUNIPER_IFML_EXTENDED_VLAN_CCC 32 #define JUNIPER_IFML_ETHER_OVER_ATM 33 #define JUNIPER_IFML_MONITOR 34 #define JUNIPER_IFML_ETHERNET_TCC 35 #define JUNIPER_IFML_VLAN_TCC 36 #define JUNIPER_IFML_EXTENDED_VLAN_TCC 37 #define JUNIPER_IFML_CONTROLLER 38 #define JUNIPER_IFML_MFR 39 #define JUNIPER_IFML_LS 40 #define JUNIPER_IFML_ETHERNET_VPLS 41 #define JUNIPER_IFML_ETHERNET_VLAN_VPLS 42 #define JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS 43 #define JUNIPER_IFML_LT 44 #define JUNIPER_IFML_SERVICES 45 #define JUNIPER_IFML_ETHER_VPLS_OVER_ATM 46 #define JUNIPER_IFML_FR_PORT_CCC 47 #define JUNIPER_IFML_FRAMERELAY_EXT_CCC 48 #define JUNIPER_IFML_FRAMERELAY_EXT_TCC 49 #define JUNIPER_IFML_FRAMERELAY_FLEX 50 #define JUNIPER_IFML_GGSNI 51 #define JUNIPER_IFML_ETHERNET_FLEX 52 #define JUNIPER_IFML_COLLECTOR 53 #define JUNIPER_IFML_AGGREGATOR 54 #define JUNIPER_IFML_LAPD 55 #define JUNIPER_IFML_PPPOE 56 #define JUNIPER_IFML_PPP_SUBORDINATE 57 #define JUNIPER_IFML_CISCOHDLC_SUBORDINATE 58 #define JUNIPER_IFML_DFC 59 #define JUNIPER_IFML_PICPEER 60 static const struct tok juniper_ifmt_values[] = { { JUNIPER_IFML_ETHER, "Ethernet" }, { JUNIPER_IFML_FDDI, "FDDI" }, { JUNIPER_IFML_TOKENRING, "Token-Ring" }, { JUNIPER_IFML_PPP, "PPP" }, { JUNIPER_IFML_PPP_SUBORDINATE, "PPP-Subordinate" }, { JUNIPER_IFML_FRAMERELAY, "Frame-Relay" }, { JUNIPER_IFML_CISCOHDLC, "Cisco-HDLC" }, { JUNIPER_IFML_SMDSDXI, "SMDS-DXI" }, { JUNIPER_IFML_ATMPVC, "ATM-PVC" }, { JUNIPER_IFML_PPP_CCC, "PPP-CCC" }, { JUNIPER_IFML_FRAMERELAY_CCC, "Frame-Relay-CCC" }, { JUNIPER_IFML_FRAMERELAY_EXT_CCC, "Extended FR-CCC" }, { JUNIPER_IFML_IPIP, "IP-over-IP" }, { JUNIPER_IFML_GRE, "GRE" }, { JUNIPER_IFML_PIM, "PIM-Encapsulator" }, { JUNIPER_IFML_PIMD, "PIM-Decapsulator" }, { JUNIPER_IFML_CISCOHDLC_CCC, "Cisco-HDLC-CCC" }, { JUNIPER_IFML_VLAN_CCC, "VLAN-CCC" }, { JUNIPER_IFML_EXTENDED_VLAN_CCC, "Extended-VLAN-CCC" }, { JUNIPER_IFML_MLPPP, "Multilink-PPP" }, { JUNIPER_IFML_MLFR, "Multilink-FR" }, { JUNIPER_IFML_MFR, "Multilink-FR-UNI-NNI" }, { JUNIPER_IFML_ML, "Multilink" }, { JUNIPER_IFML_LS, "LinkService" }, { JUNIPER_IFML_LSI, "LSI" }, { JUNIPER_IFML_ATM_CELLRELAY_CCC, "ATM-CCC-Cell-Relay" }, { JUNIPER_IFML_CRYPTO, "IPSEC-over-IP" }, { JUNIPER_IFML_GGSN, "GGSN" }, { JUNIPER_IFML_PPP_TCC, "PPP-TCC" }, { JUNIPER_IFML_FRAMERELAY_TCC, "Frame-Relay-TCC" }, { JUNIPER_IFML_FRAMERELAY_EXT_TCC, "Extended FR-TCC" }, { JUNIPER_IFML_CISCOHDLC_TCC, "Cisco-HDLC-TCC" }, { JUNIPER_IFML_ETHERNET_CCC, "Ethernet-CCC" }, { JUNIPER_IFML_VT, "VPN-Loopback-tunnel" }, { JUNIPER_IFML_ETHER_OVER_ATM, "Ethernet-over-ATM" }, { JUNIPER_IFML_ETHER_VPLS_OVER_ATM, "Ethernet-VPLS-over-ATM" }, { JUNIPER_IFML_MONITOR, "Monitor" }, { JUNIPER_IFML_ETHERNET_TCC, "Ethernet-TCC" }, { JUNIPER_IFML_VLAN_TCC, "VLAN-TCC" }, { JUNIPER_IFML_EXTENDED_VLAN_TCC, "Extended-VLAN-TCC" }, { JUNIPER_IFML_CONTROLLER, "Controller" }, { JUNIPER_IFML_ETHERNET_VPLS, "VPLS" }, { JUNIPER_IFML_ETHERNET_VLAN_VPLS, "VLAN-VPLS" }, { JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS, "Extended-VLAN-VPLS" }, { JUNIPER_IFML_LT, "Logical-tunnel" }, { JUNIPER_IFML_SERVICES, "General-Services" }, { JUNIPER_IFML_PPPOE, "PPPoE" }, { JUNIPER_IFML_ETHERNET_FLEX, "Flexible-Ethernet-Services" }, { JUNIPER_IFML_FRAMERELAY_FLEX, "Flexible-FrameRelay" }, { JUNIPER_IFML_COLLECTOR, "Flow-collection" }, { JUNIPER_IFML_PICPEER, "PIC Peer" }, { JUNIPER_IFML_DFC, "Dynamic-Flow-Capture" }, {0, NULL} }; #define JUNIPER_IFLE_ATM_SNAP 2 #define JUNIPER_IFLE_ATM_NLPID 3 #define JUNIPER_IFLE_ATM_VCMUX 4 #define JUNIPER_IFLE_ATM_LLC 5 #define JUNIPER_IFLE_ATM_PPP_VCMUX 6 #define JUNIPER_IFLE_ATM_PPP_LLC 7 #define JUNIPER_IFLE_ATM_PPP_FUNI 8 #define JUNIPER_IFLE_ATM_CCC 9 #define JUNIPER_IFLE_FR_NLPID 10 #define JUNIPER_IFLE_FR_SNAP 11 #define JUNIPER_IFLE_FR_PPP 12 #define JUNIPER_IFLE_FR_CCC 13 #define JUNIPER_IFLE_ENET2 14 #define JUNIPER_IFLE_IEEE8023_SNAP 15 #define JUNIPER_IFLE_IEEE8023_LLC 16 #define JUNIPER_IFLE_PPP 17 #define JUNIPER_IFLE_CISCOHDLC 18 #define JUNIPER_IFLE_PPP_CCC 19 #define JUNIPER_IFLE_IPIP_NULL 20 #define JUNIPER_IFLE_PIM_NULL 21 #define JUNIPER_IFLE_GRE_NULL 22 #define JUNIPER_IFLE_GRE_PPP 23 #define JUNIPER_IFLE_PIMD_DECAPS 24 #define JUNIPER_IFLE_CISCOHDLC_CCC 25 #define JUNIPER_IFLE_ATM_CISCO_NLPID 26 #define JUNIPER_IFLE_VLAN_CCC 27 #define JUNIPER_IFLE_MLPPP 28 #define JUNIPER_IFLE_MLFR 29 #define JUNIPER_IFLE_LSI_NULL 30 #define JUNIPER_IFLE_AGGREGATE_UNUSED 31 #define JUNIPER_IFLE_ATM_CELLRELAY_CCC 32 #define JUNIPER_IFLE_CRYPTO 33 #define JUNIPER_IFLE_GGSN 34 #define JUNIPER_IFLE_ATM_TCC 35 #define JUNIPER_IFLE_FR_TCC 36 #define JUNIPER_IFLE_PPP_TCC 37 #define JUNIPER_IFLE_CISCOHDLC_TCC 38 #define JUNIPER_IFLE_ETHERNET_CCC 39 #define JUNIPER_IFLE_VT 40 #define JUNIPER_IFLE_ATM_EOA_LLC 41 #define JUNIPER_IFLE_EXTENDED_VLAN_CCC 42 #define JUNIPER_IFLE_ATM_SNAP_TCC 43 #define JUNIPER_IFLE_MONITOR 44 #define JUNIPER_IFLE_ETHERNET_TCC 45 #define JUNIPER_IFLE_VLAN_TCC 46 #define JUNIPER_IFLE_EXTENDED_VLAN_TCC 47 #define JUNIPER_IFLE_MFR 48 #define JUNIPER_IFLE_ETHERNET_VPLS 49 #define JUNIPER_IFLE_ETHERNET_VLAN_VPLS 50 #define JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS 51 #define JUNIPER_IFLE_SERVICES 52 #define JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC 53 #define JUNIPER_IFLE_FR_PORT_CCC 54 #define JUNIPER_IFLE_ATM_MLPPP_LLC 55 #define JUNIPER_IFLE_ATM_EOA_CCC 56 #define JUNIPER_IFLE_LT_VLAN 57 #define JUNIPER_IFLE_COLLECTOR 58 #define JUNIPER_IFLE_AGGREGATOR 59 #define JUNIPER_IFLE_LAPD 60 #define JUNIPER_IFLE_ATM_PPPOE_LLC 61 #define JUNIPER_IFLE_ETHERNET_PPPOE 62 #define JUNIPER_IFLE_PPPOE 63 #define JUNIPER_IFLE_PPP_SUBORDINATE 64 #define JUNIPER_IFLE_CISCOHDLC_SUBORDINATE 65 #define JUNIPER_IFLE_DFC 66 #define JUNIPER_IFLE_PICPEER 67 static const struct tok juniper_ifle_values[] = { { JUNIPER_IFLE_AGGREGATOR, "Aggregator" }, { JUNIPER_IFLE_ATM_CCC, "CCC over ATM" }, { JUNIPER_IFLE_ATM_CELLRELAY_CCC, "ATM CCC Cell Relay" }, { JUNIPER_IFLE_ATM_CISCO_NLPID, "CISCO compatible NLPID" }, { JUNIPER_IFLE_ATM_EOA_CCC, "Ethernet over ATM CCC" }, { JUNIPER_IFLE_ATM_EOA_LLC, "Ethernet over ATM LLC" }, { JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC, "Ethernet VPLS over ATM LLC" }, { JUNIPER_IFLE_ATM_LLC, "ATM LLC" }, { JUNIPER_IFLE_ATM_MLPPP_LLC, "MLPPP over ATM LLC" }, { JUNIPER_IFLE_ATM_NLPID, "ATM NLPID" }, { JUNIPER_IFLE_ATM_PPPOE_LLC, "PPPoE over ATM LLC" }, { JUNIPER_IFLE_ATM_PPP_FUNI, "PPP over FUNI" }, { JUNIPER_IFLE_ATM_PPP_LLC, "PPP over ATM LLC" }, { JUNIPER_IFLE_ATM_PPP_VCMUX, "PPP over ATM VCMUX" }, { JUNIPER_IFLE_ATM_SNAP, "ATM SNAP" }, { JUNIPER_IFLE_ATM_SNAP_TCC, "ATM SNAP TCC" }, { JUNIPER_IFLE_ATM_TCC, "ATM VCMUX TCC" }, { JUNIPER_IFLE_ATM_VCMUX, "ATM VCMUX" }, { JUNIPER_IFLE_CISCOHDLC, "C-HDLC" }, { JUNIPER_IFLE_CISCOHDLC_CCC, "C-HDLC CCC" }, { JUNIPER_IFLE_CISCOHDLC_SUBORDINATE, "C-HDLC via dialer" }, { JUNIPER_IFLE_CISCOHDLC_TCC, "C-HDLC TCC" }, { JUNIPER_IFLE_COLLECTOR, "Collector" }, { JUNIPER_IFLE_CRYPTO, "Crypto" }, { JUNIPER_IFLE_ENET2, "Ethernet" }, { JUNIPER_IFLE_ETHERNET_CCC, "Ethernet CCC" }, { JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS, "Extended VLAN VPLS" }, { JUNIPER_IFLE_ETHERNET_PPPOE, "PPPoE over Ethernet" }, { JUNIPER_IFLE_ETHERNET_TCC, "Ethernet TCC" }, { JUNIPER_IFLE_ETHERNET_VLAN_VPLS, "VLAN VPLS" }, { JUNIPER_IFLE_ETHERNET_VPLS, "VPLS" }, { JUNIPER_IFLE_EXTENDED_VLAN_CCC, "Extended VLAN CCC" }, { JUNIPER_IFLE_EXTENDED_VLAN_TCC, "Extended VLAN TCC" }, { JUNIPER_IFLE_FR_CCC, "FR CCC" }, { JUNIPER_IFLE_FR_NLPID, "FR NLPID" }, { JUNIPER_IFLE_FR_PORT_CCC, "FR CCC" }, { JUNIPER_IFLE_FR_PPP, "FR PPP" }, { JUNIPER_IFLE_FR_SNAP, "FR SNAP" }, { JUNIPER_IFLE_FR_TCC, "FR TCC" }, { JUNIPER_IFLE_GGSN, "GGSN" }, { JUNIPER_IFLE_GRE_NULL, "GRE NULL" }, { JUNIPER_IFLE_GRE_PPP, "PPP over GRE" }, { JUNIPER_IFLE_IPIP_NULL, "IPIP" }, { JUNIPER_IFLE_LAPD, "LAPD" }, { JUNIPER_IFLE_LSI_NULL, "LSI Null" }, { JUNIPER_IFLE_LT_VLAN, "LT VLAN" }, { JUNIPER_IFLE_MFR, "MFR" }, { JUNIPER_IFLE_MLFR, "MLFR" }, { JUNIPER_IFLE_MLPPP, "MLPPP" }, { JUNIPER_IFLE_MONITOR, "Monitor" }, { JUNIPER_IFLE_PIMD_DECAPS, "PIMd" }, { JUNIPER_IFLE_PIM_NULL, "PIM Null" }, { JUNIPER_IFLE_PPP, "PPP" }, { JUNIPER_IFLE_PPPOE, "PPPoE" }, { JUNIPER_IFLE_PPP_CCC, "PPP CCC" }, { JUNIPER_IFLE_PPP_SUBORDINATE, "" }, { JUNIPER_IFLE_PPP_TCC, "PPP TCC" }, { JUNIPER_IFLE_SERVICES, "General Services" }, { JUNIPER_IFLE_VLAN_CCC, "VLAN CCC" }, { JUNIPER_IFLE_VLAN_TCC, "VLAN TCC" }, { JUNIPER_IFLE_VT, "VT" }, {0, NULL} }; struct juniper_cookie_table_t { uint32_t pictype; /* pic type */ uint8_t cookie_len; /* cookie len */ const char *s; /* pic name */ }; static const struct juniper_cookie_table_t juniper_cookie_table[] = { #ifdef DLT_JUNIPER_ATM1 { DLT_JUNIPER_ATM1, 4, "ATM1"}, #endif #ifdef DLT_JUNIPER_ATM2 { DLT_JUNIPER_ATM2, 8, "ATM2"}, #endif #ifdef DLT_JUNIPER_MLPPP { DLT_JUNIPER_MLPPP, 2, "MLPPP"}, #endif #ifdef DLT_JUNIPER_MLFR { DLT_JUNIPER_MLFR, 2, "MLFR"}, #endif #ifdef DLT_JUNIPER_MFR { DLT_JUNIPER_MFR, 4, "MFR"}, #endif #ifdef DLT_JUNIPER_PPPOE { DLT_JUNIPER_PPPOE, 0, "PPPoE"}, #endif #ifdef DLT_JUNIPER_PPPOE_ATM { DLT_JUNIPER_PPPOE_ATM, 0, "PPPoE ATM"}, #endif #ifdef DLT_JUNIPER_GGSN { DLT_JUNIPER_GGSN, 8, "GGSN"}, #endif #ifdef DLT_JUNIPER_MONITOR { DLT_JUNIPER_MONITOR, 8, "MONITOR"}, #endif #ifdef DLT_JUNIPER_SERVICES { DLT_JUNIPER_SERVICES, 8, "AS"}, #endif #ifdef DLT_JUNIPER_ES { DLT_JUNIPER_ES, 0, "ES"}, #endif { 0, 0, NULL } }; struct juniper_l2info_t { uint32_t length; uint32_t caplen; uint32_t pictype; uint8_t direction; uint8_t header_len; uint8_t cookie_len; uint8_t cookie_type; uint8_t cookie[8]; uint8_t bundle; uint16_t proto; uint8_t flags; }; #define LS_COOKIE_ID 0x54 #define AS_COOKIE_ID 0x47 #define LS_MLFR_COOKIE_LEN 4 #define ML_MLFR_COOKIE_LEN 2 #define LS_MFR_COOKIE_LEN 6 #define ATM1_COOKIE_LEN 4 #define ATM2_COOKIE_LEN 8 #define ATM2_PKT_TYPE_MASK 0x70 #define ATM2_GAP_COUNT_MASK 0x3F #define JUNIPER_PROTO_NULL 1 #define JUNIPER_PROTO_IPV4 2 #define JUNIPER_PROTO_IPV6 6 #define MFR_BE_MASK 0xc0 static const struct tok juniper_protocol_values[] = { { JUNIPER_PROTO_NULL, "Null" }, { JUNIPER_PROTO_IPV4, "IPv4" }, { JUNIPER_PROTO_IPV6, "IPv6" }, { 0, NULL} }; static int ip_heuristic_guess(netdissect_options *, register const u_char *, u_int); static int juniper_ppp_heuristic_guess(netdissect_options *, register const u_char *, u_int); static int juniper_parse_header(netdissect_options *, const u_char *, const struct pcap_pkthdr *, struct juniper_l2info_t *); #ifdef DLT_JUNIPER_GGSN u_int juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; ND_TCHECK(*gh); if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_ES u_int juniper_es_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ipsec_header { uint8_t sa_index[2]; uint8_t ttl; uint8_t type; uint8_t spi[4]; uint8_t src_ip[4]; uint8_t dst_ip[4]; }; u_int rewrite_len,es_type_bundle; const struct juniper_ipsec_header *ih; l2info.pictype = DLT_JUNIPER_ES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ih = (const struct juniper_ipsec_header *)p; ND_TCHECK(*ih); switch (ih->type) { case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE: rewrite_len = 0; es_type_bundle = 1; break; case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE: rewrite_len = 16; es_type_bundle = 0; break; default: ND_PRINT((ndo, "ES Invalid type %u, length %u", ih->type, l2info.length)); return l2info.header_len; } l2info.length-=rewrite_len; p+=rewrite_len; if (ndo->ndo_eflag) { if (!es_type_bundle) { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, EXTRACT_32BITS(&ih->spi), ipaddr_string(ndo, &ih->src_ip), ipaddr_string(ndo, &ih->dst_ip), l2info.length)); } else { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, l2info.length)); } } ip_print(ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MONITOR u_int juniper_monitor_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_monitor_header { uint8_t pkt_type; uint8_t padding; uint8_t iif[2]; uint8_t service_id[4]; }; const struct juniper_monitor_header *mh; l2info.pictype = DLT_JUNIPER_MONITOR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; mh = (const struct juniper_monitor_header *)p; ND_TCHECK(*mh); if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ", EXTRACT_32BITS(&mh->service_id), EXTRACT_16BITS(&mh->iif), mh->pkt_type)); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_SERVICES u_int juniper_services_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_services_header { uint8_t svc_id; uint8_t flags_len; uint8_t svc_set_id[2]; uint8_t dir_iif[4]; }; const struct juniper_services_header *sh; l2info.pictype = DLT_JUNIPER_SERVICES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; sh = (const struct juniper_services_header *)p; ND_TCHECK(*sh); if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ", sh->svc_id, sh->flags_len, EXTRACT_16BITS(&sh->svc_set_id), EXTRACT_24BITS(&sh->dir_iif[1]))); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPPOE u_int juniper_pppoe_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_PPPOE; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw ethernet frames */ ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_ETHER u_int juniper_ether_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ETHER; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw Ethernet frames */ ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPP u_int juniper_ppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_PPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw ppp frames */ ppp_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_FRELAY u_int juniper_frelay_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_FRELAY; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw frame-relay frames */ fr_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_CHDLC u_int juniper_chdlc_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_CHDLC; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw c-hdlc frames */ chdlc_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPPOE_ATM u_int juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ND_TCHECK2(p[0], 2); extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_pppoe_atm]")); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MLPPP u_int juniper_mlppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLPPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link * best indicator if the cookie looks like a proto */ if (ndo->ndo_eflag && EXTRACT_16BITS(&l2info.cookie) != PPP_OSI && EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL)) ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle)); p+=l2info.header_len; /* first try the LSQ protos */ switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: /* IP traffic going to the RE would not have a cookie * -> this must be incoming IS-IS over PPP */ if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR)) ppp_print(ndo, p, l2info.length); else ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length); return l2info.header_len; default: break; } /* zero length cookie ? */ switch (EXTRACT_16BITS(&l2info.cookie)) { case PPP_OSI: ppp_print(ndo, p - 2, l2info.length + 2); break; case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */ default: ppp_print(ndo, p, l2info.length); break; } return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MFR u_int juniper_mfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; memset(&l2info, 0, sizeof(l2info)); l2info.pictype = DLT_JUNIPER_MFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* child-link ? */ if (l2info.cookie_len == 0) { mfr_print(ndo, p, l2info.length); return l2info.header_len; } /* first try the LSQ protos */ if (l2info.cookie_len == AS_PIC_COOKIE_LEN) { switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length); return l2info.header_len; default: break; } return l2info.header_len; } /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLCSAP_ISONS<<8 | LLCSAP_ISONS): isoclns_print(ndo, p + 1, l2info.length - 1); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MLFR u_int juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } #endif /* * ATM1 PIC cookie format * * +-----+-------------------------+-------------------------------+ * |fmtid| vc index | channel ID | * +-----+-------------------------+-------------------------------+ */ #ifdef DLT_JUNIPER_ATM1 u_int juniper_atm1_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM1; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[0] == 0x80) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } ND_TCHECK2(p[0], 3); if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_atm1]")); return l2info.header_len; } #endif /* * ATM2 PIC cookie format * * +-------------------------------+---------+---+-----+-----------+ * | channel ID | reserv |AAL| CCRQ| gap cnt | * +-------------------------------+---------+---+-----+-----------+ */ #ifdef DLT_JUNIPER_ATM2 u_int juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } ND_TCHECK2(p[0], 3); if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_atm2]")); return l2info.header_len; } #endif /* try to guess, based on all PPP protos that are supported in * a juniper router if the payload data is encapsulated using PPP */ static int juniper_ppp_heuristic_guess(netdissect_options *ndo, register const u_char *p, u_int length) { switch(EXTRACT_16BITS(p)) { case PPP_IP : case PPP_OSI : case PPP_MPLS_UCAST : case PPP_MPLS_MCAST : case PPP_IPCP : case PPP_OSICP : case PPP_MPLSCP : case PPP_LCP : case PPP_PAP : case PPP_CHAP : case PPP_ML : case PPP_IPV6 : case PPP_IPV6CP : ppp_print(ndo, p, length); break; default: return 0; /* did not find a ppp header */ break; } return 1; /* we printed a ppp packet */ } static int ip_heuristic_guess(netdissect_options *ndo, register const u_char *p, u_int length) { switch(p[0]) { case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: ip_print(ndo, p, length); break; case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: ip6_print(ndo, p, length); break; default: return 0; /* did not find a ip header */ break; } return 1; /* we printed an v4/v6 packet */ } static int juniper_read_tlv_value(const u_char *p, u_int tlv_type, u_int tlv_len) { int tlv_value; /* TLVs < 128 are little endian encoded */ if (tlv_type < 128) { switch (tlv_len) { case 1: tlv_value = *p; break; case 2: tlv_value = EXTRACT_LE_16BITS(p); break; case 3: tlv_value = EXTRACT_LE_24BITS(p); break; case 4: tlv_value = EXTRACT_LE_32BITS(p); break; default: tlv_value = -1; break; } } else { /* TLVs >= 128 are big endian encoded */ switch (tlv_len) { case 1: tlv_value = *p; break; case 2: tlv_value = EXTRACT_16BITS(p); break; case 3: tlv_value = EXTRACT_24BITS(p); break; case 4: tlv_value = EXTRACT_32BITS(p); break; default: tlv_value = -1; break; } } return tlv_value; } static int juniper_parse_header(netdissect_options *ndo, const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info) { const struct juniper_cookie_table_t *lp = juniper_cookie_table; u_int idx, jnx_ext_len, jnx_header_len = 0; uint8_t tlv_type,tlv_len; uint32_t control_word; int tlv_value; const u_char *tptr; l2info->header_len = 0; l2info->cookie_len = 0; l2info->proto = 0; l2info->length = h->len; l2info->caplen = h->caplen; ND_TCHECK2(p[0], 4); l2info->flags = p[3]; l2info->direction = p[3]&JUNIPER_BPF_PKT_IN; if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */ ND_PRINT((ndo, "no magic-number found!")); return 0; } if (ndo->ndo_eflag) /* print direction */ ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction))); /* magic number + flags */ jnx_header_len = 4; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]", bittok2str(jnx_flag_values, "none", l2info->flags))); /* extensions present ? - calculate how much bytes to skip */ if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) { tptr = p+jnx_header_len; /* ok to read extension length ? */ ND_TCHECK2(tptr[0], 2); jnx_ext_len = EXTRACT_16BITS(tptr); jnx_header_len += 2; tptr +=2; /* nail up the total length - * just in case something goes wrong * with TLV parsing */ jnx_header_len += jnx_ext_len; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len)); ND_TCHECK2(tptr[0], jnx_ext_len); while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) { tlv_type = *(tptr++); tlv_len = *(tptr++); tlv_value = 0; /* sanity checks */ if (tlv_type == 0 || tlv_len == 0) break; if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len) goto trunc; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ", tok2str(jnx_ext_tlv_values,"Unknown",tlv_type), tlv_type, tlv_len)); tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len); switch (tlv_type) { case JUNIPER_EXT_TLV_IFD_NAME: /* FIXME */ break; case JUNIPER_EXT_TLV_IFD_MEDIATYPE: case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%s (%u)", tok2str(juniper_ifmt_values, "Unknown", tlv_value), tlv_value)); } break; case JUNIPER_EXT_TLV_IFL_ENCAPS: case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%s (%u)", tok2str(juniper_ifle_values, "Unknown", tlv_value), tlv_value)); } break; case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */ case JUNIPER_EXT_TLV_IFL_UNIT: case JUNIPER_EXT_TLV_IFD_IDX: default: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%u", tlv_value)); } break; } tptr+=tlv_len; jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD; } if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t-----original packet-----\n\t")); } if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) { if (ndo->ndo_eflag) ND_PRINT((ndo, "no-L2-hdr, ")); /* there is no link-layer present - * perform the v4/v6 heuristics * to figure out what it is */ ND_TCHECK2(p[jnx_header_len + 4], 1); if (ip_heuristic_guess(ndo, p + jnx_header_len + 4, l2info->length - (jnx_header_len + 4)) == 0) ND_PRINT((ndo, "no IP-hdr found!")); l2info->header_len=jnx_header_len+4; return 0; /* stop parsing the output further */ } l2info->header_len = jnx_header_len; p+=l2info->header_len; l2info->length -= l2info->header_len; l2info->caplen -= l2info->header_len; /* search through the cookie table and copy values matching for our PIC type */ ND_TCHECK(p[0]); while (lp->s != NULL) { if (lp->pictype == l2info->pictype) { l2info->cookie_len += lp->cookie_len; switch (p[0]) { case LS_COOKIE_ID: l2info->cookie_type = LS_COOKIE_ID; l2info->cookie_len += 2; break; case AS_COOKIE_ID: l2info->cookie_type = AS_COOKIE_ID; l2info->cookie_len = 8; break; default: l2info->bundle = l2info->cookie[0]; break; } #ifdef DLT_JUNIPER_MFR /* MFR child links don't carry cookies */ if (l2info->pictype == DLT_JUNIPER_MFR && (p[0] & MFR_BE_MASK) == MFR_BE_MASK) { l2info->cookie_len = 0; } #endif l2info->header_len += l2info->cookie_len; l2info->length -= l2info->cookie_len; l2info->caplen -= l2info->cookie_len; if (ndo->ndo_eflag) ND_PRINT((ndo, "%s-PIC, cookie-len %u", lp->s, l2info->cookie_len)); if (l2info->cookie_len > 0) { ND_TCHECK2(p[0], l2info->cookie_len); if (ndo->ndo_eflag) ND_PRINT((ndo, ", cookie 0x")); for (idx = 0; idx < l2info->cookie_len; idx++) { l2info->cookie[idx] = p[idx]; /* copy cookie data */ if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx])); } } if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/ l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len); break; } ++lp; } p+=l2info->cookie_len; /* DLT_ specific parsing */ switch(l2info->pictype) { #ifdef DLT_JUNIPER_MLPPP case DLT_JUNIPER_MLPPP: switch (l2info->cookie_type) { case LS_COOKIE_ID: l2info->bundle = l2info->cookie[1]; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; break; } break; #endif #ifdef DLT_JUNIPER_MLFR case DLT_JUNIPER_MLFR: switch (l2info->cookie_type) { case LS_COOKIE_ID: ND_TCHECK2(p[0], 2); l2info->bundle = l2info->cookie[1]; l2info->proto = EXTRACT_16BITS(p); l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; } break; #endif #ifdef DLT_JUNIPER_MFR case DLT_JUNIPER_MFR: switch (l2info->cookie_type) { case LS_COOKIE_ID: ND_TCHECK2(p[0], 2); l2info->bundle = l2info->cookie[1]; l2info->proto = EXTRACT_16BITS(p); l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; break; } break; #endif #ifdef DLT_JUNIPER_ATM2 case DLT_JUNIPER_ATM2: ND_TCHECK2(p[0], 4); /* ATM cell relay control word present ? */ if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) { control_word = EXTRACT_32BITS(p); /* some control word heuristics */ switch(control_word) { case 0: /* zero control word */ case 0x08000000: /* < JUNOS 7.4 control-word */ case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/ l2info->header_len += 4; break; default: break; } if (ndo->ndo_eflag) ND_PRINT((ndo, "control-word 0x%08x ", control_word)); } break; #endif #ifdef DLT_JUNIPER_GGSN case DLT_JUNIPER_GGSN: break; #endif #ifdef DLT_JUNIPER_ATM1 case DLT_JUNIPER_ATM1: break; #endif #ifdef DLT_JUNIPER_PPP case DLT_JUNIPER_PPP: break; #endif #ifdef DLT_JUNIPER_CHDLC case DLT_JUNIPER_CHDLC: break; #endif #ifdef DLT_JUNIPER_ETHER case DLT_JUNIPER_ETHER: break; #endif #ifdef DLT_JUNIPER_FRELAY case DLT_JUNIPER_FRELAY: break; #endif default: ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype)); break; } if (ndo->ndo_eflag > 1) ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto)); return 1; /* everything went ok so far. continue parsing */ trunc: ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len)); return 0; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2680_0
crossvul-cpp_data_bad_2644_7
/* NetBSD: print-juniper.c,v 1.2 2007/07/24 11:53:45 drochner Exp */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: DLT_JUNIPER_* printers */ #ifndef lint #else __RCSID("NetBSD: print-juniper.c,v 1.3 2007/07/25 06:31:32 dogcow Exp "); #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ppp.h" #include "llc.h" #include "nlpid.h" #include "ethertype.h" #include "atm.h" #define JUNIPER_BPF_OUT 0 /* Outgoing packet */ #define JUNIPER_BPF_IN 1 /* Incoming packet */ #define JUNIPER_BPF_PKT_IN 0x1 /* Incoming packet */ #define JUNIPER_BPF_NO_L2 0x2 /* L2 header stripped */ #define JUNIPER_BPF_IIF 0x4 /* IIF is valid */ #define JUNIPER_BPF_FILTER 0x40 /* BPF filtering is supported */ #define JUNIPER_BPF_EXT 0x80 /* extensions present */ #define JUNIPER_MGC_NUMBER 0x4d4743 /* = "MGC" */ #define JUNIPER_LSQ_COOKIE_RE (1 << 3) #define JUNIPER_LSQ_COOKIE_DIR (1 << 2) #define JUNIPER_LSQ_L3_PROTO_SHIFT 4 #define JUNIPER_LSQ_L3_PROTO_MASK (0x17 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_IPV4 (0 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_IPV6 (1 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_MPLS (2 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define JUNIPER_LSQ_L3_PROTO_ISO (3 << JUNIPER_LSQ_L3_PROTO_SHIFT) #define AS_PIC_COOKIE_LEN 8 #define JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE 1 #define JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE 2 #define JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE 3 #define JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE 4 #define JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE 5 static const struct tok juniper_ipsec_type_values[] = { { JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE, "ESP ENCR-AUTH" }, { JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE, "ESP ENCR-AH AUTH" }, { JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE, "ESP AUTH" }, { JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE, "AH AUTH" }, { JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE, "ESP ENCR" }, { 0, NULL} }; static const struct tok juniper_direction_values[] = { { JUNIPER_BPF_IN, "In"}, { JUNIPER_BPF_OUT, "Out"}, { 0, NULL} }; /* codepoints for encoding extensions to a .pcap file */ enum { JUNIPER_EXT_TLV_IFD_IDX = 1, JUNIPER_EXT_TLV_IFD_NAME = 2, JUNIPER_EXT_TLV_IFD_MEDIATYPE = 3, JUNIPER_EXT_TLV_IFL_IDX = 4, JUNIPER_EXT_TLV_IFL_UNIT = 5, JUNIPER_EXT_TLV_IFL_ENCAPS = 6, JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE = 7, JUNIPER_EXT_TLV_TTP_IFL_ENCAPS = 8 }; /* 1 byte type and 1-byte length */ #define JUNIPER_EXT_TLV_OVERHEAD 2U static const struct tok jnx_ext_tlv_values[] = { { JUNIPER_EXT_TLV_IFD_IDX, "Device Interface Index" }, { JUNIPER_EXT_TLV_IFD_NAME,"Device Interface Name" }, { JUNIPER_EXT_TLV_IFD_MEDIATYPE, "Device Media Type" }, { JUNIPER_EXT_TLV_IFL_IDX, "Logical Interface Index" }, { JUNIPER_EXT_TLV_IFL_UNIT,"Logical Unit Number" }, { JUNIPER_EXT_TLV_IFL_ENCAPS, "Logical Interface Encapsulation" }, { JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE, "TTP derived Device Media Type" }, { JUNIPER_EXT_TLV_TTP_IFL_ENCAPS, "TTP derived Logical Interface Encapsulation" }, { 0, NULL } }; static const struct tok jnx_flag_values[] = { { JUNIPER_BPF_EXT, "Ext" }, { JUNIPER_BPF_FILTER, "Filter" }, { JUNIPER_BPF_IIF, "IIF" }, { JUNIPER_BPF_NO_L2, "no-L2" }, { JUNIPER_BPF_PKT_IN, "In" }, { 0, NULL } }; #define JUNIPER_IFML_ETHER 1 #define JUNIPER_IFML_FDDI 2 #define JUNIPER_IFML_TOKENRING 3 #define JUNIPER_IFML_PPP 4 #define JUNIPER_IFML_FRAMERELAY 5 #define JUNIPER_IFML_CISCOHDLC 6 #define JUNIPER_IFML_SMDSDXI 7 #define JUNIPER_IFML_ATMPVC 8 #define JUNIPER_IFML_PPP_CCC 9 #define JUNIPER_IFML_FRAMERELAY_CCC 10 #define JUNIPER_IFML_IPIP 11 #define JUNIPER_IFML_GRE 12 #define JUNIPER_IFML_PIM 13 #define JUNIPER_IFML_PIMD 14 #define JUNIPER_IFML_CISCOHDLC_CCC 15 #define JUNIPER_IFML_VLAN_CCC 16 #define JUNIPER_IFML_MLPPP 17 #define JUNIPER_IFML_MLFR 18 #define JUNIPER_IFML_ML 19 #define JUNIPER_IFML_LSI 20 #define JUNIPER_IFML_DFE 21 #define JUNIPER_IFML_ATM_CELLRELAY_CCC 22 #define JUNIPER_IFML_CRYPTO 23 #define JUNIPER_IFML_GGSN 24 #define JUNIPER_IFML_LSI_PPP 25 #define JUNIPER_IFML_LSI_CISCOHDLC 26 #define JUNIPER_IFML_PPP_TCC 27 #define JUNIPER_IFML_FRAMERELAY_TCC 28 #define JUNIPER_IFML_CISCOHDLC_TCC 29 #define JUNIPER_IFML_ETHERNET_CCC 30 #define JUNIPER_IFML_VT 31 #define JUNIPER_IFML_EXTENDED_VLAN_CCC 32 #define JUNIPER_IFML_ETHER_OVER_ATM 33 #define JUNIPER_IFML_MONITOR 34 #define JUNIPER_IFML_ETHERNET_TCC 35 #define JUNIPER_IFML_VLAN_TCC 36 #define JUNIPER_IFML_EXTENDED_VLAN_TCC 37 #define JUNIPER_IFML_CONTROLLER 38 #define JUNIPER_IFML_MFR 39 #define JUNIPER_IFML_LS 40 #define JUNIPER_IFML_ETHERNET_VPLS 41 #define JUNIPER_IFML_ETHERNET_VLAN_VPLS 42 #define JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS 43 #define JUNIPER_IFML_LT 44 #define JUNIPER_IFML_SERVICES 45 #define JUNIPER_IFML_ETHER_VPLS_OVER_ATM 46 #define JUNIPER_IFML_FR_PORT_CCC 47 #define JUNIPER_IFML_FRAMERELAY_EXT_CCC 48 #define JUNIPER_IFML_FRAMERELAY_EXT_TCC 49 #define JUNIPER_IFML_FRAMERELAY_FLEX 50 #define JUNIPER_IFML_GGSNI 51 #define JUNIPER_IFML_ETHERNET_FLEX 52 #define JUNIPER_IFML_COLLECTOR 53 #define JUNIPER_IFML_AGGREGATOR 54 #define JUNIPER_IFML_LAPD 55 #define JUNIPER_IFML_PPPOE 56 #define JUNIPER_IFML_PPP_SUBORDINATE 57 #define JUNIPER_IFML_CISCOHDLC_SUBORDINATE 58 #define JUNIPER_IFML_DFC 59 #define JUNIPER_IFML_PICPEER 60 static const struct tok juniper_ifmt_values[] = { { JUNIPER_IFML_ETHER, "Ethernet" }, { JUNIPER_IFML_FDDI, "FDDI" }, { JUNIPER_IFML_TOKENRING, "Token-Ring" }, { JUNIPER_IFML_PPP, "PPP" }, { JUNIPER_IFML_PPP_SUBORDINATE, "PPP-Subordinate" }, { JUNIPER_IFML_FRAMERELAY, "Frame-Relay" }, { JUNIPER_IFML_CISCOHDLC, "Cisco-HDLC" }, { JUNIPER_IFML_SMDSDXI, "SMDS-DXI" }, { JUNIPER_IFML_ATMPVC, "ATM-PVC" }, { JUNIPER_IFML_PPP_CCC, "PPP-CCC" }, { JUNIPER_IFML_FRAMERELAY_CCC, "Frame-Relay-CCC" }, { JUNIPER_IFML_FRAMERELAY_EXT_CCC, "Extended FR-CCC" }, { JUNIPER_IFML_IPIP, "IP-over-IP" }, { JUNIPER_IFML_GRE, "GRE" }, { JUNIPER_IFML_PIM, "PIM-Encapsulator" }, { JUNIPER_IFML_PIMD, "PIM-Decapsulator" }, { JUNIPER_IFML_CISCOHDLC_CCC, "Cisco-HDLC-CCC" }, { JUNIPER_IFML_VLAN_CCC, "VLAN-CCC" }, { JUNIPER_IFML_EXTENDED_VLAN_CCC, "Extended-VLAN-CCC" }, { JUNIPER_IFML_MLPPP, "Multilink-PPP" }, { JUNIPER_IFML_MLFR, "Multilink-FR" }, { JUNIPER_IFML_MFR, "Multilink-FR-UNI-NNI" }, { JUNIPER_IFML_ML, "Multilink" }, { JUNIPER_IFML_LS, "LinkService" }, { JUNIPER_IFML_LSI, "LSI" }, { JUNIPER_IFML_ATM_CELLRELAY_CCC, "ATM-CCC-Cell-Relay" }, { JUNIPER_IFML_CRYPTO, "IPSEC-over-IP" }, { JUNIPER_IFML_GGSN, "GGSN" }, { JUNIPER_IFML_PPP_TCC, "PPP-TCC" }, { JUNIPER_IFML_FRAMERELAY_TCC, "Frame-Relay-TCC" }, { JUNIPER_IFML_FRAMERELAY_EXT_TCC, "Extended FR-TCC" }, { JUNIPER_IFML_CISCOHDLC_TCC, "Cisco-HDLC-TCC" }, { JUNIPER_IFML_ETHERNET_CCC, "Ethernet-CCC" }, { JUNIPER_IFML_VT, "VPN-Loopback-tunnel" }, { JUNIPER_IFML_ETHER_OVER_ATM, "Ethernet-over-ATM" }, { JUNIPER_IFML_ETHER_VPLS_OVER_ATM, "Ethernet-VPLS-over-ATM" }, { JUNIPER_IFML_MONITOR, "Monitor" }, { JUNIPER_IFML_ETHERNET_TCC, "Ethernet-TCC" }, { JUNIPER_IFML_VLAN_TCC, "VLAN-TCC" }, { JUNIPER_IFML_EXTENDED_VLAN_TCC, "Extended-VLAN-TCC" }, { JUNIPER_IFML_CONTROLLER, "Controller" }, { JUNIPER_IFML_ETHERNET_VPLS, "VPLS" }, { JUNIPER_IFML_ETHERNET_VLAN_VPLS, "VLAN-VPLS" }, { JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS, "Extended-VLAN-VPLS" }, { JUNIPER_IFML_LT, "Logical-tunnel" }, { JUNIPER_IFML_SERVICES, "General-Services" }, { JUNIPER_IFML_PPPOE, "PPPoE" }, { JUNIPER_IFML_ETHERNET_FLEX, "Flexible-Ethernet-Services" }, { JUNIPER_IFML_FRAMERELAY_FLEX, "Flexible-FrameRelay" }, { JUNIPER_IFML_COLLECTOR, "Flow-collection" }, { JUNIPER_IFML_PICPEER, "PIC Peer" }, { JUNIPER_IFML_DFC, "Dynamic-Flow-Capture" }, {0, NULL} }; #define JUNIPER_IFLE_ATM_SNAP 2 #define JUNIPER_IFLE_ATM_NLPID 3 #define JUNIPER_IFLE_ATM_VCMUX 4 #define JUNIPER_IFLE_ATM_LLC 5 #define JUNIPER_IFLE_ATM_PPP_VCMUX 6 #define JUNIPER_IFLE_ATM_PPP_LLC 7 #define JUNIPER_IFLE_ATM_PPP_FUNI 8 #define JUNIPER_IFLE_ATM_CCC 9 #define JUNIPER_IFLE_FR_NLPID 10 #define JUNIPER_IFLE_FR_SNAP 11 #define JUNIPER_IFLE_FR_PPP 12 #define JUNIPER_IFLE_FR_CCC 13 #define JUNIPER_IFLE_ENET2 14 #define JUNIPER_IFLE_IEEE8023_SNAP 15 #define JUNIPER_IFLE_IEEE8023_LLC 16 #define JUNIPER_IFLE_PPP 17 #define JUNIPER_IFLE_CISCOHDLC 18 #define JUNIPER_IFLE_PPP_CCC 19 #define JUNIPER_IFLE_IPIP_NULL 20 #define JUNIPER_IFLE_PIM_NULL 21 #define JUNIPER_IFLE_GRE_NULL 22 #define JUNIPER_IFLE_GRE_PPP 23 #define JUNIPER_IFLE_PIMD_DECAPS 24 #define JUNIPER_IFLE_CISCOHDLC_CCC 25 #define JUNIPER_IFLE_ATM_CISCO_NLPID 26 #define JUNIPER_IFLE_VLAN_CCC 27 #define JUNIPER_IFLE_MLPPP 28 #define JUNIPER_IFLE_MLFR 29 #define JUNIPER_IFLE_LSI_NULL 30 #define JUNIPER_IFLE_AGGREGATE_UNUSED 31 #define JUNIPER_IFLE_ATM_CELLRELAY_CCC 32 #define JUNIPER_IFLE_CRYPTO 33 #define JUNIPER_IFLE_GGSN 34 #define JUNIPER_IFLE_ATM_TCC 35 #define JUNIPER_IFLE_FR_TCC 36 #define JUNIPER_IFLE_PPP_TCC 37 #define JUNIPER_IFLE_CISCOHDLC_TCC 38 #define JUNIPER_IFLE_ETHERNET_CCC 39 #define JUNIPER_IFLE_VT 40 #define JUNIPER_IFLE_ATM_EOA_LLC 41 #define JUNIPER_IFLE_EXTENDED_VLAN_CCC 42 #define JUNIPER_IFLE_ATM_SNAP_TCC 43 #define JUNIPER_IFLE_MONITOR 44 #define JUNIPER_IFLE_ETHERNET_TCC 45 #define JUNIPER_IFLE_VLAN_TCC 46 #define JUNIPER_IFLE_EXTENDED_VLAN_TCC 47 #define JUNIPER_IFLE_MFR 48 #define JUNIPER_IFLE_ETHERNET_VPLS 49 #define JUNIPER_IFLE_ETHERNET_VLAN_VPLS 50 #define JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS 51 #define JUNIPER_IFLE_SERVICES 52 #define JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC 53 #define JUNIPER_IFLE_FR_PORT_CCC 54 #define JUNIPER_IFLE_ATM_MLPPP_LLC 55 #define JUNIPER_IFLE_ATM_EOA_CCC 56 #define JUNIPER_IFLE_LT_VLAN 57 #define JUNIPER_IFLE_COLLECTOR 58 #define JUNIPER_IFLE_AGGREGATOR 59 #define JUNIPER_IFLE_LAPD 60 #define JUNIPER_IFLE_ATM_PPPOE_LLC 61 #define JUNIPER_IFLE_ETHERNET_PPPOE 62 #define JUNIPER_IFLE_PPPOE 63 #define JUNIPER_IFLE_PPP_SUBORDINATE 64 #define JUNIPER_IFLE_CISCOHDLC_SUBORDINATE 65 #define JUNIPER_IFLE_DFC 66 #define JUNIPER_IFLE_PICPEER 67 static const struct tok juniper_ifle_values[] = { { JUNIPER_IFLE_AGGREGATOR, "Aggregator" }, { JUNIPER_IFLE_ATM_CCC, "CCC over ATM" }, { JUNIPER_IFLE_ATM_CELLRELAY_CCC, "ATM CCC Cell Relay" }, { JUNIPER_IFLE_ATM_CISCO_NLPID, "CISCO compatible NLPID" }, { JUNIPER_IFLE_ATM_EOA_CCC, "Ethernet over ATM CCC" }, { JUNIPER_IFLE_ATM_EOA_LLC, "Ethernet over ATM LLC" }, { JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC, "Ethernet VPLS over ATM LLC" }, { JUNIPER_IFLE_ATM_LLC, "ATM LLC" }, { JUNIPER_IFLE_ATM_MLPPP_LLC, "MLPPP over ATM LLC" }, { JUNIPER_IFLE_ATM_NLPID, "ATM NLPID" }, { JUNIPER_IFLE_ATM_PPPOE_LLC, "PPPoE over ATM LLC" }, { JUNIPER_IFLE_ATM_PPP_FUNI, "PPP over FUNI" }, { JUNIPER_IFLE_ATM_PPP_LLC, "PPP over ATM LLC" }, { JUNIPER_IFLE_ATM_PPP_VCMUX, "PPP over ATM VCMUX" }, { JUNIPER_IFLE_ATM_SNAP, "ATM SNAP" }, { JUNIPER_IFLE_ATM_SNAP_TCC, "ATM SNAP TCC" }, { JUNIPER_IFLE_ATM_TCC, "ATM VCMUX TCC" }, { JUNIPER_IFLE_ATM_VCMUX, "ATM VCMUX" }, { JUNIPER_IFLE_CISCOHDLC, "C-HDLC" }, { JUNIPER_IFLE_CISCOHDLC_CCC, "C-HDLC CCC" }, { JUNIPER_IFLE_CISCOHDLC_SUBORDINATE, "C-HDLC via dialer" }, { JUNIPER_IFLE_CISCOHDLC_TCC, "C-HDLC TCC" }, { JUNIPER_IFLE_COLLECTOR, "Collector" }, { JUNIPER_IFLE_CRYPTO, "Crypto" }, { JUNIPER_IFLE_ENET2, "Ethernet" }, { JUNIPER_IFLE_ETHERNET_CCC, "Ethernet CCC" }, { JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS, "Extended VLAN VPLS" }, { JUNIPER_IFLE_ETHERNET_PPPOE, "PPPoE over Ethernet" }, { JUNIPER_IFLE_ETHERNET_TCC, "Ethernet TCC" }, { JUNIPER_IFLE_ETHERNET_VLAN_VPLS, "VLAN VPLS" }, { JUNIPER_IFLE_ETHERNET_VPLS, "VPLS" }, { JUNIPER_IFLE_EXTENDED_VLAN_CCC, "Extended VLAN CCC" }, { JUNIPER_IFLE_EXTENDED_VLAN_TCC, "Extended VLAN TCC" }, { JUNIPER_IFLE_FR_CCC, "FR CCC" }, { JUNIPER_IFLE_FR_NLPID, "FR NLPID" }, { JUNIPER_IFLE_FR_PORT_CCC, "FR CCC" }, { JUNIPER_IFLE_FR_PPP, "FR PPP" }, { JUNIPER_IFLE_FR_SNAP, "FR SNAP" }, { JUNIPER_IFLE_FR_TCC, "FR TCC" }, { JUNIPER_IFLE_GGSN, "GGSN" }, { JUNIPER_IFLE_GRE_NULL, "GRE NULL" }, { JUNIPER_IFLE_GRE_PPP, "PPP over GRE" }, { JUNIPER_IFLE_IPIP_NULL, "IPIP" }, { JUNIPER_IFLE_LAPD, "LAPD" }, { JUNIPER_IFLE_LSI_NULL, "LSI Null" }, { JUNIPER_IFLE_LT_VLAN, "LT VLAN" }, { JUNIPER_IFLE_MFR, "MFR" }, { JUNIPER_IFLE_MLFR, "MLFR" }, { JUNIPER_IFLE_MLPPP, "MLPPP" }, { JUNIPER_IFLE_MONITOR, "Monitor" }, { JUNIPER_IFLE_PIMD_DECAPS, "PIMd" }, { JUNIPER_IFLE_PIM_NULL, "PIM Null" }, { JUNIPER_IFLE_PPP, "PPP" }, { JUNIPER_IFLE_PPPOE, "PPPoE" }, { JUNIPER_IFLE_PPP_CCC, "PPP CCC" }, { JUNIPER_IFLE_PPP_SUBORDINATE, "" }, { JUNIPER_IFLE_PPP_TCC, "PPP TCC" }, { JUNIPER_IFLE_SERVICES, "General Services" }, { JUNIPER_IFLE_VLAN_CCC, "VLAN CCC" }, { JUNIPER_IFLE_VLAN_TCC, "VLAN TCC" }, { JUNIPER_IFLE_VT, "VT" }, {0, NULL} }; struct juniper_cookie_table_t { uint32_t pictype; /* pic type */ uint8_t cookie_len; /* cookie len */ const char *s; /* pic name */ }; static const struct juniper_cookie_table_t juniper_cookie_table[] = { #ifdef DLT_JUNIPER_ATM1 { DLT_JUNIPER_ATM1, 4, "ATM1"}, #endif #ifdef DLT_JUNIPER_ATM2 { DLT_JUNIPER_ATM2, 8, "ATM2"}, #endif #ifdef DLT_JUNIPER_MLPPP { DLT_JUNIPER_MLPPP, 2, "MLPPP"}, #endif #ifdef DLT_JUNIPER_MLFR { DLT_JUNIPER_MLFR, 2, "MLFR"}, #endif #ifdef DLT_JUNIPER_MFR { DLT_JUNIPER_MFR, 4, "MFR"}, #endif #ifdef DLT_JUNIPER_PPPOE { DLT_JUNIPER_PPPOE, 0, "PPPoE"}, #endif #ifdef DLT_JUNIPER_PPPOE_ATM { DLT_JUNIPER_PPPOE_ATM, 0, "PPPoE ATM"}, #endif #ifdef DLT_JUNIPER_GGSN { DLT_JUNIPER_GGSN, 8, "GGSN"}, #endif #ifdef DLT_JUNIPER_MONITOR { DLT_JUNIPER_MONITOR, 8, "MONITOR"}, #endif #ifdef DLT_JUNIPER_SERVICES { DLT_JUNIPER_SERVICES, 8, "AS"}, #endif #ifdef DLT_JUNIPER_ES { DLT_JUNIPER_ES, 0, "ES"}, #endif { 0, 0, NULL } }; struct juniper_l2info_t { uint32_t length; uint32_t caplen; uint32_t pictype; uint8_t direction; uint8_t header_len; uint8_t cookie_len; uint8_t cookie_type; uint8_t cookie[8]; uint8_t bundle; uint16_t proto; uint8_t flags; }; #define LS_COOKIE_ID 0x54 #define AS_COOKIE_ID 0x47 #define LS_MLFR_COOKIE_LEN 4 #define ML_MLFR_COOKIE_LEN 2 #define LS_MFR_COOKIE_LEN 6 #define ATM1_COOKIE_LEN 4 #define ATM2_COOKIE_LEN 8 #define ATM2_PKT_TYPE_MASK 0x70 #define ATM2_GAP_COUNT_MASK 0x3F #define JUNIPER_PROTO_NULL 1 #define JUNIPER_PROTO_IPV4 2 #define JUNIPER_PROTO_IPV6 6 #define MFR_BE_MASK 0xc0 static const struct tok juniper_protocol_values[] = { { JUNIPER_PROTO_NULL, "Null" }, { JUNIPER_PROTO_IPV4, "IPv4" }, { JUNIPER_PROTO_IPV6, "IPv6" }, { 0, NULL} }; static int ip_heuristic_guess(netdissect_options *, register const u_char *, u_int); static int juniper_ppp_heuristic_guess(netdissect_options *, register const u_char *, u_int); static int juniper_parse_header(netdissect_options *, const u_char *, const struct pcap_pkthdr *, struct juniper_l2info_t *); #ifdef DLT_JUNIPER_GGSN u_int juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; } #endif #ifdef DLT_JUNIPER_ES u_int juniper_es_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ipsec_header { uint8_t sa_index[2]; uint8_t ttl; uint8_t type; uint8_t spi[4]; uint8_t src_ip[4]; uint8_t dst_ip[4]; }; u_int rewrite_len,es_type_bundle; const struct juniper_ipsec_header *ih; l2info.pictype = DLT_JUNIPER_ES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ih = (const struct juniper_ipsec_header *)p; switch (ih->type) { case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE: rewrite_len = 0; es_type_bundle = 1; break; case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE: case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE: rewrite_len = 16; es_type_bundle = 0; break; default: ND_PRINT((ndo, "ES Invalid type %u, length %u", ih->type, l2info.length)); return l2info.header_len; } l2info.length-=rewrite_len; p+=rewrite_len; if (ndo->ndo_eflag) { if (!es_type_bundle) { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, EXTRACT_32BITS(&ih->spi), ipaddr_string(ndo, &ih->src_ip), ipaddr_string(ndo, &ih->dst_ip), l2info.length)); } else { ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n", EXTRACT_16BITS(&ih->sa_index), ih->ttl, tok2str(juniper_ipsec_type_values,"Unknown",ih->type), ih->type, l2info.length)); } } ip_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MONITOR u_int juniper_monitor_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_monitor_header { uint8_t pkt_type; uint8_t padding; uint8_t iif[2]; uint8_t service_id[4]; }; const struct juniper_monitor_header *mh; l2info.pictype = DLT_JUNIPER_MONITOR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; mh = (const struct juniper_monitor_header *)p; if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ", EXTRACT_32BITS(&mh->service_id), EXTRACT_16BITS(&mh->iif), mh->pkt_type)); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_SERVICES u_int juniper_services_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_services_header { uint8_t svc_id; uint8_t flags_len; uint8_t svc_set_id[2]; uint8_t dir_iif[4]; }; const struct juniper_services_header *sh; l2info.pictype = DLT_JUNIPER_SERVICES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; sh = (const struct juniper_services_header *)p; if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ", sh->svc_id, sh->flags_len, EXTRACT_16BITS(&sh->svc_set_id), EXTRACT_24BITS(&sh->dir_iif[1]))); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPPOE u_int juniper_pppoe_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_PPPOE; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw ethernet frames */ ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_ETHER u_int juniper_ether_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ETHER; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw Ethernet frames */ ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPP u_int juniper_ppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_PPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw ppp frames */ ppp_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_FRELAY u_int juniper_frelay_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_FRELAY; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw frame-relay frames */ fr_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_CHDLC u_int juniper_chdlc_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_CHDLC; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* this DLT contains nothing but raw c-hdlc frames */ chdlc_print(ndo, p, l2info.length); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_PPPOE_ATM u_int juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MLPPP u_int juniper_mlppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLPPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link * best indicator if the cookie looks like a proto */ if (ndo->ndo_eflag && EXTRACT_16BITS(&l2info.cookie) != PPP_OSI && EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL)) ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle)); p+=l2info.header_len; /* first try the LSQ protos */ switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: /* IP traffic going to the RE would not have a cookie * -> this must be incoming IS-IS over PPP */ if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR)) ppp_print(ndo, p, l2info.length); else ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length, l2info.caplen); return l2info.header_len; default: break; } /* zero length cookie ? */ switch (EXTRACT_16BITS(&l2info.cookie)) { case PPP_OSI: ppp_print(ndo, p - 2, l2info.length + 2); break; case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */ default: ppp_print(ndo, p, l2info.length); break; } return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MFR u_int juniper_mfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; memset(&l2info, 0, sizeof(l2info)); l2info.pictype = DLT_JUNIPER_MFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* child-link ? */ if (l2info.cookie_len == 0) { mfr_print(ndo, p, l2info.length); return l2info.header_len; } /* first try the LSQ protos */ if (l2info.cookie_len == AS_PIC_COOKIE_LEN) { switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length, l2info.caplen); return l2info.header_len; default: break; } return l2info.header_len; } /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLCSAP_ISONS<<8 | LLCSAP_ISONS): isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } #endif #ifdef DLT_JUNIPER_MLFR u_int juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length, l2info.caplen); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } #endif /* * ATM1 PIC cookie format * * +-----+-------------------------+-------------------------------+ * |fmtid| vc index | channel ID | * +-----+-------------------------+-------------------------------+ */ #ifdef DLT_JUNIPER_ATM1 u_int juniper_atm1_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM1; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[0] == 0x80) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } #endif /* * ATM2 PIC cookie format * * +-------------------------------+---------+---+-----+-----------+ * | channel ID | reserv |AAL| CCRQ| gap cnt | * +-------------------------------+---------+---+-----+-----------+ */ #ifdef DLT_JUNIPER_ATM2 u_int juniper_atm2_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM2; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */ (EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) { ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */ return l2info.header_len; if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } #endif /* try to guess, based on all PPP protos that are supported in * a juniper router if the payload data is encapsulated using PPP */ static int juniper_ppp_heuristic_guess(netdissect_options *ndo, register const u_char *p, u_int length) { switch(EXTRACT_16BITS(p)) { case PPP_IP : case PPP_OSI : case PPP_MPLS_UCAST : case PPP_MPLS_MCAST : case PPP_IPCP : case PPP_OSICP : case PPP_MPLSCP : case PPP_LCP : case PPP_PAP : case PPP_CHAP : case PPP_ML : case PPP_IPV6 : case PPP_IPV6CP : ppp_print(ndo, p, length); break; default: return 0; /* did not find a ppp header */ break; } return 1; /* we printed a ppp packet */ } static int ip_heuristic_guess(netdissect_options *ndo, register const u_char *p, u_int length) { switch(p[0]) { case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: ip_print(ndo, p, length); break; case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: ip6_print(ndo, p, length); break; default: return 0; /* did not find a ip header */ break; } return 1; /* we printed an v4/v6 packet */ } static int juniper_read_tlv_value(const u_char *p, u_int tlv_type, u_int tlv_len) { int tlv_value; /* TLVs < 128 are little endian encoded */ if (tlv_type < 128) { switch (tlv_len) { case 1: tlv_value = *p; break; case 2: tlv_value = EXTRACT_LE_16BITS(p); break; case 3: tlv_value = EXTRACT_LE_24BITS(p); break; case 4: tlv_value = EXTRACT_LE_32BITS(p); break; default: tlv_value = -1; break; } } else { /* TLVs >= 128 are big endian encoded */ switch (tlv_len) { case 1: tlv_value = *p; break; case 2: tlv_value = EXTRACT_16BITS(p); break; case 3: tlv_value = EXTRACT_24BITS(p); break; case 4: tlv_value = EXTRACT_32BITS(p); break; default: tlv_value = -1; break; } } return tlv_value; } static int juniper_parse_header(netdissect_options *ndo, const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info) { const struct juniper_cookie_table_t *lp = juniper_cookie_table; u_int idx, jnx_ext_len, jnx_header_len = 0; uint8_t tlv_type,tlv_len; uint32_t control_word; int tlv_value; const u_char *tptr; l2info->header_len = 0; l2info->cookie_len = 0; l2info->proto = 0; l2info->length = h->len; l2info->caplen = h->caplen; ND_TCHECK2(p[0], 4); l2info->flags = p[3]; l2info->direction = p[3]&JUNIPER_BPF_PKT_IN; if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */ ND_PRINT((ndo, "no magic-number found!")); return 0; } if (ndo->ndo_eflag) /* print direction */ ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction))); /* magic number + flags */ jnx_header_len = 4; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]", bittok2str(jnx_flag_values, "none", l2info->flags))); /* extensions present ? - calculate how much bytes to skip */ if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) { tptr = p+jnx_header_len; /* ok to read extension length ? */ ND_TCHECK2(tptr[0], 2); jnx_ext_len = EXTRACT_16BITS(tptr); jnx_header_len += 2; tptr +=2; /* nail up the total length - * just in case something goes wrong * with TLV parsing */ jnx_header_len += jnx_ext_len; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len)); ND_TCHECK2(tptr[0], jnx_ext_len); while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) { tlv_type = *(tptr++); tlv_len = *(tptr++); tlv_value = 0; /* sanity checks */ if (tlv_type == 0 || tlv_len == 0) break; if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len) goto trunc; if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ", tok2str(jnx_ext_tlv_values,"Unknown",tlv_type), tlv_type, tlv_len)); tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len); switch (tlv_type) { case JUNIPER_EXT_TLV_IFD_NAME: /* FIXME */ break; case JUNIPER_EXT_TLV_IFD_MEDIATYPE: case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%s (%u)", tok2str(juniper_ifmt_values, "Unknown", tlv_value), tlv_value)); } break; case JUNIPER_EXT_TLV_IFL_ENCAPS: case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%s (%u)", tok2str(juniper_ifle_values, "Unknown", tlv_value), tlv_value)); } break; case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */ case JUNIPER_EXT_TLV_IFL_UNIT: case JUNIPER_EXT_TLV_IFD_IDX: default: if (tlv_value != -1) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "%u", tlv_value)); } break; } tptr+=tlv_len; jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD; } if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t-----original packet-----\n\t")); } if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) { if (ndo->ndo_eflag) ND_PRINT((ndo, "no-L2-hdr, ")); /* there is no link-layer present - * perform the v4/v6 heuristics * to figure out what it is */ ND_TCHECK2(p[jnx_header_len + 4], 1); if (ip_heuristic_guess(ndo, p + jnx_header_len + 4, l2info->length - (jnx_header_len + 4)) == 0) ND_PRINT((ndo, "no IP-hdr found!")); l2info->header_len=jnx_header_len+4; return 0; /* stop parsing the output further */ } l2info->header_len = jnx_header_len; p+=l2info->header_len; l2info->length -= l2info->header_len; l2info->caplen -= l2info->header_len; /* search through the cookie table and copy values matching for our PIC type */ while (lp->s != NULL) { if (lp->pictype == l2info->pictype) { l2info->cookie_len += lp->cookie_len; switch (p[0]) { case LS_COOKIE_ID: l2info->cookie_type = LS_COOKIE_ID; l2info->cookie_len += 2; break; case AS_COOKIE_ID: l2info->cookie_type = AS_COOKIE_ID; l2info->cookie_len = 8; break; default: l2info->bundle = l2info->cookie[0]; break; } #ifdef DLT_JUNIPER_MFR /* MFR child links don't carry cookies */ if (l2info->pictype == DLT_JUNIPER_MFR && (p[0] & MFR_BE_MASK) == MFR_BE_MASK) { l2info->cookie_len = 0; } #endif l2info->header_len += l2info->cookie_len; l2info->length -= l2info->cookie_len; l2info->caplen -= l2info->cookie_len; if (ndo->ndo_eflag) ND_PRINT((ndo, "%s-PIC, cookie-len %u", lp->s, l2info->cookie_len)); if (l2info->cookie_len > 0) { ND_TCHECK2(p[0], l2info->cookie_len); if (ndo->ndo_eflag) ND_PRINT((ndo, ", cookie 0x")); for (idx = 0; idx < l2info->cookie_len; idx++) { l2info->cookie[idx] = p[idx]; /* copy cookie data */ if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx])); } } if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/ l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len); break; } ++lp; } p+=l2info->cookie_len; /* DLT_ specific parsing */ switch(l2info->pictype) { #ifdef DLT_JUNIPER_MLPPP case DLT_JUNIPER_MLPPP: switch (l2info->cookie_type) { case LS_COOKIE_ID: l2info->bundle = l2info->cookie[1]; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; break; } break; #endif #ifdef DLT_JUNIPER_MLFR case DLT_JUNIPER_MLFR: switch (l2info->cookie_type) { case LS_COOKIE_ID: l2info->bundle = l2info->cookie[1]; l2info->proto = EXTRACT_16BITS(p); l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; } break; #endif #ifdef DLT_JUNIPER_MFR case DLT_JUNIPER_MFR: switch (l2info->cookie_type) { case LS_COOKIE_ID: l2info->bundle = l2info->cookie[1]; l2info->proto = EXTRACT_16BITS(p); l2info->header_len += 2; l2info->length -= 2; l2info->caplen -= 2; break; case AS_COOKIE_ID: l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff; l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK; break; default: l2info->bundle = l2info->cookie[0]; break; } break; #endif #ifdef DLT_JUNIPER_ATM2 case DLT_JUNIPER_ATM2: ND_TCHECK2(p[0], 4); /* ATM cell relay control word present ? */ if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) { control_word = EXTRACT_32BITS(p); /* some control word heuristics */ switch(control_word) { case 0: /* zero control word */ case 0x08000000: /* < JUNOS 7.4 control-word */ case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/ l2info->header_len += 4; break; default: break; } if (ndo->ndo_eflag) ND_PRINT((ndo, "control-word 0x%08x ", control_word)); } break; #endif #ifdef DLT_JUNIPER_GGSN case DLT_JUNIPER_GGSN: break; #endif #ifdef DLT_JUNIPER_ATM1 case DLT_JUNIPER_ATM1: break; #endif #ifdef DLT_JUNIPER_PPP case DLT_JUNIPER_PPP: break; #endif #ifdef DLT_JUNIPER_CHDLC case DLT_JUNIPER_CHDLC: break; #endif #ifdef DLT_JUNIPER_ETHER case DLT_JUNIPER_ETHER: break; #endif #ifdef DLT_JUNIPER_FRELAY case DLT_JUNIPER_FRELAY: break; #endif default: ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype)); break; } if (ndo->ndo_eflag > 1) ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto)); return 1; /* everything went ok so far. continue parsing */ trunc: ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len)); return 0; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_7
crossvul-cpp_data_good_351_2
/* * card-authentic.c: Support for the Oberthur smart cards * with PKI applet AuthentIC v3.2 * * Copyright (C) 2010 Viktor Tarasov <vtarasov@opentrust.com> * OpenTrust <www.opentrust.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <string.h> #include <stdlib.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" #include "opensc.h" #include "pkcs15.h" #include "iso7816.h" /* #include "hash-strings.h" */ #include "authentic.h" #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/rsa.h> #include <openssl/pkcs12.h> #include <openssl/x509v3.h> #include <openssl/sha.h> #define AUTHENTIC_CARD_DEFAULT_FLAGS ( 0 \ | SC_ALGORITHM_ONBOARD_KEY_GEN \ | SC_ALGORITHM_RSA_PAD_ISO9796 \ | SC_ALGORITHM_RSA_PAD_PKCS1 \ | SC_ALGORITHM_RSA_HASH_NONE \ | SC_ALGORITHM_RSA_HASH_SHA1 \ | SC_ALGORITHM_RSA_HASH_SHA256) #define AUTHENTIC_READ_BINARY_LENGTH_MAX 0xE7 /* generic iso 7816 operations table */ static const struct sc_card_operations *iso_ops = NULL; /* our operations table with overrides */ static struct sc_card_operations authentic_ops; static struct sc_card_driver authentic_drv = { "Oberthur AuthentIC v3.1", "authentic", &authentic_ops, NULL, 0, NULL }; /* * FIXME: use dynamic allocation for the PIN data to reduce memory usage * actually size of 'authentic_private_data' 140kb */ struct authentic_private_data { struct sc_pin_cmd_data pins[8]; unsigned char pins_sha1[8][SHA_DIGEST_LENGTH]; struct sc_cplc cplc; }; static struct sc_atr_table authentic_known_atrs[] = { { "3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:00:70:0A:90:00:8B", NULL, "Oberthur AuthentIC 3.2.2", SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; unsigned char aid_AuthentIC_3_2[] = { 0xA0,0x00,0x00,0x00,0x77,0x01,0x00,0x70,0x0A,0x10,0x00,0xF1,0x00,0x00,0x01,0x00 }; static int authentic_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out); static int authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen); static int authentic_get_serialnr(struct sc_card *card, struct sc_serial_number *serial); static int authentic_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data); static int authentic_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left); static int authentic_select_mf(struct sc_card *card, struct sc_file **file_out); static int authentic_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr); static void authentic_debug_select_file(struct sc_card *card, const struct sc_path *path); #ifdef ENABLE_SM static int authentic_sm_open(struct sc_card *card); static int authentic_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *apdu, struct sc_apdu **sm_apdu); static int authentic_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *apdu, struct sc_apdu **sm_apdu); #endif static int authentic_update_blob(struct sc_context *ctx, unsigned tag, unsigned char *data, size_t data_len, unsigned char **blob, size_t *blob_size) { unsigned char *pp = NULL; int offs = 0, sz; if (data_len == 0) return SC_SUCCESS; sz = data_len + 2; if (tag > 0xFF) sz++; if (data_len > 0x7F && data_len < 0x100) sz++; else if (data_len >= 0x100) sz += 2; pp = realloc(*blob, *blob_size + sz); if (!pp) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); if (tag > 0xFF) *(pp + *blob_size + offs++) = (tag >> 8) & 0xFF; *(pp + *blob_size + offs++) = tag & 0xFF; if (data_len >= 0x100) { *(pp + *blob_size + offs++) = 0x82; *(pp + *blob_size + offs++) = (data_len >> 8) & 0xFF; } else if (data_len > 0x7F) { *(pp + *blob_size + offs++) = 0x81; } *(pp + *blob_size + offs++) = data_len & 0xFF; memcpy(pp + *blob_size + offs, data, data_len); *blob_size += sz; *blob = pp; return SC_SUCCESS; } static int authentic_parse_size(unsigned char *in, size_t *out) { if (!in || !out) return SC_ERROR_INVALID_ARGUMENTS; if (*in < 0x80) { *out = *in; return 1; } else if (*in == 0x81) { *out = *(in + 1); return 2; } else if (*in == 0x82) { *out = *(in + 1) * 0x100 + *(in + 2); return 3; } return SC_ERROR_INVALID_DATA; } static int authentic_get_tagged_data(struct sc_context *ctx, unsigned char *in, size_t in_len, unsigned in_tag, unsigned char **out, size_t *out_len) { size_t size_len, tag_len, offs, size; unsigned tag; if (!out || !out_len) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); for (offs = 0; offs < in_len; ) { if ((*(in + offs) == 0x7F) || (*(in + offs) == 0x5F)) { tag = *(in + offs) * 0x100 + *(in + offs + 1); tag_len = 2; } else { tag = *(in + offs); tag_len = 1; } size_len = authentic_parse_size(in + offs + tag_len, &size); LOG_TEST_RET(ctx, size_len, "parse error: invalid size data"); if (tag == in_tag) { *out = in + offs + tag_len + size_len; *out_len = size; return SC_SUCCESS; } offs += tag_len + size_len + size; } return SC_ERROR_ASN1_OBJECT_NOT_FOUND; } static int authentic_decode_pubkey_rsa(struct sc_context *ctx, unsigned char *blob, size_t blob_len, struct sc_pkcs15_prkey **out_key) { struct sc_pkcs15_prkey_rsa *key; unsigned char *data; size_t data_len; int rv; LOG_FUNC_CALLED(ctx); if (!out_key) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*out_key)) { *out_key = calloc(1, sizeof(struct sc_pkcs15_prkey)); if (!(*out_key)) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate pkcs15 private key"); (*out_key)->algorithm = SC_ALGORITHM_RSA; } else if (*out_key && (*out_key)->algorithm != SC_ALGORITHM_RSA) { LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA); } key = &(*out_key)->u.rsa; rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_RSA_PUBLIC, &data, &data_len); LOG_TEST_RET(ctx, rv, "cannot get public key SDO data"); blob = data; blob_len = data_len; /* Get RSA public modulus */ rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_RSA_PUBLIC_MODULUS, &data, &data_len); LOG_TEST_RET(ctx, rv, "cannot get public key SDO data"); if (key->modulus.data) free(key->modulus.data); key->modulus.data = calloc(1, data_len); if (!key->modulus.data) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate modulus BN"); memcpy(key->modulus.data, data, data_len); key->modulus.len = data_len; /* Get RSA public exponent */ rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_RSA_PUBLIC_EXPONENT, &data, &data_len); LOG_TEST_RET(ctx, rv, "cannot get public key SDO data"); if (key->exponent.data) free(key->exponent.data); key->exponent.data = calloc(1, data_len); if (!key->exponent.data) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate modulus BN"); memcpy(key->exponent.data, data, data_len); key->exponent.len = data_len; LOG_FUNC_RETURN(ctx, rv); } static int authentic_parse_credential_data(struct sc_context *ctx, struct sc_pin_cmd_data *pin_cmd, unsigned char *blob, size_t blob_len) { unsigned char *data; size_t data_len; int rv, ii; unsigned tag = AUTHENTIC_TAG_CREDENTIAL | pin_cmd->pin_reference; rv = authentic_get_tagged_data(ctx, blob, blob_len, tag, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "cannot get credential data"); rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_TRYLIMIT, &data, &data_len); LOG_TEST_RET(ctx, rv, "cannot get try limit"); pin_cmd->pin1.max_tries = *data; rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_DOCP_MECH, &data, &data_len); LOG_TEST_RET(ctx, rv, "cannot get PIN type"); if (*data == 0) pin_cmd->pin_type = SC_AC_CHV; else if (*data >= 2 && *data <= 7) pin_cmd->pin_type = SC_AC_AUT; else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "unsupported Credential type"); rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_DOCP_ACLS, &data, &data_len); LOG_TEST_RET(ctx, rv, "failed to get ACLs"); sc_log(ctx, "data_len:%"SC_FORMAT_LEN_SIZE_T"u", data_len); if (data_len == 10) { for (ii=0; ii<5; ii++) { unsigned char acl = *(data + ii*2); unsigned char cred_id = *(data + ii*2 + 1); unsigned sc = acl * 0x100 + cred_id; sc_log(ctx, "%i: SC:%X", ii, sc); if (!sc) continue; if (acl & AUTHENTIC_AC_SM_MASK) { pin_cmd->pin1.acls[ii].method = SC_AC_SCB; pin_cmd->pin1.acls[ii].key_ref = sc; } else if (acl!=0xFF && cred_id) { sc_log(ctx, "%i: ACL(method:SC_AC_CHV,id:%i)", ii, cred_id); pin_cmd->pin1.acls[ii].method = SC_AC_CHV; pin_cmd->pin1.acls[ii].key_ref = cred_id; } else { pin_cmd->pin1.acls[ii].method = SC_AC_NEVER; pin_cmd->pin1.acls[ii].key_ref = 0; } } } rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_PINPOLICY, &data, &data_len); if (!rv) { blob = data; blob_len = data_len; rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_PINPOLICY_MAXLENGTH, &data, &data_len); LOG_TEST_RET(ctx, rv, "failed to get PIN max.length value"); pin_cmd->pin1.max_length = *data; rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_PINPOLICY_MINLENGTH, &data, &data_len); LOG_TEST_RET(ctx, rv, "failed to get PIN min.length value"); pin_cmd->pin1.min_length = *data; } return SC_SUCCESS; } static int authentic_get_cplc(struct sc_card *card) { struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data; struct sc_apdu apdu; int rv, ii; unsigned char p1, p2; p1 = (SC_CPLC_TAG >> 8) & 0xFF; p2 = SC_CPLC_TAG & 0xFF; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, p1, p2); for (ii=0;ii<2;ii++) { apdu.le = SC_CPLC_DER_SIZE; apdu.resplen = sizeof(prv_data->cplc.value); apdu.resp = prv_data->cplc.value; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); if (rv != SC_ERROR_CLASS_NOT_SUPPORTED) break; apdu.cla = 0x80; } LOG_TEST_RET(card->ctx, rv, "'GET CPLC' error"); prv_data->cplc.len = SC_CPLC_DER_SIZE; return SC_SUCCESS; } static int authentic_select_aid(struct sc_card *card, unsigned char *aid, size_t aid_len, unsigned char *out, size_t *out_len) { struct sc_apdu apdu; unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE]; int rv; /* Select Card Manager (to deselect previously selected application) */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x04, 0x00); apdu.lc = aid_len; apdu.data = aid; apdu.datalen = aid_len; apdu.resplen = sizeof(apdu_resp); apdu.resp = apdu_resp; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, rv, "Cannot select AID"); if (out && out_len) { if (*out_len < apdu.resplen) LOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, "Cannot select AID"); memcpy(out, apdu.resp, apdu.resplen); } return SC_SUCCESS; } static int authentic_match_card(struct sc_card *card) { struct sc_context *ctx = card->ctx; int i; sc_log_hex(ctx, "try to match card with ATR", card->atr.value, card->atr.len); i = _sc_match_atr(card, authentic_known_atrs, &card->type); if (i < 0) { sc_log(ctx, "card not matched"); return 0; } sc_log(ctx, "'%s' card matched", authentic_known_atrs[i].name); return 1; } static int authentic_init_oberthur_authentic_3_2(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned int flags; int rv = 0; LOG_FUNC_CALLED(ctx); flags = AUTHENTIC_CARD_DEFAULT_FLAGS; _sc_card_add_rsa_alg(card, 1024, flags, 0x10001); _sc_card_add_rsa_alg(card, 2048, flags, 0x10001); card->caps = SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; card->caps |= SC_CARD_CAP_USE_FCI_AC; #ifdef ENABLE_SM card->sm_ctx.ops.open = authentic_sm_open; card->sm_ctx.ops.get_sm_apdu = authentic_sm_get_wrapped_apdu; card->sm_ctx.ops.free_sm_apdu = authentic_sm_free_wrapped_apdu; #endif rv = authentic_select_aid(card, aid_AuthentIC_3_2, sizeof(aid_AuthentIC_3_2), NULL, NULL); LOG_TEST_RET(ctx, rv, "AuthentIC application select error"); rv = authentic_select_mf(card, NULL); LOG_TEST_RET(ctx, rv, "MF selection error"); LOG_FUNC_RETURN(ctx, rv); } static int authentic_init(struct sc_card *card) { struct sc_context *ctx = card->ctx; int ii, rv = SC_ERROR_INVALID_CARD; LOG_FUNC_CALLED(ctx); for(ii=0;authentic_known_atrs[ii].atr;ii++) { if (card->type == authentic_known_atrs[ii].type) { card->name = authentic_known_atrs[ii].name; card->flags = authentic_known_atrs[ii].flags; break; } } if (!authentic_known_atrs[ii].atr) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD); card->cla = 0x00; card->drv_data = (struct authentic_private_data *) calloc(sizeof(struct authentic_private_data), 1); if (!card->drv_data) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); if (card->type == SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2) rv = authentic_init_oberthur_authentic_3_2(card); if (rv != SC_SUCCESS) rv = authentic_get_serialnr(card, NULL); if (rv != SC_SUCCESS) rv = SC_ERROR_INVALID_CARD; LOG_FUNC_RETURN(ctx, rv); } static int authentic_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; int rv; unsigned char *buf_zero = NULL; LOG_FUNC_CALLED(ctx); if (!count) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "'ERASE BINARY' with ZERO count not supported"); if (card->cache.valid && card->cache.current_ef) sc_log(ctx, "current_ef(type=%i) %s", card->cache.current_ef->path.type, sc_print_path(&card->cache.current_ef->path)); buf_zero = calloc(1, count); if (!buf_zero) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "cannot allocate buff 'zero'"); rv = sc_update_binary(card, offs, buf_zero, count, flags); free(buf_zero); LOG_TEST_RET(ctx, rv, "'ERASE BINARY' failed"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int authentic_set_current_files(struct sc_card *card, struct sc_path *path, unsigned char *resp, size_t resplen, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_file *file = NULL; int rv; LOG_FUNC_CALLED(ctx); if (resplen) { switch (resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); if (path) file->path = *path; rv = authentic_process_fci(card, file, resp, resplen); LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error"); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } if (file->type == SC_FILE_TYPE_DF) { struct sc_path cur_df_path; memset(&cur_df_path, 0, sizeof(cur_df_path)); if (card->cache.valid && card->cache.current_df) { cur_df_path = card->cache.current_df->path; sc_file_free(card->cache.current_df); } card->cache.current_df = NULL; sc_file_dup(&card->cache.current_df, file); if (cur_df_path.len) { if (cur_df_path.len + card->cache.current_df->path.len > sizeof card->cache.current_df->path.value || cur_df_path.len > sizeof card->cache.current_df->path.value) LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); memcpy(card->cache.current_df->path.value + cur_df_path.len, card->cache.current_df->path.value, card->cache.current_df->path.len); memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len); card->cache.current_df->path.len += cur_df_path.len; } sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } else { sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) *file_out = file; else sc_file_free(file); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int authentic_select_mf(struct sc_card *card, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_path mfpath; int rv; struct sc_apdu apdu; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; LOG_FUNC_CALLED(ctx); sc_format_path("3F00", &mfpath); mfpath.type = SC_PATH_TYPE_PATH; if (card->cache.valid == 1 && card->cache.current_df && card->cache.current_df->path.len == 2 && !memcmp(card->cache.current_df->path.value, "\x3F\x00", 2)) { if (file_out) sc_file_dup(file_out, card->cache.current_df); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xA4, 0x00, 0x00); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "authentic_select_file() check SW failed"); if (card->cache.valid == 1) { sc_file_free(card->cache.current_df); card->cache.current_df = NULL; sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; } rv = authentic_set_current_files(card, &mfpath, apdu.resp, apdu.resplen, file_out); LOG_TEST_RET(ctx, rv, "authentic_select_file() cannot set 'current_file'"); LOG_FUNC_RETURN(ctx, rv); } static int authentic_reduce_path(struct sc_card *card, struct sc_path *path) { struct sc_context *ctx = card->ctx; struct sc_path in_path, cur_path; size_t offs; LOG_FUNC_CALLED(ctx); if (!path || path->len <= 2 || path->type == SC_PATH_TYPE_DF_NAME) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (!card->cache.valid || !card->cache.current_df) LOG_FUNC_RETURN(ctx, 0); in_path = *path; cur_path = card->cache.current_df->path; if (!memcmp(cur_path.value, "\x3F\x00", 2) && memcmp(in_path.value, "\x3F\x00", 2)) { memmove(in_path.value + 2, in_path.value, in_path.len); memcpy(in_path.value, "\x3F\x00", 2); in_path.len += 2; } for (offs=0; offs < in_path.len && offs < cur_path.len; offs += 2) { if (cur_path.value[offs] != in_path.value[offs]) break; if (cur_path.value[offs + 1] != in_path.value[offs + 1]) break; } memmove(in_path.value, in_path.value + offs, sizeof(in_path.value) - offs); in_path.len -= offs; *path = in_path; LOG_FUNC_RETURN(ctx, offs); } static void authentic_debug_select_file(struct sc_card *card, const struct sc_path *path) { struct sc_context *ctx = card->ctx; struct sc_card_cache *cache = &card->cache; if (path) sc_log(ctx, "try to select path(type:%i) %s", path->type, sc_print_path(path)); if (!cache->valid) return; if (cache->current_df) sc_log(ctx, "current_df(type=%i) %s", cache->current_df->path.type, sc_print_path(&cache->current_df->path)); else sc_log(ctx, "current_df empty"); if (cache->current_ef) sc_log(ctx, "current_ef(type=%i) %s", cache->current_ef->path.type, sc_print_path(&cache->current_ef->path)); else sc_log(ctx, "current_ef empty"); } static int authentic_is_selected(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out) { if (!path->len) { if (file_out && card->cache.valid && card->cache.current_df) sc_file_dup(file_out, card->cache.current_df); return SC_SUCCESS; } else if (path->len == 2 && card->cache.valid && card->cache.current_ef) { if (!memcmp(card->cache.current_ef->path.value, path->value, 2)) { if (file_out) sc_file_dup(file_out, card->cache.current_ef); return SC_SUCCESS; } } return SC_ERROR_FILE_NOT_FOUND; } static int authentic_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; struct sc_path lpath; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int pathlen, rv; LOG_FUNC_CALLED(ctx); authentic_debug_select_file(card, path); memcpy(&lpath, path, sizeof(struct sc_path)); rv = authentic_reduce_path(card, &lpath); LOG_TEST_RET(ctx, rv, "reduce path error"); if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) { rv = authentic_select_mf(card, file_out); LOG_TEST_RET(ctx, rv, "cannot select MF"); memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2); lpath.len -= 2; if (!lpath.len) LOG_FUNC_RETURN(ctx, SC_SUCCESS); } if (lpath.type == SC_PATH_TYPE_PATH && (lpath.len == 2)) lpath.type = SC_PATH_TYPE_FILE_ID; rv = authentic_is_selected(card, &lpath, file_out); if (!rv) LOG_FUNC_RETURN(ctx, SC_SUCCESS); pathlen = lpath.len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); if (card->type != SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card"); if (lpath.type == SC_PATH_TYPE_FILE_ID) { apdu.p1 = 0x00; } else if (lpath.type == SC_PATH_TYPE_PATH) { apdu.p1 = 0x08; } else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) { apdu.p1 = 0x09; } else if (lpath.type == SC_PATH_TYPE_DF_NAME) { apdu.p1 = 4; } else if (lpath.type == SC_PATH_TYPE_PARENT) { apdu.p1 = 0x03; pathlen = 0; apdu.cse = SC_APDU_CASE_2_SHORT; } else { sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type); LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "authentic_select_file() invalid PATH type"); } apdu.lc = pathlen; apdu.data = lpath.value; apdu.datalen = pathlen; if (apdu.cse == SC_APDU_CASE_4_SHORT || apdu.cse == SC_APDU_CASE_2_SHORT) { apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; } rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "authentic_select_file() check SW failed"); rv = authentic_set_current_files(card, &lpath, apdu.resp, apdu.resplen, file_out); LOG_TEST_RET(ctx, rv, "authentic_select_file() cannot set 'current_file'"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int authentic_read_binary(struct sc_card *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; size_t sz, rest, ret_count = 0; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); sc_log(ctx, "offs:%i,count:%"SC_FORMAT_LEN_SIZE_T"u,max_recv_size:%"SC_FORMAT_LEN_SIZE_T"u", idx, count, card->max_recv_size); rest = count; while(rest) { sz = rest > 256 ? 256 : rest; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (idx >> 8) & 0x7F, idx & 0xFF); apdu.le = sz; apdu.resplen = sz; apdu.resp = (buf + ret_count); rv = sc_transmit_apdu(card, &apdu); if(!rv) ret_count += apdu.resplen; else break; idx += sz; rest -= sz; } if (rv) { LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "authentic_read_binary() failed"); LOG_FUNC_RETURN(ctx, count); } rv = sc_check_sw(card, apdu.sw1, apdu.sw2); if (!rv) count = ret_count; LOG_TEST_RET(ctx, rv, "authentic_read_binary() failed"); LOG_FUNC_RETURN(ctx, count); } static int authentic_write_binary(struct sc_card *card, unsigned int idx, const unsigned char *buf, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; size_t sz, rest; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); sc_log(ctx, "offs:%i,count:%"SC_FORMAT_LEN_SIZE_T"u,max_send_size:%"SC_FORMAT_LEN_SIZE_T"u", idx, count, card->max_send_size); rest = count; while(rest) { sz = rest > 255 ? 255 : rest; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xD0, (idx >> 8) & 0x7F, idx & 0xFF); apdu.lc = sz; apdu.datalen = sz; apdu.data = buf + count - rest; rv = sc_transmit_apdu(card, &apdu); if(rv) break; idx += sz; rest -= sz; } if (rv) { LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "authentic_write_binary() failed"); LOG_FUNC_RETURN(ctx, count); } rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "authentic_write_binary() failed"); LOG_FUNC_RETURN(ctx, count); } static int authentic_update_binary(struct sc_card *card, unsigned int idx, const unsigned char *buf, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; size_t sz, rest; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); sc_log(ctx, "offs:%i,count:%"SC_FORMAT_LEN_SIZE_T"u,max_send_size:%"SC_FORMAT_LEN_SIZE_T"u", idx, count, card->max_send_size); rest = count; while(rest) { sz = rest > 255 ? 255 : rest; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xD6, (idx >> 8) & 0x7F, idx & 0xFF); apdu.lc = sz; apdu.datalen = sz; apdu.data = buf + count - rest; rv = sc_transmit_apdu(card, &apdu); if(rv) break; idx += sz; rest -= sz; } if (rv) { LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "authentic_update_binary() failed"); LOG_FUNC_RETURN(ctx, count); } rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "authentic_update_binary() failed"); LOG_FUNC_RETURN(ctx, count); } static int authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv; unsigned ii; const unsigned char *tag = NULL; unsigned char ops_DF[8] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; unsigned char ops_EF[8] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); if (!file->sec_attr_len) { sc_log_hex(ctx, "ACLs not found in data", buf, buflen); sc_log(ctx, "Path:%s; Type:%X; PathType:%X", sc_print_path(&file->path), file->type, file->path.type); if (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) { file->type = SC_FILE_TYPE_DF; } else { LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } } sc_log_hex(ctx, "ACL data", file->sec_attr, file->sec_attr_len); for (ii = 0; ii < file->sec_attr_len / 2 && ii < sizeof ops_DF; ii++) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; unsigned char acl = *(file->sec_attr + ii*2); unsigned char cred_id = *(file->sec_attr + ii*2 + 1); unsigned sc = acl * 0x100 + cred_id; sc_log(ctx, "ACL(%i) op 0x%X, acl %X:%X", ii, op, acl, cred_id); if (op == 0xFF) ; else if (!acl && !cred_id) sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); else if (acl == 0xFF) sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); else if (acl & AUTHENTIC_AC_SM_MASK) sc_file_add_acl_entry(file, op, SC_AC_SCB, sc); else if (cred_id) sc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id); else sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } LOG_FUNC_RETURN(ctx, 0); } static int authentic_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; unsigned char buf[0x80]; size_t ii, offs; unsigned char ops_ef[4] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE }; unsigned char ops_df[3] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO }; unsigned char *ops = file->type == SC_FILE_TYPE_DF ? ops_df : ops_ef; size_t ops_len = file->type == SC_FILE_TYPE_DF ? 3 : 4; LOG_FUNC_CALLED(ctx); offs = 0; buf[offs++] = ISO7816_TAG_FCP_SIZE; buf[offs++] = 2; buf[offs++] = (file->size >> 8) & 0xFF; buf[offs++] = file->size & 0xFF; buf[offs++] = ISO7816_TAG_FCP_TYPE; buf[offs++] = 1; buf[offs++] = file->type == SC_FILE_TYPE_DF ? ISO7816_FILE_TYPE_DF : ISO7816_FILE_TYPE_TRANSPARENT_EF; buf[offs++] = ISO7816_TAG_FCP_FID; buf[offs++] = 2; buf[offs++] = (file->id >> 8) & 0xFF; buf[offs++] = file->id & 0xFF; buf[offs++] = ISO7816_TAG_FCP_ACLS; buf[offs++] = ops_len * 2; for (ii=0; ii < ops_len; ii++) { const struct sc_acl_entry *entry; entry = sc_file_get_acl_entry(file, ops[ii]); sc_log(ctx, "acl entry(method:%X,ref:%X)", entry->method, entry->key_ref); if (entry->method == SC_AC_NEVER) { /* TODO: After development change for 0xFF */ buf[offs++] = 0x00; buf[offs++] = 0x00; } else if (entry->method == SC_AC_NONE) { buf[offs++] = 0x00; buf[offs++] = 0x00; } else if (entry->method == SC_AC_CHV) { if (!(entry->key_ref & AUTHENTIC_V3_CREDENTIAL_ID_MASK) || (entry->key_ref & ~AUTHENTIC_V3_CREDENTIAL_ID_MASK)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported Credential Reference"); buf[offs++] = 0x00; buf[offs++] = 0x01 << (entry->key_ref - 1); } else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported AC method"); } if (out) { if (out_len < offs) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to encode FCP"); memcpy(out, buf, offs); } LOG_FUNC_RETURN(ctx, offs); } static int authentic_create_file(struct sc_card *card, struct sc_file *file) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char sbuf[0x100]; size_t sbuf_len; struct sc_path path; int rv; LOG_FUNC_CALLED(ctx); if (file->type != SC_FILE_TYPE_WORKING_EF) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Creation of the file with of this type is not supported"); authentic_debug_select_file(card, &file->path); sbuf_len = authentic_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2); LOG_TEST_RET(ctx, sbuf_len, "FCP encode error"); sbuf[0] = ISO7816_TAG_FCP; sbuf[1] = sbuf_len; if (card->cache.valid && card->cache.current_df) { const struct sc_acl_entry *entry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE); sc_log(ctx, "CREATE method/reference %X/%X", entry->method, entry->key_ref); if (entry->method == SC_AC_SCB) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet supported"); } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0); apdu.data = sbuf; apdu.datalen = sbuf_len + 2; apdu.lc = sbuf_len + 2; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "authentic_create_file() create file error"); path = file->path; memcpy(path.value, path.value + path.len - 2, 2); path.len = 2; rv = authentic_set_current_files(card, &path, sbuf, sbuf_len + 2, NULL); LOG_TEST_RET(ctx, rv, "authentic_select_file() cannot set 'current_file'"); LOG_FUNC_RETURN(ctx, rv); } static int authentic_delete_file(struct sc_card *card, const struct sc_path *path) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char p1; int rv, ii; LOG_FUNC_CALLED(ctx); if (!path) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); for (ii=0, p1 = 0x02; ii<2; ii++, p1 = 0x01) { sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, p1, 0x00); apdu.data = path->value + path->len - 2; apdu.datalen = 2; apdu.lc = 2; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); if (rv != SC_ERROR_FILE_NOT_FOUND || p1 != 0x02) break; } LOG_TEST_RET(ctx, rv, "Delete file failed"); if (card->cache.valid) { sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; } LOG_FUNC_RETURN(ctx, rv); } static int authentic_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left) { struct sc_context *ctx = card->ctx; unsigned char buffer[0x100]; struct sc_pin_cmd_pin *pin1 = &pin_cmd->pin1; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Verify PIN(ref:%i) with pin-pad", pin_cmd->pin_reference); rv = authentic_pin_is_verified(card, pin_cmd, tries_left); if (!rv) LOG_FUNC_RETURN(ctx, rv); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } pin1->len = pin1->min_length; pin1->max_length = 8; memset(buffer, pin1->pad_char, sizeof(buffer)); pin1->data = buffer; pin_cmd->cmd = SC_PIN_CMD_VERIFY; pin_cmd->flags |= SC_PIN_CMD_USE_PINPAD; rv = iso_ops->pin_cmd(card, pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } static int authentic_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; struct sc_pin_cmd_pin *pin1 = &pin_cmd->pin1; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "CHV PIN reference %i, pin1(%p,len:%i)", pin_cmd->pin_reference, pin1->data, pin1->len); if (pin1->data && !pin1->len) { sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference); } else if (pin1->data && pin1->len) { unsigned char pin_buff[SC_MAX_APDU_BUFFER_SIZE]; size_t pin_len; memcpy(pin_buff, pin1->data, pin1->len); pin_len = pin1->len; if (pin1->pad_length && pin_cmd->flags & SC_PIN_CMD_NEED_PADDING) { memset(pin_buff + pin1->len, pin1->pad_char, pin1->pad_length - pin1->len); pin_len = pin1->pad_length; } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference); apdu.data = pin_buff; apdu.datalen = pin_len; apdu.lc = pin_len; } else if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin1->data && !pin1->len) { rv = authentic_chv_verify_pinpad(card, pin_cmd, tries_left); sc_log(ctx, "authentic_chv_verify() authentic_chv_verify_pinpad returned %i", rv); LOG_FUNC_RETURN(ctx, rv); } else { LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); if (apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0) { pin1->tries_left = apdu.sw2 & 0x0F; if (tries_left) *tries_left = apdu.sw2 & 0x0F; } rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_FUNC_RETURN(ctx, rv); } static int authentic_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; int rv; LOG_FUNC_CALLED(ctx); if (pin_cmd_data->pin_type != SC_AC_CHV) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN type is not supported for the verification"); pin_cmd = *pin_cmd_data; pin_cmd.pin1.data = (unsigned char *)""; pin_cmd.pin1.len = 0; rv = authentic_chv_verify(card, &pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } static int authentic_pin_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd) { struct sc_context *ctx = card->ctx; struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data; unsigned char pin_sha1[SHA_DIGEST_LENGTH]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "PIN(type:%X,reference:%X,data:%p,length:%i)", pin_cmd->pin_type, pin_cmd->pin_reference, pin_cmd->pin1.data, pin_cmd->pin1.len); if (pin_cmd->pin1.data && !pin_cmd->pin1.len) { pin_cmd->pin1.tries_left = -1; rv = authentic_pin_is_verified(card, pin_cmd, &pin_cmd->pin1.tries_left); LOG_FUNC_RETURN(ctx, rv); } if (pin_cmd->pin1.data) SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_sha1); else SHA1((unsigned char *)"", 0, pin_sha1); if (!memcmp(pin_sha1, prv_data->pins_sha1[pin_cmd->pin_reference], SHA_DIGEST_LENGTH)) { sc_log(ctx, "Already verified"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } memset(prv_data->pins_sha1[pin_cmd->pin_reference], 0, sizeof(prv_data->pins_sha1[0])); rv = authentic_pin_get_policy(card, pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); if (pin_cmd->pin1.len > (int)pin_cmd->pin1.max_length) LOG_TEST_RET(ctx, SC_ERROR_INVALID_PIN_LENGTH, "PIN policy check failed"); pin_cmd->pin1.tries_left = -1; rv = authentic_chv_verify(card, pin_cmd, &pin_cmd->pin1.tries_left); LOG_TEST_RET(ctx, rv, "PIN CHV verification error"); memcpy(prv_data->pins_sha1[pin_cmd->pin_reference], pin_sha1, SHA_DIGEST_LENGTH); LOG_FUNC_RETURN(ctx, rv); } static int authentic_pin_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned char pin1_data[SC_MAX_APDU_BUFFER_SIZE], pin2_data[SC_MAX_APDU_BUFFER_SIZE]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "CHV PINPAD PIN reference %i", reference); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = reference; pin_cmd.cmd = SC_PIN_CMD_CHANGE; pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD | SC_PIN_CMD_NEED_PADDING; rv = authentic_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); memset(pin1_data, pin_cmd.pin1.pad_char, sizeof(pin1_data)); pin_cmd.pin1.data = pin1_data; pin_cmd.pin1.len = pin_cmd.pin1.min_length; pin_cmd.pin1.max_length = 8; memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1)); memset(pin2_data, pin_cmd.pin2.pad_char, sizeof(pin2_data)); pin_cmd.pin2.data = pin2_data; sc_log(ctx, "PIN1 lengths max/min/pad: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length, pin_cmd.pin1.pad_length); sc_log(ctx, "PIN2 lengths max/min/pad: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length, pin_cmd.pin2.pad_length); rv = iso_ops->pin_cmd(card, &pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } static int authentic_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data; struct sc_apdu apdu; unsigned char pin_data[SC_MAX_APDU_BUFFER_SIZE]; size_t offs; int rv; rv = authentic_pin_get_policy(card, data); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); memset(prv_data->pins_sha1[data->pin_reference], 0, sizeof(prv_data->pins_sha1[0])); if (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) { if (!(card->reader->capabilities & SC_READER_CAP_PIN_PAD)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN pad not supported"); rv = authentic_pin_change_pinpad(card, data->pin_reference, tries_left); sc_log(ctx, "authentic_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i", rv); LOG_FUNC_RETURN(ctx, rv); } if (card->max_send_size && (data->pin1.len + data->pin2.len > (int)card->max_send_size)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_PIN_LENGTH, "APDU transmit failed"); memset(pin_data, data->pin1.pad_char, sizeof(pin_data)); offs = 0; if (data->pin1.data && data->pin1.len) { memcpy(pin_data, data->pin1.data, data->pin1.len); offs += data->pin1.pad_length; } if (data->pin2.data && data->pin2.len) memcpy(pin_data + offs, data->pin2.data, data->pin2.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, offs ? 0x00 : 0x01, data->pin_reference); apdu.data = pin_data; apdu.datalen = offs + data->pin1.pad_length; apdu.lc = offs + data->pin1.pad_length; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_FUNC_RETURN(ctx, rv); } static int authentic_chv_set_pinpad(struct sc_card *card, unsigned char reference) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned char pin_data[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Set CHV PINPAD PIN reference %i", reference); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = reference; pin_cmd.cmd = SC_PIN_CMD_UNBLOCK; pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD | SC_PIN_CMD_NEED_PADDING; rv = authentic_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); memset(pin_data, pin_cmd.pin1.pad_char, sizeof(pin_data)); pin_cmd.pin1.data = pin_data; pin_cmd.pin1.len = pin_cmd.pin1.min_length; pin_cmd.pin1.max_length = 8; memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1)); memset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1)); sc_log(ctx, "PIN2 max/min/pad %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length, pin_cmd.pin2.pad_length); rv = iso_ops->pin_cmd(card, &pin_cmd, NULL); LOG_FUNC_RETURN(ctx, rv); } static int authentic_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char rbuf[0x100]; int ii, rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "get PIN(type:%X,ref:%X,tries-left:%i)", data->pin_type, data->pin_reference, data->pin1.tries_left); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0x5F, data->pin_reference); for (ii=0;ii<2;ii++) { apdu.le = sizeof(rbuf); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); if (rv != SC_ERROR_CLASS_NOT_SUPPORTED) break; apdu.cla = 0x80; } LOG_TEST_RET(ctx, rv, "'GET DATA' error"); data->pin1.tries_left = -1; rv = authentic_parse_credential_data(ctx, data, apdu.resp, apdu.resplen); LOG_TEST_RET(ctx, rv, "Cannot parse credential data"); data->pin1.encoding = SC_PIN_ENCODING_ASCII; data->pin1.offset = 5; data->pin1.pad_char = 0xFF; data->pin1.pad_length = data->pin1.max_length; data->pin1.logged_in = SC_PIN_STATE_UNKNOWN; data->flags |= SC_PIN_CMD_NEED_PADDING; sc_log(ctx, "PIN policy: size max/min/pad %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u, tries max/left %i/%i", data->pin1.max_length, data->pin1.min_length, data->pin1.pad_length, data->pin1.max_tries, data->pin1.tries_left); LOG_FUNC_RETURN(ctx, rv); } static int authentic_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data; struct sc_pin_cmd_data pin_cmd, puk_cmd; struct sc_apdu apdu; unsigned reference; int rv, ii; LOG_FUNC_CALLED(ctx); sc_log(ctx, "reset PIN (ref:%i,lengths %i/%i)", data->pin_reference, data->pin1.len, data->pin2.len); memset(prv_data->pins_sha1[data->pin_reference], 0, sizeof(prv_data->pins_sha1[0])); memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_reference = data->pin_reference; pin_cmd.pin_type = data->pin_type; pin_cmd.pin1.tries_left = -1; rv = authentic_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); if (pin_cmd.pin1.acls[AUTHENTIC_ACL_NUM_PIN_RESET].method == SC_AC_CHV) { for (ii=0;ii<8;ii++) { unsigned char mask = 0x01 << ii; if (pin_cmd.pin1.acls[AUTHENTIC_ACL_NUM_PIN_RESET].key_ref & mask) { memset(&puk_cmd, 0, sizeof(puk_cmd)); puk_cmd.pin_reference = ii + 1; rv = authentic_pin_get_policy(card, &puk_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); if (puk_cmd.pin_type == SC_AC_CHV) break; } } if (ii < 8) { puk_cmd.pin1.data = data->pin1.data; puk_cmd.pin1.len = data->pin1.len; rv = authentic_pin_verify(card, &puk_cmd); if (tries_left && rv == SC_ERROR_PIN_CODE_INCORRECT) *tries_left = puk_cmd.pin1.tries_left; LOG_TEST_RET(ctx, rv, "Cannot verify PUK"); } } reference = data->pin_reference; if (data->pin2.len) { unsigned char pin_data[SC_MAX_APDU_BUFFER_SIZE]; memset(pin_data, pin_cmd.pin1.pad_char, sizeof(pin_data)); memcpy(pin_data, data->pin2.data, data->pin2.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference); apdu.data = pin_data; apdu.datalen = pin_cmd.pin1.pad_length; apdu.lc = pin_cmd.pin1.pad_length; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); } else if (data->pin2.data) { sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); } else { rv = authentic_chv_set_pinpad(card, reference); LOG_TEST_RET(ctx, rv, "Failed to set PIN with pin-pad"); } LOG_FUNC_RETURN(ctx, rv); } static int authentic_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; int rv = SC_ERROR_INTERNAL; LOG_FUNC_CALLED(ctx); sc_log(ctx, "PIN-CMD:%X,PIN(type:%X,ret:%i)", data->cmd, data->pin_type, data->pin_reference); sc_log(ctx, "PIN1(%p,len:%i,tries-left:%i)", data->pin1.data, data->pin1.len, data->pin1.tries_left); sc_log(ctx, "PIN2(%p,len:%i)", data->pin2.data, data->pin2.len); switch (data->cmd) { case SC_PIN_CMD_VERIFY: rv = authentic_pin_verify(card, data); break; case SC_PIN_CMD_CHANGE: rv = authentic_pin_change(card, data, tries_left); break; case SC_PIN_CMD_UNBLOCK: rv = authentic_pin_reset(card, data, tries_left); break; case SC_PIN_CMD_GET_INFO: rv = authentic_pin_get_policy(card, data); break; default: LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported PIN command"); } if (rv == SC_ERROR_PIN_CODE_INCORRECT && tries_left) *tries_left = data->pin1.tries_left; LOG_FUNC_RETURN(ctx, rv); } static int authentic_get_serialnr(struct sc_card *card, struct sc_serial_number *serial) { struct sc_context *ctx = card->ctx; struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data; int rv; LOG_FUNC_CALLED(ctx); if (!card->serialnr.len) { rv = authentic_get_cplc(card); LOG_TEST_RET(ctx, rv, "get CPLC data error"); card->serialnr.len = 4; memcpy(card->serialnr.value, prv_data->cplc.value + 15, 4); sc_log(ctx, "serial %02X%02X%02X%02X", card->serialnr.value[0], card->serialnr.value[1], card->serialnr.value[2], card->serialnr.value[3]); } if (serial) memcpy(serial, &card->serialnr, sizeof(*serial)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int authentic_get_challenge(struct sc_card *card, unsigned char *rnd, size_t len) { /* 'GET CHALLENGE' returns always 24 bytes */ unsigned char rbuf[0x18]; size_t out_len; int r; LOG_FUNC_CALLED(card->ctx); r = iso_ops->get_challenge(card, rbuf, sizeof rbuf); LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed"); if (len < (size_t) r) { out_len = len; } else { out_len = (size_t) r; } memcpy(rnd, rbuf, out_len); LOG_FUNC_RETURN(card->ctx, out_len); } static int authentic_manage_sdo_encode_prvkey(struct sc_card *card, struct sc_pkcs15_prkey *prvkey, unsigned char **out, size_t *out_len) { struct sc_context *ctx = card->ctx; struct sc_pkcs15_prkey_rsa rsa; unsigned char *blob = NULL, *blob01 = NULL; size_t blob_len = 0, blob01_len = 0; int rv; if (!prvkey || !out || !out_len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments"); if (prvkey->algorithm != SC_ALGORITHM_RSA) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO operation"); rsa = prvkey->u.rsa; /* Encode private RSA key part */ rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_P, rsa.p.data, rsa.p.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA P encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_Q, rsa.q.data, rsa.q.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA Q encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_PQ, rsa.iqmp.data, rsa.iqmp.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA PQ encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_DP1, rsa.dmp1.data, rsa.dmp1.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA DP1 encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_DQ1, rsa.dmq1.data, rsa.dmq1.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA DQ1 encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE, blob, blob_len, &blob01, &blob01_len); LOG_TEST_RET(ctx, rv, "SDO RSA Private encode error"); free (blob); blob = NULL; blob_len = 0; /* Encode public RSA key part */ sc_log(ctx, "modulus.len:%"SC_FORMAT_LEN_SIZE_T"u blob_len:%"SC_FORMAT_LEN_SIZE_T"u", rsa.modulus.len, blob_len); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_MODULUS, rsa.modulus.data, rsa.modulus.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA Modulus encode error"); sc_log(ctx, "exponent.len:%"SC_FORMAT_LEN_SIZE_T"u blob_len:%"SC_FORMAT_LEN_SIZE_T"u", rsa.exponent.len, blob_len); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_EXPONENT, rsa.exponent.data, rsa.exponent.len, &blob, &blob_len); LOG_TEST_RET(ctx, rv, "SDO RSA Exponent encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC, blob, blob_len, &blob01, &blob01_len); LOG_TEST_RET(ctx, rv, "SDO RSA Private encode error"); free (blob); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA, blob01, blob01_len, out, out_len); LOG_TEST_RET(ctx, rv, "SDO RSA encode error"); free(blob01); LOG_FUNC_RETURN(ctx, rv); } static int authentic_manage_sdo_encode(struct sc_card *card, struct sc_authentic_sdo *sdo, unsigned long cmd, unsigned char **out, size_t *out_len) { struct sc_context *ctx = card->ctx; unsigned char *data = NULL; size_t data_len = 0; unsigned char data_tag = AUTHENTIC_TAG_DOCP; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "encode SDO operation (cmd:%lX,mech:%X,id:%X)", cmd, sdo->docp.mech, sdo->docp.id); if (!out || !out_len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_MECH, &sdo->docp.mech, sizeof(sdo->docp.mech), &data, &data_len); LOG_TEST_RET(ctx, rv, "DOCP MECH encode error"); rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_ID, &sdo->docp.id, sizeof(sdo->docp.id), &data, &data_len); LOG_TEST_RET(ctx, rv, "DOCP ID encode error"); if (cmd == SC_CARDCTL_AUTHENTIC_SDO_CREATE) { rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_ACLS, sdo->docp.acl_data, sdo->docp.acl_data_len, &data, &data_len); LOG_TEST_RET(ctx, rv, "DOCP ACLs encode error"); if (sdo->docp.security_parameter) { rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_SCP, &sdo->docp.security_parameter, sizeof(sdo->docp.security_parameter), &data, &data_len); LOG_TEST_RET(ctx, rv, "DOCP ACLs encode error"); } if (sdo->docp.usage_counter[0] || sdo->docp.usage_counter[1]) { rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_USAGE_COUNTER, sdo->docp.usage_counter, sizeof(sdo->docp.usage_counter), &data, &data_len); LOG_TEST_RET(ctx, rv, "DOCP ACLs encode error"); } } else if (cmd == SC_CARDCTL_AUTHENTIC_SDO_STORE) { if (sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1024 || sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1280 || sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1536 || sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1792 || sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA2048) { rv = authentic_manage_sdo_encode_prvkey(card, sdo->data.prvkey, &data, &data_len); LOG_TEST_RET(ctx, rv, "SDO RSA encode error"); } else { LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cryptographic object unsupported for encoding"); } } else if (cmd == SC_CARDCTL_AUTHENTIC_SDO_GENERATE) { if (sdo->data.prvkey) { rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_EXPONENT, sdo->data.prvkey->u.rsa.exponent.data, sdo->data.prvkey->u.rsa.exponent.len, &data, &data_len); LOG_TEST_RET(ctx, rv, "SDO RSA Exponent encode error"); } data_tag = AUTHENTIC_TAG_RSA_GENERATE_DATA; } else if (cmd != SC_CARDCTL_AUTHENTIC_SDO_DELETE) { LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO operation"); } rv = authentic_update_blob(ctx, data_tag, data, data_len, out, out_len); LOG_TEST_RET(ctx, rv, "SDO DOCP encode error"); free(data); sc_log_hex(ctx, "encoded SDO operation data", *out, *out_len); LOG_FUNC_RETURN(ctx, rv); } static int authentic_manage_sdo_generate(struct sc_card *card, struct sc_authentic_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char rbuf[0x400]; unsigned char *data = NULL; size_t data_len = 0; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Generate SDO(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id); rv = authentic_manage_sdo_encode(card, sdo, SC_CARDCTL_AUTHENTIC_SDO_GENERATE, &data, &data_len); LOG_TEST_RET(ctx, rv, "Cannot encode SDO data"); sc_log(ctx, "encoded SDO length %"SC_FORMAT_LEN_SIZE_T"u", data_len); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00); apdu.data = data; apdu.datalen = data_len; apdu.lc = data_len; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "authentic_sdo_create() SDO put data error"); rv = authentic_decode_pubkey_rsa(ctx, apdu.resp, apdu.resplen, &sdo->data.prvkey); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, rv, "cannot decode public key"); free(data); LOG_FUNC_RETURN(ctx, rv); } static int authentic_manage_sdo(struct sc_card *card, struct sc_authentic_sdo *sdo, unsigned long cmd) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char *data = NULL; size_t data_len = 0, save_max_send = card->max_send_size; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "SDO(cmd:%lX,mech:%X,id:%X)", cmd, sdo->docp.mech, sdo->docp.id); rv = authentic_manage_sdo_encode(card, sdo, cmd, &data, &data_len); LOG_TEST_RET(ctx, rv, "Cannot encode SDO data"); sc_log(ctx, "encoded SDO length %"SC_FORMAT_LEN_SIZE_T"u", data_len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF); apdu.data = data; apdu.datalen = data_len; apdu.lc = data_len; apdu.flags |= SC_APDU_FLAGS_CHAINING; if (card->max_send_size > 255) card->max_send_size = 255; rv = sc_transmit_apdu(card, &apdu); card->max_send_size = save_max_send; LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "authentic_sdo_create() SDO put data error"); free(data); LOG_FUNC_RETURN(ctx, rv); } static int authentic_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { struct sc_context *ctx = card->ctx; struct sc_authentic_sdo *sdo = (struct sc_authentic_sdo *) ptr; switch (cmd) { case SC_CARDCTL_GET_SERIALNR: return authentic_get_serialnr(card, (struct sc_serial_number *)ptr); case SC_CARDCTL_AUTHENTIC_SDO_CREATE: sc_log(ctx, "CARDCTL SDO_CREATE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id); return authentic_manage_sdo(card, (struct sc_authentic_sdo *) ptr, cmd); case SC_CARDCTL_AUTHENTIC_SDO_DELETE: sc_log(ctx, "CARDCTL SDO_DELETE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id); return authentic_manage_sdo(card, (struct sc_authentic_sdo *) ptr, cmd); case SC_CARDCTL_AUTHENTIC_SDO_STORE: sc_log(ctx, "CARDCTL SDO_STORE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id); return authentic_manage_sdo(card, (struct sc_authentic_sdo *) ptr, cmd); case SC_CARDCTL_AUTHENTIC_SDO_GENERATE: sc_log(ctx, "CARDCTL SDO_GENERATE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id); return authentic_manage_sdo_generate(card, (struct sc_authentic_sdo *) ptr); } return SC_ERROR_NOT_SUPPORTED; } static int authentic_set_security_env(struct sc_card *card, const struct sc_security_env *env, int se_num) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char cse_crt_dst[] = { 0x80, 0x01, AUTHENTIC_ALGORITHM_RSA_PKCS1, 0x83, 0x01, env->key_ref[0] & ~AUTHENTIC_OBJECT_REF_FLAG_LOCAL, }; unsigned char cse_crt_ct[] = { 0x80, 0x01, AUTHENTIC_ALGORITHM_RSA_PKCS1, 0x83, 0x01, env->key_ref[0] & ~AUTHENTIC_OBJECT_REF_FLAG_LOCAL, }; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "set SE#%i(op:0x%X,algo:0x%X,algo_ref:0x%X,flags:0x%X), key_ref:0x%X", se_num, env->operation, env->algorithm, env->algorithm_ref, env->algorithm_flags, env->key_ref[0]); switch (env->operation) { case SC_SEC_OPERATION_SIGN: sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, AUTHENTIC_TAG_CRT_DST); apdu.data = cse_crt_dst; apdu.datalen = sizeof(cse_crt_dst); apdu.lc = sizeof(cse_crt_dst); break; case SC_SEC_OPERATION_DECIPHER: sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, AUTHENTIC_TAG_CRT_CT); apdu.data = cse_crt_ct; apdu.datalen = sizeof(cse_crt_ct); apdu.lc = sizeof(cse_crt_ct); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "MSE restore error"); LOG_FUNC_RETURN(ctx, rv); } static int authentic_decipher(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u", in_len, out_len); if (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.flags |= SC_APDU_FLAGS_CHAINING; apdu.data = in; apdu.datalen = in_len; apdu.lc = in_len; apdu.resp = resp; apdu.resplen = sizeof(resp); apdu.le = 256; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Card returned error"); if (out_len > apdu.resplen) out_len = apdu.resplen; memcpy(out, apdu.resp, out_len); rv = out_len; LOG_FUNC_RETURN(ctx, rv); } static int authentic_finish(struct sc_card *card) { struct sc_context *ctx = card->ctx; LOG_FUNC_CALLED(ctx); #ifdef ENABLE_SM if (card->sm_ctx.ops.close) card->sm_ctx.ops.close(card); #endif if (card->drv_data) free(card->drv_data); card->drv_data = NULL; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int authentic_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0 && card->type == SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2) { r = authentic_select_aid(card, aid_AuthentIC_3_2, sizeof(aid_AuthentIC_3_2), NULL, NULL); } LOG_FUNC_RETURN(card->ctx, r); } /* SM related */ #ifdef ENABLE_SM static int authentic_sm_acl_init (struct sc_card *card, struct sm_info *sm_info, int cmd, unsigned char *resp, size_t *resp_len) { struct sc_context *ctx; struct sm_type_params_gp *params_gp; struct sc_remote_data rdata; int rv; if (!card || !sm_info || !resp || !resp_len) return SC_ERROR_INVALID_ARGUMENTS; ctx = card->ctx; params_gp = &sm_info->session.gp.params; if (!card->sm_ctx.module.ops.initialize || !card->sm_ctx.module.ops.get_apdus) LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); if (*resp_len < 28) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sm_info->cmd = cmd; sm_info->sm_type = SM_TYPE_GP_SCP01; sm_info->card_type = card->type; params_gp->index = 0; /* logical channel */ params_gp->version = 1; params_gp->level = 3; /* Only supported SM level 'ENC & MAC' */ sm_info->serialnr = card->serialnr; sc_remote_data_init(&rdata); rv = card->sm_ctx.module.ops.initialize(ctx, sm_info, &rdata); LOG_TEST_RET(ctx, rv, "SM: INITIALIZE failed"); if (!rdata.length) LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL); rv = sc_transmit_apdu(card, &rdata.data->apdu); LOG_TEST_RET(ctx, rv, "transmit APDU failed"); rv = sc_check_sw(card, rdata.data->apdu.sw1, rdata.data->apdu.sw2); LOG_TEST_RET(ctx, rv, "Card returned error"); if (rdata.data->apdu.resplen != 28 || *resp_len < 28) LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL); memcpy(resp, rdata.data->apdu.resp, 28); *resp_len = 28; rdata.free(&rdata); LOG_FUNC_RETURN(ctx, rv); } static int authentic_sm_execute (struct sc_card *card, struct sm_info *sm_info, unsigned char *data, int data_len, unsigned char *out, size_t len) { struct sc_context *ctx = card->ctx; struct sc_remote_data rdata; int rv, ii; if (!card->sm_ctx.module.ops.get_apdus) LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); sc_remote_data_init(&rdata); rv = card->sm_ctx.module.ops.get_apdus(ctx, sm_info, data, data_len, &rdata); LOG_TEST_RET(ctx, rv, "SM: GET_APDUS failed"); if (!rdata.length) LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL); sc_log(ctx, "GET_APDUS: rv %i; rdata length %i", rv, rdata.length); for (ii=0; ii < rdata.length; ii++) { struct sc_apdu *apdu = &((rdata.data + ii)->apdu); if (!apdu->ins) break; rv = sc_transmit_apdu(card, apdu); if (rv < 0) break; rv = sc_check_sw(card, apdu->sw1, apdu->sw2); if (rv < 0) break; } rdata.free(&rdata); LOG_FUNC_RETURN(ctx, rv); } static int authentic_sm_open(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned char init_data[SC_MAX_APDU_BUFFER_SIZE]; size_t init_data_len = sizeof(init_data); int rv; LOG_FUNC_CALLED(ctx); memset(&card->sm_ctx.info, 0, sizeof(card->sm_ctx.info)); memcpy(card->sm_ctx.info.config_section, card->sm_ctx.config_section, sizeof(card->sm_ctx.info.config_section)); sc_log(ctx, "SM context config '%s'; SM mode 0x%X", card->sm_ctx.info.config_section, card->sm_ctx.sm_mode); if (card->sm_ctx.sm_mode == SM_MODE_TRANSMIT && card->max_send_size == 0) card->max_send_size = 239; rv = authentic_sm_acl_init (card, &card->sm_ctx.info, SM_CMD_INITIALIZE, init_data, &init_data_len); LOG_TEST_RET(ctx, rv, "authentIC: cannot open SM"); rv = authentic_sm_execute (card, &card->sm_ctx.info, init_data, init_data_len, NULL, 0); LOG_TEST_RET(ctx, rv, "SM: execute failed"); card->sm_ctx.info.cmd = SM_CMD_APDU_TRANSMIT; LOG_FUNC_RETURN(ctx, rv); } static int authentic_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; LOG_FUNC_CALLED(ctx); if (!sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); if (!(*sm_apdu)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (plain) { if (plain->resplen < (*sm_apdu)->resplen) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Insufficient plain APDU response size"); memcpy(plain->resp, (*sm_apdu)->resp, (*sm_apdu)->resplen); plain->resplen = (*sm_apdu)->resplen; plain->sw1 = (*sm_apdu)->sw1; plain->sw2 = (*sm_apdu)->sw2; } if ((*sm_apdu)->data) free((unsigned char *) (*sm_apdu)->data); if ((*sm_apdu)->resp) free((unsigned char *) (*sm_apdu)->resp); free(*sm_apdu); *sm_apdu = NULL; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int authentic_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu) { struct sc_context *ctx = card->ctx; struct sc_apdu *apdu = NULL; int rv = 0; LOG_FUNC_CALLED(ctx); if (!plain || !sm_apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_log(ctx, "called; CLA:%X, INS:%X, P1:%X, P2:%X, data(%"SC_FORMAT_LEN_SIZE_T"u) %p", plain->cla, plain->ins, plain->p1, plain->p2, plain->datalen, plain->data); *sm_apdu = NULL; if ((plain->cla & 0x04) || (plain->cla==0x00 && plain->ins==0x22) || (plain->cla==0x00 && plain->ins==0x2A) || (plain->cla==0x00 && plain->ins==0x84) || (plain->cla==0x00 && plain->ins==0x88) || (plain->cla==0x00 && plain->ins==0xA4) || (plain->cla==0x00 && plain->ins==0xC0) || (plain->cla==0x00 && plain->ins==0xCA) || (plain->cla==0x80 && plain->ins==0x50) ) { sc_log(ctx, "SM wrap is not applied for this APDU"); LOG_FUNC_RETURN(ctx, SC_ERROR_SM_NOT_APPLIED); } if (card->sm_ctx.sm_mode != SM_MODE_TRANSMIT) LOG_FUNC_RETURN(ctx, SC_ERROR_SM_NOT_INITIALIZED); if (!card->sm_ctx.module.ops.get_apdus) LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); apdu = calloc(1, sizeof(struct sc_apdu)); if (!apdu) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); memcpy((void *)apdu, (void *)plain, sizeof(struct sc_apdu)); apdu->data = calloc (1, plain->datalen + 24); if (!apdu->data) { free(apdu); LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); } if (plain->data && plain->datalen) memcpy((unsigned char *) apdu->data, plain->data, plain->datalen); apdu->resp = calloc (1, plain->resplen + 32); if (!apdu->resp) { free(apdu); LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); } card->sm_ctx.info.cmd = SM_CMD_APDU_TRANSMIT; card->sm_ctx.info.cmd_data = (void *)apdu; rv = card->sm_ctx.module.ops.get_apdus(ctx, &card->sm_ctx.info, NULL, 0, NULL); if (rv < 0) { free(apdu->resp); free(apdu); } LOG_TEST_RET(ctx, rv, "SM: GET_APDUS failed"); *sm_apdu = apdu; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } #endif static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (!iso_ops) iso_ops = iso_drv->ops; authentic_ops = *iso_ops; authentic_ops.match_card = authentic_match_card; authentic_ops.init = authentic_init; authentic_ops.finish = authentic_finish; authentic_ops.read_binary = authentic_read_binary; authentic_ops.write_binary = authentic_write_binary; authentic_ops.update_binary = authentic_update_binary; authentic_ops.erase_binary = authentic_erase_binary; /* authentic_ops.resize_file = authentic_resize_file; */ authentic_ops.select_file = authentic_select_file; /* get_response: Untested */ authentic_ops.get_challenge = authentic_get_challenge; authentic_ops.set_security_env = authentic_set_security_env; /* decipher: Untested */ authentic_ops.decipher = authentic_decipher; /* authentic_ops.compute_signature = authentic_compute_signature; */ authentic_ops.create_file = authentic_create_file; authentic_ops.delete_file = authentic_delete_file; authentic_ops.card_ctl = authentic_card_ctl; authentic_ops.process_fci = authentic_process_fci; authentic_ops.pin_cmd = authentic_pin_cmd; authentic_ops.card_reader_lock_obtained = authentic_card_reader_lock_obtained; return &authentic_drv; } struct sc_card_driver * sc_get_authentic_driver(void) { return sc_get_driver(); } #endif /* ENABLE_OPENSSL */
./CrossVul/dataset_final_sorted/CWE-125/c/good_351_2
crossvul-cpp_data_bad_1854_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS U U N N % % SS U U NN N % % SSS U U N N N % % SS U U N NN % % SSSSS UUU N N % % % % % % Read/Write Sun Rasterfile Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Forward declarations. */ static MagickBooleanType WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S U N % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSUN() returns MagickTrue if the image format type, identified by the % magick string, is SUN. % % The format of the IsSUN method is: % % MagickBooleanType IsSUN(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsSUN(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\131\246\152\225",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded pixel % packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, % const size_t length,unsigned char *pixels) % % A description of each parameter follows: % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % % o length: An integer value that is the total number of bytes of the % source image (as just read by ReadBlob) % % o pixels: The address of a byte (8 bits) array of pixel data created by % the uncompression process. The number of bytes in this array % must be at least equal to the number columns times the number of rows % of the source pixels. % */ static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels, const size_t length,unsigned char *pixels,size_t maxpixels) { register const unsigned char *l, *p; register unsigned char *q; ssize_t count; unsigned char byte; (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(compressed_pixels != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); p=compressed_pixels; q=pixels; l=q+maxpixels; while (((size_t) (p-compressed_pixels) < length) && (q < l)) { byte=(*p++); if (byte != 128U) *q++=byte; else { /* Runlength-encoded packet: <count><byte> */ count=(ssize_t) (*p++); if (count > 0) byte=(*p++); while ((count >= 0) && (q < l)) { *q++=byte; count--; } } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSUNImage() reads a SUN image file and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer to % the new image. % % The format of the ReadSUNImage method is: % % Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) && ((number_pixels*((sun_info.depth+7)/8)) > sun_info.length)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); sun_pixels=sun_data; bytes_per_line=0; if (sun_info.type == RT_ENCODED) { size_t height; /* Read run-length encoded raster pixels. */ height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); } /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSUNImage() adds attributes for the SUN image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterSUNImage method is: % % size_t RegisterSUNImage(void) % */ ModuleExport size_t RegisterSUNImage(void) { MagickInfo *entry; entry=SetMagickInfo("RAS"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->magick=(IsImageFormatHandler *) IsSUN; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("SUN"); entry->decoder=(DecodeImageHandler *) ReadSUNImage; entry->encoder=(EncodeImageHandler *) WriteSUNImage; entry->description=ConstantString("SUN Rasterfile"); entry->module=ConstantString("SUN"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSUNImage() removes format registrations made by the % SUN module from the list of supported formats. % % The format of the UnregisterSUNImage method is: % % UnregisterSUNImage(void) % */ ModuleExport void UnregisterSUNImage(void) { (void) UnregisterMagickInfo("RAS"); (void) UnregisterMagickInfo("SUN"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S U N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSUNImage() writes an image in the SUN rasterfile format. % % The format of the WriteSUNImage method is: % % MagickBooleanType WriteSUNImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; register const Quantum *p; register ssize_t i, x; ssize_t y; SUNInfo sun_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { /* Initialize SUN raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); sun_info.magic=0x59a66a95; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); sun_info.width=(unsigned int) image->columns; sun_info.height=(unsigned int) image->rows; sun_info.type=(unsigned int) (image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD); sun_info.maptype=RMT_NONE; sun_info.maplength=0; number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (size_t) (4*number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (image->storage_class == DirectClass) { /* Full color SUN raster. */ sun_info.depth=(unsigned int) image->alpha_trait != UndefinedPixelTrait ? 32U : 24U; sun_info.length=(unsigned int) ((image->alpha_trait != UndefinedPixelTrait ? 4 : 3)*number_pixels); sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows : 0; } else if (IsImageMonochrome(image,exception) != MagickFalse) { /* Monochrome SUN raster. */ sun_info.depth=1; sun_info.length=(unsigned int) (((image->columns+7) >> 3)* image->rows); sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2 ? image->rows : 0); } else { /* Colormapped SUN raster. */ sun_info.depth=8; sun_info.length=(unsigned int) number_pixels; sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows : 0); sun_info.maptype=RMT_EQUAL_RGB; sun_info.maplength=(unsigned int) (3*image->colors); } /* Write SUN header. */ (void) WriteBlobMSBLong(image,sun_info.magic); (void) WriteBlobMSBLong(image,sun_info.width); (void) WriteBlobMSBLong(image,sun_info.height); (void) WriteBlobMSBLong(image,sun_info.depth); (void) WriteBlobMSBLong(image,sun_info.length); (void) WriteBlobMSBLong(image,sun_info.type); (void) WriteBlobMSBLong(image,sun_info.maptype); (void) WriteBlobMSBLong(image,sun_info.maplength); /* Convert MIFF to SUN raster pixels. */ x=0; y=0; if (image->storage_class == DirectClass) { register unsigned char *q; size_t bytes_per_pixel, length; unsigned char *pixels; /* Allocate memory for pixels. */ bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; length=image->columns; pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert DirectClass packet to SUN RGB pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) & 0x01) != 0) *q++='\0'; /* pad scanline */ (void) WriteBlob(image,(size_t) (q-pixels),pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } else if (IsImageMonochrome(image,exception) != MagickFalse) { register unsigned char bit, byte; /* Convert PseudoClass image to a SUN monochrome image. */ (void) SetImageType(image,BilevelType,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { (void) WriteBlobByte(image,byte); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); if ((((image->columns/8)+ (image->columns % 8 ? 1 : 0)) % 2) != 0) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Dump colormap to file. */ for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); /* Convert PseudoClass packet to SUN colormapped pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->columns & 0x01) (void) WriteBlobByte(image,0); /* pad scanline */ if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1854_0
crossvul-cpp_data_good_2718_0
/* * Copyright (c) 2016 Antonin Décimo, Jean-Raphaël Gaglione * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* \summary: Home Networking Control Protocol (HNCP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdlib.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" static void hncp_print_rec(netdissect_options *ndo, const u_char *cp, u_int length, int indent); void hncp_print(netdissect_options *ndo, const u_char *cp, u_int length) { ND_PRINT((ndo, "hncp (%d)", length)); hncp_print_rec(ndo, cp, length, 1); } /* RFC7787 */ #define DNCP_REQUEST_NETWORK_STATE 1 #define DNCP_REQUEST_NODE_STATE 2 #define DNCP_NODE_ENDPOINT 3 #define DNCP_NETWORK_STATE 4 #define DNCP_NODE_STATE 5 #define DNCP_PEER 8 #define DNCP_KEEP_ALIVE_INTERVAL 9 #define DNCP_TRUST_VERDICT 10 /* RFC7788 */ #define HNCP_HNCP_VERSION 32 #define HNCP_EXTERNAL_CONNECTION 33 #define HNCP_DELEGATED_PREFIX 34 #define HNCP_PREFIX_POLICY 43 #define HNCP_DHCPV4_DATA 37 #define HNCP_DHCPV6_DATA 38 #define HNCP_ASSIGNED_PREFIX 35 #define HNCP_NODE_ADDRESS 36 #define HNCP_DNS_DELEGATED_ZONE 39 #define HNCP_DOMAIN_NAME 40 #define HNCP_NODE_NAME 41 #define HNCP_MANAGED_PSK 42 /* See type_mask in hncp_print_rec below */ #define RANGE_DNCP_RESERVED 0x10000 #define RANGE_HNCP_UNASSIGNED 0x10001 #define RANGE_DNCP_PRIVATE_USE 0x10002 #define RANGE_DNCP_FUTURE_USE 0x10003 static const struct tok type_values[] = { { DNCP_REQUEST_NETWORK_STATE, "Request network state" }, { DNCP_REQUEST_NODE_STATE, "Request node state" }, { DNCP_NODE_ENDPOINT, "Node endpoint" }, { DNCP_NETWORK_STATE, "Network state" }, { DNCP_NODE_STATE, "Node state" }, { DNCP_PEER, "Peer" }, { DNCP_KEEP_ALIVE_INTERVAL, "Keep-alive interval" }, { DNCP_TRUST_VERDICT, "Trust-Verdict" }, { HNCP_HNCP_VERSION, "HNCP-Version" }, { HNCP_EXTERNAL_CONNECTION, "External-Connection" }, { HNCP_DELEGATED_PREFIX, "Delegated-Prefix" }, { HNCP_PREFIX_POLICY, "Prefix-Policy" }, { HNCP_DHCPV4_DATA, "DHCPv4-Data" }, { HNCP_DHCPV6_DATA, "DHCPv6-Data" }, { HNCP_ASSIGNED_PREFIX, "Assigned-Prefix" }, { HNCP_NODE_ADDRESS, "Node-Address" }, { HNCP_DNS_DELEGATED_ZONE, "DNS-Delegated-Zone" }, { HNCP_DOMAIN_NAME, "Domain-Name" }, { HNCP_NODE_NAME, "Node-Name" }, { HNCP_MANAGED_PSK, "Managed-PSK" }, { RANGE_DNCP_RESERVED, "Reserved" }, { RANGE_HNCP_UNASSIGNED, "Unassigned" }, { RANGE_DNCP_PRIVATE_USE, "Private use" }, { RANGE_DNCP_FUTURE_USE, "Future use" }, { 0, NULL} }; #define DH4OPT_DNS_SERVERS 6 /* RFC2132 */ #define DH4OPT_NTP_SERVERS 42 /* RFC2132 */ #define DH4OPT_DOMAIN_SEARCH 119 /* RFC3397 */ static const struct tok dh4opt_str[] = { { DH4OPT_DNS_SERVERS, "DNS-server" }, { DH4OPT_NTP_SERVERS, "NTP-server"}, { DH4OPT_DOMAIN_SEARCH, "DNS-search" }, { 0, NULL } }; #define DH6OPT_DNS_SERVERS 23 /* RFC3646 */ #define DH6OPT_DOMAIN_LIST 24 /* RFC3646 */ #define DH6OPT_SNTP_SERVERS 31 /* RFC4075 */ static const struct tok dh6opt_str[] = { { DH6OPT_DNS_SERVERS, "DNS-server" }, { DH6OPT_DOMAIN_LIST, "DNS-search-list" }, { DH6OPT_SNTP_SERVERS, "SNTP-servers" }, { 0, NULL } }; /* * For IPv4-mapped IPv6 addresses, length of the prefix that precedes * the 4 bytes of IPv4 address at the end of the IPv6 address. */ #define IPV4_MAPPED_HEADING_LEN 12 /* * Is an IPv6 address an IPv4-mapped address? */ static inline int is_ipv4_mapped_address(const u_char *addr) { /* The value of the prefix */ static const u_char ipv4_mapped_heading[IPV4_MAPPED_HEADING_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF }; return memcmp(addr, ipv4_mapped_heading, IPV4_MAPPED_HEADING_LEN) == 0; } static const char * format_nid(const u_char *data) { static char buf[4][sizeof("01:01:01:01")]; static int i = 0; i = (i + 1) % 4; snprintf(buf[i], sizeof(buf[i]), "%02x:%02x:%02x:%02x", data[0], data[1], data[2], data[3]); return buf[i]; } static const char * format_256(const u_char *data) { static char buf[4][sizeof("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")]; static int i = 0; i = (i + 1) % 4; snprintf(buf[i], sizeof(buf[i]), "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64, EXTRACT_64BITS(data), EXTRACT_64BITS(data + 8), EXTRACT_64BITS(data + 16), EXTRACT_64BITS(data + 24) ); return buf[i]; } static const char * format_interval(const uint32_t n) { static char buf[4][sizeof("0000000.000s")]; static int i = 0; i = (i + 1) % 4; snprintf(buf[i], sizeof(buf[i]), "%u.%03us", n / 1000, n % 1000); return buf[i]; } static const char * format_ip6addr(netdissect_options *ndo, const u_char *cp) { if (is_ipv4_mapped_address(cp)) return ipaddr_string(ndo, cp + IPV4_MAPPED_HEADING_LEN); else return ip6addr_string(ndo, cp); } static int print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length) { int plenbytes; char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")]; if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 && is_ipv4_mapped_address(&prefix[1])) { struct in_addr addr; u_int plen; plen = prefix[0]-96; if (32 < plen) return -1; max_length -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN) return -3; memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen); plenbytes += 1 + IPV4_MAPPED_HEADING_LEN; } else { plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf)); } ND_PRINT((ndo, "%s", buf)); return plenbytes; } static int print_dns_label(netdissect_options *ndo, const u_char *cp, u_int max_length, int print) { u_int length = 0; while (length < max_length) { u_int lab_length = cp[length++]; if (lab_length == 0) return (int)length; if (length > 1 && print) safeputchar(ndo, '.'); if (length+lab_length > max_length) { if (print) safeputs(ndo, cp+length, max_length-length); break; } if (print) safeputs(ndo, cp+length, lab_length); length += lab_length; } if (print) ND_PRINT((ndo, "[|DNS]")); return -1; } static int dhcpv4_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint8_t type, optlen; i = 0; while (i < length) { tlv = cp + i; type = (uint8_t)tlv[0]; optlen = (uint8_t)tlv[1]; value = tlv + 2; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 2 )); switch (type) { case DH4OPT_DNS_SERVERS: case DH4OPT_NTP_SERVERS: { if (optlen < 4 || optlen % 4 != 0) { return -1; } for (t = 0; t < optlen; t += 4) ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t))); } break; case DH4OPT_DOMAIN_SEARCH: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 2 + optlen; } return 0; } static int dhcpv6_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint16_t type, optlen; i = 0; while (i < length) { if (i + 4 > length) return -1; tlv = cp + i; type = EXTRACT_16BITS(tlv); optlen = EXTRACT_16BITS(tlv + 2); value = tlv + 4; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 4 )); if (i + 4 + optlen > length) return -1; switch (type) { case DH6OPT_DNS_SERVERS: case DH6OPT_SNTP_SERVERS: { if (optlen % 16 != 0) { ND_PRINT((ndo, " %s", istr)); return -1; } for (t = 0; t < optlen; t += 16) ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t))); } break; case DH6OPT_DOMAIN_LIST: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 4 + optlen; } return 0; } /* Determine in-line mode */ static int is_in_line(netdissect_options *ndo, int indent) { return indent - 1 >= ndo->ndo_vflag && ndo->ndo_vflag < 3; } static void print_type_in_line(netdissect_options *ndo, uint32_t type, int count, int indent, int *first_one) { if (count > 0) { if (*first_one) { *first_one = 0; if (indent > 1) { u_int t; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); } else { ND_PRINT((ndo, " ")); } } else { ND_PRINT((ndo, ", ")); } ND_PRINT((ndo, "%s", tok2str(type_values, "Easter Egg", type))); if (count > 1) ND_PRINT((ndo, " (x%d)", count)); } } void hncp_print_rec(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { const int in_line = is_in_line(ndo, indent); int first_one = 1; u_int i, t; uint32_t last_type_mask = 0xffffffffU; int last_type_count = -1; const u_char *tlv, *value; uint16_t type, bodylen; uint32_t type_mask; i = 0; while (i < length) { tlv = cp + i; if (!in_line) { ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); } ND_TCHECK2(*tlv, 4); if (i + 4 > length) goto invalid; type = EXTRACT_16BITS(tlv); bodylen = EXTRACT_16BITS(tlv + 2); value = tlv + 4; ND_TCHECK2(*value, bodylen); if (i + bodylen + 4 > length) goto invalid; type_mask = (type == 0) ? RANGE_DNCP_RESERVED: (44 <= type && type <= 511) ? RANGE_HNCP_UNASSIGNED: (768 <= type && type <= 1023) ? RANGE_DNCP_PRIVATE_USE: RANGE_DNCP_FUTURE_USE; if (type == 6 || type == 7) type_mask = RANGE_DNCP_FUTURE_USE; /* defined types */ { t = 0; while (1) { u_int key = type_values[t++].v; if (key > 0xffff) break; if (key == type) { type_mask = type; break; } } } if (in_line) { if (last_type_mask == type_mask) { last_type_count++; } else { print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one); last_type_mask = type_mask; last_type_count = 1; } goto skip_multiline; } ND_PRINT((ndo,"%s", tok2str(type_values, "Easter Egg (42)", type_mask) )); if (type_mask > 0xffff) ND_PRINT((ndo,": type=%u", type )); ND_PRINT((ndo," (%u)", bodylen + 4 )); switch (type_mask) { case DNCP_REQUEST_NETWORK_STATE: { if (bodylen != 0) ND_PRINT((ndo, " %s", istr)); } break; case DNCP_REQUEST_NODE_STATE: { const char *node_identifier; if (bodylen != 4) { ND_PRINT((ndo, " %s", istr)); break; } node_identifier = format_nid(value); ND_PRINT((ndo, " NID: %s", node_identifier)); } break; case DNCP_NODE_ENDPOINT: { const char *node_identifier; uint32_t endpoint_identifier; if (bodylen != 8) { ND_PRINT((ndo, " %s", istr)); break; } node_identifier = format_nid(value); endpoint_identifier = EXTRACT_32BITS(value + 4); ND_PRINT((ndo, " NID: %s EPID: %08x", node_identifier, endpoint_identifier )); } break; case DNCP_NETWORK_STATE: { uint64_t hash; if (bodylen != 8) { ND_PRINT((ndo, " %s", istr)); break; } hash = EXTRACT_64BITS(value); ND_PRINT((ndo, " hash: %016" PRIx64, hash)); } break; case DNCP_NODE_STATE: { const char *node_identifier, *interval; uint32_t sequence_number; uint64_t hash; if (bodylen < 20) { ND_PRINT((ndo, " %s", istr)); break; } node_identifier = format_nid(value); sequence_number = EXTRACT_32BITS(value + 4); interval = format_interval(EXTRACT_32BITS(value + 8)); hash = EXTRACT_64BITS(value + 12); ND_PRINT((ndo, " NID: %s seqno: %u %s hash: %016" PRIx64, node_identifier, sequence_number, interval, hash )); hncp_print_rec(ndo, value+20, bodylen-20, indent+1); } break; case DNCP_PEER: { const char *peer_node_identifier; uint32_t peer_endpoint_identifier, endpoint_identifier; if (bodylen != 12) { ND_PRINT((ndo, " %s", istr)); break; } peer_node_identifier = format_nid(value); peer_endpoint_identifier = EXTRACT_32BITS(value + 4); endpoint_identifier = EXTRACT_32BITS(value + 8); ND_PRINT((ndo, " Peer-NID: %s Peer-EPID: %08x Local-EPID: %08x", peer_node_identifier, peer_endpoint_identifier, endpoint_identifier )); } break; case DNCP_KEEP_ALIVE_INTERVAL: { uint32_t endpoint_identifier; const char *interval; if (bodylen < 8) { ND_PRINT((ndo, " %s", istr)); break; } endpoint_identifier = EXTRACT_32BITS(value); interval = format_interval(EXTRACT_32BITS(value + 4)); ND_PRINT((ndo, " EPID: %08x Interval: %s", endpoint_identifier, interval )); } break; case DNCP_TRUST_VERDICT: { if (bodylen <= 36) { ND_PRINT((ndo, " %s", istr)); break; } ND_PRINT((ndo, " Verdict: %u Fingerprint: %s Common Name: ", *value, format_256(value + 4))); safeputs(ndo, value + 36, bodylen - 36); } break; case HNCP_HNCP_VERSION: { uint16_t capabilities; uint8_t M, P, H, L; if (bodylen < 5) { ND_PRINT((ndo, " %s", istr)); break; } capabilities = EXTRACT_16BITS(value + 2); M = (uint8_t)((capabilities >> 12) & 0xf); P = (uint8_t)((capabilities >> 8) & 0xf); H = (uint8_t)((capabilities >> 4) & 0xf); L = (uint8_t)(capabilities & 0xf); ND_PRINT((ndo, " M: %u P: %u H: %u L: %u User-agent: ", M, P, H, L )); safeputs(ndo, value + 4, bodylen - 4); } break; case HNCP_EXTERNAL_CONNECTION: { /* Container TLV */ hncp_print_rec(ndo, value, bodylen, indent+1); } break; case HNCP_DELEGATED_PREFIX: { int l; if (bodylen < 9 || bodylen < 9 + (value[8] + 7) / 8) { ND_PRINT((ndo, " %s", istr)); break; } ND_PRINT((ndo, " VLSO: %s PLSO: %s Prefix: ", format_interval(EXTRACT_32BITS(value)), format_interval(EXTRACT_32BITS(value + 4)) )); l = print_prefix(ndo, value + 8, bodylen - 8); if (l == -1) { ND_PRINT((ndo, "(length is invalid)")); break; } if (l < 0) { /* * We've already checked that we've captured the * entire TLV, based on its length, so this will * either be -1, meaning "the prefix length is * greater than the longest possible address of * that type" (i.e., > 32 for IPv4 or > 128 for * IPv6", or -3, meaning "the prefix runs past * the end of the TLV". */ ND_PRINT((ndo, " %s", istr)); break; } l += 8 + (-l & 3); if (bodylen >= l) hncp_print_rec(ndo, value + l, bodylen - l, indent+1); } break; case HNCP_PREFIX_POLICY: { uint8_t policy; int l; if (bodylen < 1) { ND_PRINT((ndo, " %s", istr)); break; } policy = value[0]; ND_PRINT((ndo, " type: ")); if (policy == 0) { if (bodylen != 1) { ND_PRINT((ndo, " %s", istr)); break; } ND_PRINT((ndo, "Internet connectivity")); } else if (policy >= 1 && policy <= 128) { ND_PRINT((ndo, "Dest-Prefix: ")); l = print_prefix(ndo, value, bodylen); if (l == -1) { ND_PRINT((ndo, "(length is invalid)")); break; } if (l < 0) { /* * We've already checked that we've captured the * entire TLV, based on its length, so this will * either be -1, meaning "the prefix length is * greater than the longest possible address of * that type" (i.e., > 32 for IPv4 or > 128 for * IPv6", or -3, meaning "the prefix runs past * the end of the TLV". */ ND_PRINT((ndo, " %s", istr)); break; } } else if (policy == 129) { ND_PRINT((ndo, "DNS domain: ")); print_dns_label(ndo, value+1, bodylen-1, 1); } else if (policy == 130) { ND_PRINT((ndo, "Opaque UTF-8: ")); safeputs(ndo, value + 1, bodylen - 1); } else if (policy == 131) { if (bodylen != 1) { ND_PRINT((ndo, " %s", istr)); break; } ND_PRINT((ndo, "Restrictive assignment")); } else if (policy >= 132) { ND_PRINT((ndo, "Unknown (%u)", policy)); /* Reserved for future additions */ } } break; case HNCP_DHCPV4_DATA: { if (bodylen == 0) { ND_PRINT((ndo, " %s", istr)); break; } if (dhcpv4_print(ndo, value, bodylen, indent+1) != 0) goto invalid; } break; case HNCP_DHCPV6_DATA: { if (bodylen == 0) { ND_PRINT((ndo, " %s", istr)); break; } if (dhcpv6_print(ndo, value, bodylen, indent+1) != 0) { ND_PRINT((ndo, " %s", istr)); break; } } break; case HNCP_ASSIGNED_PREFIX: { uint8_t prty; int l; if (bodylen < 6 || bodylen < 6 + (value[5] + 7) / 8) { ND_PRINT((ndo, " %s", istr)); break; } prty = (uint8_t)(value[4] & 0xf); ND_PRINT((ndo, " EPID: %08x Prty: %u", EXTRACT_32BITS(value), prty )); ND_PRINT((ndo, " Prefix: ")); if ((l = print_prefix(ndo, value + 5, bodylen - 5)) < 0) { ND_PRINT((ndo, " %s", istr)); break; } l += 5; l += -l & 3; if (bodylen >= l) hncp_print_rec(ndo, value + l, bodylen - l, indent+1); } break; case HNCP_NODE_ADDRESS: { uint32_t endpoint_identifier; const char *ip_address; if (bodylen < 20) { ND_PRINT((ndo, " %s", istr)); break; } endpoint_identifier = EXTRACT_32BITS(value); ip_address = format_ip6addr(ndo, value + 4); ND_PRINT((ndo, " EPID: %08x IP Address: %s", endpoint_identifier, ip_address )); hncp_print_rec(ndo, value + 20, bodylen - 20, indent+1); } break; case HNCP_DNS_DELEGATED_ZONE: { const char *ip_address; int len; if (bodylen < 17) { ND_PRINT((ndo, " %s", istr)); break; } ip_address = format_ip6addr(ndo, value); ND_PRINT((ndo, " IP-Address: %s %c%c%c ", ip_address, (value[16] & 4) ? 'l' : '-', (value[16] & 2) ? 'b' : '-', (value[16] & 1) ? 's' : '-' )); len = print_dns_label(ndo, value+17, bodylen-17, 1); if (len < 0) { ND_PRINT((ndo, " %s", istr)); break; } len += 17; len += -len & 3; if (bodylen >= len) hncp_print_rec(ndo, value+len, bodylen-len, indent+1); } break; case HNCP_DOMAIN_NAME: { if (bodylen == 0) { ND_PRINT((ndo, " %s", istr)); break; } ND_PRINT((ndo, " Domain: ")); print_dns_label(ndo, value, bodylen, 1); } break; case HNCP_NODE_NAME: { u_int l; if (bodylen < 17) { ND_PRINT((ndo, " %s", istr)); break; } l = value[16]; if (bodylen < 17 + l) { ND_PRINT((ndo, " %s", istr)); break; } ND_PRINT((ndo, " IP-Address: %s Name: ", format_ip6addr(ndo, value) )); if (l < 64) { safeputchar(ndo, '"'); safeputs(ndo, value + 17, l); safeputchar(ndo, '"'); } else { ND_PRINT((ndo, "%s", istr)); } l += 17; l += -l & 3; if (bodylen >= l) hncp_print_rec(ndo, value + l, bodylen - l, indent+1); } break; case HNCP_MANAGED_PSK: { if (bodylen < 32) { ND_PRINT((ndo, " %s", istr)); break; } ND_PRINT((ndo, " PSK: %s", format_256(value))); hncp_print_rec(ndo, value + 32, bodylen - 32, indent+1); } break; case RANGE_DNCP_RESERVED: case RANGE_HNCP_UNASSIGNED: case RANGE_DNCP_PRIVATE_USE: case RANGE_DNCP_FUTURE_USE: break; } skip_multiline: i += 4 + bodylen + (-bodylen & 3); } print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one); return; trunc: ND_PRINT((ndo, "%s", "[|hncp]")); return; invalid: ND_PRINT((ndo, "%s", istr)); return; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2718_0
crossvul-cpp_data_bad_628_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // dsdiff.c // This module is a helper to the WavPack command-line programs to support DFF files. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #ifdef _WIN32 #define strdup(x) _strdup(x) #endif #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; #pragma pack(push,2) typedef struct { char ckID [4]; int64_t ckDataSize; } DFFChunkHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char formType [4]; } DFFFileHeader; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t version; } DFFVersionChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t sampleRate; } DFFSampleRateChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint16_t numChannels; } DFFChannelsHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char compressionType [4]; } DFFCompressionHeader; #pragma pack(pop) #define DFFChunkHeaderFormat "4D" #define DFFFileHeaderFormat "4D4" #define DFFVersionChunkFormat "4DL" #define DFFSampleRateChunkFormat "4DL" #define DFFChannelsHeaderFormat "4DS" #define DFFCompressionHeaderFormat "4D4" int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteDsdiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { uint32_t chan_mask = WavpackGetChannelMask (wpc); int num_channels = WavpackGetNumChannels (wpc); DFFFileHeader file_header, prop_header; DFFChunkHeader data_header; DFFVersionChunk ver_chunk; DFFSampleRateChunk fs_chunk; DFFChannelsHeader chan_header; DFFCompressionHeader cmpr_header; char *cmpr_name = "\016not compressed", *chan_ids; int64_t file_size, prop_chunk_size, data_size; int cmpr_name_size, chan_ids_size; uint32_t bcount; if (debug_logging_mode) error_line ("WriteDsdiffHeader (), total samples = %lld, qmode = 0x%02x\n", (long long) total_samples, qmode); cmpr_name_size = (strlen (cmpr_name) + 1) & ~1; chan_ids_size = num_channels * 4; chan_ids = malloc (chan_ids_size); if (chan_ids) { uint32_t scan_mask = 0x1; char *cptr = chan_ids; int ci, uci = 0; for (ci = 0; ci < num_channels; ++ci) { while (scan_mask && !(scan_mask & chan_mask)) scan_mask <<= 1; if (scan_mask & 0x1) memcpy (cptr, num_channels <= 2 ? "SLFT" : "MLFT", 4); else if (scan_mask & 0x2) memcpy (cptr, num_channels <= 2 ? "SRGT" : "MRGT", 4); else if (scan_mask & 0x4) memcpy (cptr, "C ", 4); else if (scan_mask & 0x8) memcpy (cptr, "LFE ", 4); else if (scan_mask & 0x10) memcpy (cptr, "LS ", 4); else if (scan_mask & 0x20) memcpy (cptr, "RS ", 4); else { cptr [0] = 'C'; cptr [1] = (uci / 100) + '0'; cptr [2] = ((uci % 100) / 10) + '0'; cptr [3] = (uci % 10) + '0'; uci++; } scan_mask <<= 1; cptr += 4; } } else { error_line ("can't allocate memory!"); return FALSE; } data_size = total_samples * num_channels; prop_chunk_size = sizeof (prop_header) + sizeof (fs_chunk) + sizeof (chan_header) + chan_ids_size + sizeof (cmpr_header) + cmpr_name_size; file_size = sizeof (file_header) + sizeof (ver_chunk) + prop_chunk_size + sizeof (data_header) + ((data_size + 1) & ~(int64_t)1); memcpy (file_header.ckID, "FRM8", 4); file_header.ckDataSize = file_size - 12; memcpy (file_header.formType, "DSD ", 4); memcpy (prop_header.ckID, "PROP", 4); prop_header.ckDataSize = prop_chunk_size - 12; memcpy (prop_header.formType, "SND ", 4); memcpy (ver_chunk.ckID, "FVER", 4); ver_chunk.ckDataSize = sizeof (ver_chunk) - 12; ver_chunk.version = 0x01050000; memcpy (fs_chunk.ckID, "FS ", 4); fs_chunk.ckDataSize = sizeof (fs_chunk) - 12; fs_chunk.sampleRate = WavpackGetSampleRate (wpc) * 8; memcpy (chan_header.ckID, "CHNL", 4); chan_header.ckDataSize = sizeof (chan_header) + chan_ids_size - 12; chan_header.numChannels = num_channels; memcpy (cmpr_header.ckID, "CMPR", 4); cmpr_header.ckDataSize = sizeof (cmpr_header) + cmpr_name_size - 12; memcpy (cmpr_header.compressionType, "DSD ", 4); memcpy (data_header.ckID, "DSD ", 4); data_header.ckDataSize = data_size; WavpackNativeToBigEndian (&file_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&ver_chunk, DFFVersionChunkFormat); WavpackNativeToBigEndian (&prop_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&fs_chunk, DFFSampleRateChunkFormat); WavpackNativeToBigEndian (&chan_header, DFFChannelsHeaderFormat); WavpackNativeToBigEndian (&cmpr_header, DFFCompressionHeaderFormat); WavpackNativeToBigEndian (&data_header, DFFChunkHeaderFormat); if (!DoWriteFile (outfile, &file_header, sizeof (file_header), &bcount) || bcount != sizeof (file_header) || !DoWriteFile (outfile, &ver_chunk, sizeof (ver_chunk), &bcount) || bcount != sizeof (ver_chunk) || !DoWriteFile (outfile, &prop_header, sizeof (prop_header), &bcount) || bcount != sizeof (prop_header) || !DoWriteFile (outfile, &fs_chunk, sizeof (fs_chunk), &bcount) || bcount != sizeof (fs_chunk) || !DoWriteFile (outfile, &chan_header, sizeof (chan_header), &bcount) || bcount != sizeof (chan_header) || !DoWriteFile (outfile, chan_ids, chan_ids_size, &bcount) || bcount != chan_ids_size || !DoWriteFile (outfile, &cmpr_header, sizeof (cmpr_header), &bcount) || bcount != sizeof (cmpr_header) || !DoWriteFile (outfile, cmpr_name, cmpr_name_size, &bcount) || bcount != cmpr_name_size || !DoWriteFile (outfile, &data_header, sizeof (data_header), &bcount) || bcount != sizeof (data_header)) { error_line ("can't write .DSF data, disk probably full!"); free (chan_ids); return FALSE; } free (chan_ids); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_628_0
crossvul-cpp_data_bad_675_0
/** * WinPR: Windows Portable Runtime * NTLM Security Package (Message) * * Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ntlm.h" #include "../sspi.h" #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/stream.h> #include <winpr/sysinfo.h> #include "ntlm_compute.h" #include "ntlm_message.h" #include "../log.h" #define TAG WINPR_TAG("sspi.NTLM") static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' }; static const char* const NTLM_NEGOTIATE_STRINGS[] = { "NTLMSSP_NEGOTIATE_56", "NTLMSSP_NEGOTIATE_KEY_EXCH", "NTLMSSP_NEGOTIATE_128", "NTLMSSP_RESERVED1", "NTLMSSP_RESERVED2", "NTLMSSP_RESERVED3", "NTLMSSP_NEGOTIATE_VERSION", "NTLMSSP_RESERVED4", "NTLMSSP_NEGOTIATE_TARGET_INFO", "NTLMSSP_REQUEST_NON_NT_SESSION_KEY", "NTLMSSP_RESERVED5", "NTLMSSP_NEGOTIATE_IDENTIFY", "NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY", "NTLMSSP_RESERVED6", "NTLMSSP_TARGET_TYPE_SERVER", "NTLMSSP_TARGET_TYPE_DOMAIN", "NTLMSSP_NEGOTIATE_ALWAYS_SIGN", "NTLMSSP_RESERVED7", "NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED", "NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED", "NTLMSSP_NEGOTIATE_ANONYMOUS", "NTLMSSP_RESERVED8", "NTLMSSP_NEGOTIATE_NTLM", "NTLMSSP_RESERVED9", "NTLMSSP_NEGOTIATE_LM_KEY", "NTLMSSP_NEGOTIATE_DATAGRAM", "NTLMSSP_NEGOTIATE_SEAL", "NTLMSSP_NEGOTIATE_SIGN", "NTLMSSP_RESERVED10", "NTLMSSP_REQUEST_TARGET", "NTLMSSP_NEGOTIATE_OEM", "NTLMSSP_NEGOTIATE_UNICODE" }; void ntlm_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, "\t%s (%d),", str, (31 - i)); } } } int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { if (Stream_GetRemainingLength(s) < 12) return -1; Stream_Read(s, header->Signature, 8); Stream_Read_UINT32(s, header->MessageType); if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0) return -1; return 1; } void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); } void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; } int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; } void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->MaxLen < 1) fields->MaxLen = fields->Len; Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ } int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { Stream_SetPosition(s, fields->BufferOffset); Stream_Write(s, fields->Buffer, fields->Len); } } void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } } void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); } SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } context->NegotiateFlags = message->NegotiateFlags; /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %"PRIu32")", context->NegotiateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, context->NegotiateMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; NTLM_NEGOTIATE_MESSAGE* message; message = &context->NEGOTIATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*) message, MESSAGE_TYPE_NEGOTIATE); if (context->NTLMv2) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM; } message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; if (context->confidentiality) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; if (context->SendVersionInfo) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_get_version_info(&(message->Version)); context->NegotiateFlags = message->NegotiateFlags; /* Message Header (12 bytes) */ ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*) message); Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ /* DomainNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->DomainName)); /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ /* WorkstationFields (8 bytes) */ ntlm_write_message_fields(s, &(message->Workstation)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); context->NegotiateMessage.BufferType = buffer->BufferType; #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); #endif context->state = NTLM_STATE_CHALLENGE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; int length; PBYTE StartOffset; PBYTE PayloadOffset; NTLM_AV_PAIR* AvTimestamp; NTLM_CHALLENGE_MESSAGE* message; ntlm_generate_client_challenge(context); message = &context->CHALLENGE_MESSAGE; ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; StartOffset = Stream_Pointer(s); if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_CHALLENGE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->TargetName)) < 0) /* TargetNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (Stream_GetRemainingLength(s) < 4) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ context->NegotiateFlags = message->NegotiateFlags; if (Stream_GetRemainingLength(s) < 8) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ CopyMemory(context->ServerChallenge, message->ServerChallenge, 8); if (Stream_GetRemainingLength(s) < 8) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ if (ntlm_read_message_fields(s, &(message->TargetInfo)) < 0) /* TargetInfoFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } /* Payload (variable) */ PayloadOffset = Stream_Pointer(s); if (message->TargetName.Len > 0) { if (ntlm_read_message_fields_buffer(s, &(message->TargetName)) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } } if (message->TargetInfo.Len > 0) { if (ntlm_read_message_fields_buffer(s, &(message->TargetInfo)) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer; context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len; AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*) message->TargetInfo.Buffer, MsvAvTimestamp); if (AvTimestamp) { if (context->NTLMv2) context->UseMIC = TRUE; CopyMemory(context->ChallengeTimestamp, ntlm_av_pair_get_value_pointer(AvTimestamp), 8); } } length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len; if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->ChallengeMessage.pvBuffer, StartOffset, length); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer, context->ChallengeMessage.cbBuffer); ntlm_print_negotiate_flags(context->NegotiateFlags); if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->TargetName), "TargetName"); ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo"); if (context->ChallengeTargetInfo.cbBuffer > 0) { WLog_DBG(TAG, "ChallengeTargetInfo (%"PRIu32"):", context->ChallengeTargetInfo.cbBuffer); ntlm_print_av_pair_list(context->ChallengeTargetInfo.pvBuffer); } #endif /* AV_PAIRs */ if (context->NTLMv2) { if (ntlm_construct_authenticate_target_info(context) < 0) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } sspi_SecBufferFree(&context->ChallengeTargetInfo); context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer; context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer; } ntlm_generate_timestamp(context); /* Timestamp */ if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */ ntlm_generate_random_session_key(context); /* RandomSessionKey */ ntlm_generate_exported_session_key(context); /* ExportedSessionKey */ ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */ /* Generate signing keys */ ntlm_generate_client_signing_key(context); ntlm_generate_server_signing_key(context); /* Generate sealing keys */ ntlm_generate_client_sealing_key(context); ntlm_generate_server_sealing_key(context); /* Initialize RC4 seal state using client sealing key */ ntlm_init_rc4_seal_states(context); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "ClientChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8); WLog_DBG(TAG, "ServerChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8); WLog_DBG(TAG, "SessionBaseKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16); WLog_DBG(TAG, "KeyExchangeKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16); WLog_DBG(TAG, "ExportedSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16); WLog_DBG(TAG, "RandomSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16); WLog_DBG(TAG, "ClientSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16); WLog_DBG(TAG, "ClientSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16); WLog_DBG(TAG, "ServerSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16); WLog_DBG(TAG, "ServerSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16); WLog_DBG(TAG, "Timestamp"); winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8); #endif context->state = NTLM_STATE_AUTHENTICATE; ntlm_free_message_fields_buffer(&(message->TargetName)); Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 PayloadOffset; NTLM_CHALLENGE_MESSAGE* message; message = &context->CHALLENGE_MESSAGE; ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; ntlm_get_version_info(&(message->Version)); /* Version */ ntlm_generate_server_challenge(context); /* Server Challenge */ ntlm_generate_timestamp(context); /* Timestamp */ if (ntlm_construct_challenge_target_info(context) < 0) /* TargetInfo */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */ message->NegotiateFlags = context->NegotiateFlags; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*) message, MESSAGE_TYPE_CHALLENGE); /* Message Header (12 bytes) */ ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*) message); if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) { message->TargetName.Len = (UINT16) context->TargetName.cbBuffer; message->TargetName.Buffer = (PBYTE) context->TargetName.pvBuffer; } message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) { message->TargetInfo.Len = (UINT16) context->ChallengeTargetInfo.cbBuffer; message->TargetInfo.Buffer = (PBYTE) context->ChallengeTargetInfo.pvBuffer; } PayloadOffset = 48; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) PayloadOffset += 8; message->TargetName.BufferOffset = PayloadOffset; message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len; /* TargetNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->TargetName)); Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */ Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */ /* TargetInfoFields (8 bytes) */ ntlm_write_message_fields(s, &(message->TargetInfo)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */ /* Payload (variable) */ if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) ntlm_write_message_fields_buffer(s, &(message->TargetName)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO) ntlm_write_message_fields_buffer(s, &(message->TargetInfo)); length = Stream_GetPosition(s); buffer->cbBuffer = length; if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer, context->ChallengeMessage.cbBuffer); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->TargetName), "TargetName"); ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo"); #endif context->state = NTLM_STATE_AUTHENTICATE; Stream_Free(s, FALSE); return SEC_I_CONTINUE_NEEDED; } SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 flags; NTLM_AV_PAIR* AvFlags; UINT32 PayloadBufferOffset; NTLM_AUTHENTICATE_MESSAGE* message; SSPI_CREDENTIALS* credentials = context->credentials; flags = 0; AvFlags = NULL; message = &context->AUTHENTICATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponseFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKeyFields (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ context->NegotiateKeyExchange = (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE; if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) || (!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len)) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) { if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } } PayloadBufferOffset = Stream_GetPosition(s); if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) < 0) /* LmChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) < 0) /* NtChallengeResponse */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->NtChallengeResponse.Len > 0) { wStream* snt = Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len); if (!snt) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0) { Stream_Free(s, FALSE); Stream_Free(snt, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Free(snt, FALSE); context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer; context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len; sspi_SecBufferFree(&(context->ChallengeTargetInfo)); context->ChallengeTargetInfo.pvBuffer = (void*) context->NTLMv2Response.Challenge.AvPairs; context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16); CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8); AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, MsvAvFlags); if (AvFlags) Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags); } if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) < 0) /* EncryptedRandomSessionKey */ { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } if (message->EncryptedRandomSessionKey.Len > 0) { if (message->EncryptedRandomSessionKey.Len != 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer, 16); } length = Stream_GetPosition(s); if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); buffer->cbBuffer = length; Stream_SetPosition(s, PayloadBufferOffset); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { context->MessageIntegrityCheckOffset = (UINT32) Stream_GetPosition(s); if (Stream_GetRemainingLength(s) < 16) { Stream_Free(s, FALSE); return SEC_E_INVALID_TOKEN; } Stream_Read(s, message->MessageIntegrityCheck, 16); } #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %"PRIu32")", context->AuthenticateMessage.cbBuffer); winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer, context->AuthenticateMessage.cbBuffer); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); ntlm_print_message_fields(&(message->DomainName), "DomainName"); ntlm_print_message_fields(&(message->UserName), "UserName"); ntlm_print_message_fields(&(message->Workstation), "Workstation"); ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { WLog_DBG(TAG, "MessageIntegrityCheck:"); winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16); } #endif if (message->UserName.Len > 0) { credentials->identity.User = (UINT16*) malloc(message->UserName.Len); if (!credentials->identity.User) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len); credentials->identity.UserLength = message->UserName.Len / 2; } if (message->DomainName.Len > 0) { credentials->identity.Domain = (UINT16*) malloc(message->DomainName.Len); if (!credentials->identity.Domain) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(credentials->identity.Domain, message->DomainName.Buffer, message->DomainName.Len); credentials->identity.DomainLength = message->DomainName.Len / 2; } Stream_Free(s, FALSE); /* Computations beyond this point require the NTLM hash of the password */ context->state = NTLM_STATE_COMPLETION; return SEC_I_COMPLETE_NEEDED; } /** * Send NTLMSSP AUTHENTICATE_MESSAGE.\n * AUTHENTICATE_MESSAGE @msdn{cc236643} * @param NTLM context * @param buffer */ SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) { wStream* s; size_t length; UINT32 PayloadBufferOffset; NTLM_AUTHENTICATE_MESSAGE* message; SSPI_CREDENTIALS* credentials = context->credentials; message = &context->AUTHENTICATE_MESSAGE; ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE)); s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); if (!s) return SEC_E_INTERNAL_ERROR; if (context->NTLMv2) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56; if (context->SendVersionInfo) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION; } if (context->UseMIC) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO; if (context->SendWorkstationName) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED; if (context->confidentiality) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL; if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN; message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET; message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_get_version_info(&(message->Version)); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) { message->Workstation.Len = context->Workstation.Length; message->Workstation.Buffer = (BYTE*) context->Workstation.Buffer; } if (credentials->identity.DomainLength > 0) { message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED; message->DomainName.Len = (UINT16) credentials->identity.DomainLength * 2; message->DomainName.Buffer = (BYTE*) credentials->identity.Domain; } message->UserName.Len = (UINT16) credentials->identity.UserLength * 2; message->UserName.Buffer = (BYTE*) credentials->identity.User; message->LmChallengeResponse.Len = (UINT16) context->LmChallengeResponse.cbBuffer; message->LmChallengeResponse.Buffer = (BYTE*) context->LmChallengeResponse.pvBuffer; message->NtChallengeResponse.Len = (UINT16) context->NtChallengeResponse.cbBuffer; message->NtChallengeResponse.Buffer = (BYTE*) context->NtChallengeResponse.pvBuffer; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) { message->EncryptedRandomSessionKey.Len = 16; message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey; } PayloadBufferOffset = 64; if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) PayloadBufferOffset += 8; /* Version (8 bytes) */ if (context->UseMIC) PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */ message->DomainName.BufferOffset = PayloadBufferOffset; message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len; message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len; message->LmChallengeResponse.BufferOffset = message->Workstation.BufferOffset + message->Workstation.Len; message->NtChallengeResponse.BufferOffset = message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len; message->EncryptedRandomSessionKey.BufferOffset = message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len; ntlm_populate_message_header((NTLM_MESSAGE_HEADER*) message, MESSAGE_TYPE_AUTHENTICATE); ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*) message); /* Message Header (12 bytes) */ ntlm_write_message_fields(s, & (message->LmChallengeResponse)); /* LmChallengeResponseFields (8 bytes) */ ntlm_write_message_fields(s, & (message->NtChallengeResponse)); /* NtChallengeResponseFields (8 bytes) */ ntlm_write_message_fields(s, &(message->DomainName)); /* DomainNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->UserName)); /* UserNameFields (8 bytes) */ ntlm_write_message_fields(s, &(message->Workstation)); /* WorkstationFields (8 bytes) */ ntlm_write_message_fields(s, & (message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKeyFields (8 bytes) */ Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */ if (context->UseMIC) { context->MessageIntegrityCheckOffset = (UINT32) Stream_GetPosition(s); Stream_Zero(s, 16); /* Message Integrity Check (16 bytes) */ } if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED) ntlm_write_message_fields_buffer(s, &(message->DomainName)); /* DomainName */ ntlm_write_message_fields_buffer(s, &(message->UserName)); /* UserName */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED) ntlm_write_message_fields_buffer(s, &(message->Workstation)); /* Workstation */ ntlm_write_message_fields_buffer(s, &(message->LmChallengeResponse)); /* LmChallengeResponse */ ntlm_write_message_fields_buffer(s, &(message->NtChallengeResponse)); /* NtChallengeResponse */ if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ntlm_write_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKey */ length = Stream_GetPosition(s); if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length)) { Stream_Free(s, FALSE); return SEC_E_INTERNAL_ERROR; } CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length); buffer->cbBuffer = length; if (context->UseMIC) { /* Message Integrity Check */ ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, 16); Stream_SetPosition(s, context->MessageIntegrityCheckOffset); Stream_Write(s, message->MessageIntegrityCheck, 16); Stream_SetPosition(s, length); } #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %d)", length); winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length); ntlm_print_negotiate_flags(message->NegotiateFlags); if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) ntlm_print_version_info(&(message->Version)); if (context->AuthenticateTargetInfo.cbBuffer > 0) { WLog_DBG(TAG, "AuthenticateTargetInfo (%"PRIu32"):", context->AuthenticateTargetInfo.cbBuffer); ntlm_print_av_pair_list(context->AuthenticateTargetInfo.pvBuffer); } ntlm_print_message_fields(&(message->DomainName), "DomainName"); ntlm_print_message_fields(&(message->UserName), "UserName"); ntlm_print_message_fields(&(message->Workstation), "Workstation"); ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse"); ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse"); ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey"); if (context->UseMIC) { WLog_DBG(TAG, "MessageIntegrityCheck (length = 16)"); winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16); } #endif context->state = NTLM_STATE_FINAL; Stream_Free(s, FALSE); return SEC_I_COMPLETE_NEEDED; } SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context) { UINT32 flags = 0; NTLM_AV_PAIR* AvFlags = NULL; NTLM_AUTHENTICATE_MESSAGE* message; BYTE messageIntegrityCheck[16]; if (context->state != NTLM_STATE_COMPLETION) return SEC_E_OUT_OF_SEQUENCE; message = &context->AUTHENTICATE_MESSAGE; AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs, MsvAvFlags); if (AvFlags) Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags); if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */ return SEC_E_INTERNAL_ERROR; if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */ return SEC_E_INTERNAL_ERROR; /* KeyExchangeKey */ ntlm_generate_key_exchange_key(context); /* EncryptedRandomSessionKey */ ntlm_decrypt_random_session_key(context); /* ExportedSessionKey */ ntlm_generate_exported_session_key(context); if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK) { ZeroMemory(&((PBYTE) context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset], 16); ntlm_compute_message_integrity_check(context, messageIntegrityCheck, sizeof(messageIntegrityCheck)); CopyMemory(&((PBYTE) context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset], message->MessageIntegrityCheck, 16); if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, 16) != 0) { WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!"); WLog_ERR(TAG, "Expected MIC:"); winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, 16); WLog_ERR(TAG, "Actual MIC:"); winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck, 16); return SEC_E_MESSAGE_ALTERED; } } /* Generate signing keys */ ntlm_generate_client_signing_key(context); ntlm_generate_server_signing_key(context); /* Generate sealing keys */ ntlm_generate_client_sealing_key(context); ntlm_generate_server_sealing_key(context); /* Initialize RC4 seal state */ ntlm_init_rc4_seal_states(context); #ifdef WITH_DEBUG_NTLM WLog_DBG(TAG, "ClientChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8); WLog_DBG(TAG, "ServerChallenge"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8); WLog_DBG(TAG, "SessionBaseKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16); WLog_DBG(TAG, "KeyExchangeKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16); WLog_DBG(TAG, "ExportedSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16); WLog_DBG(TAG, "RandomSessionKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16); WLog_DBG(TAG, "ClientSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16); WLog_DBG(TAG, "ClientSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16); WLog_DBG(TAG, "ServerSigningKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16); WLog_DBG(TAG, "ServerSealingKey"); winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16); WLog_DBG(TAG, "Timestamp"); winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8); #endif context->state = NTLM_STATE_FINAL; ntlm_free_message_fields_buffer(&(message->DomainName)); ntlm_free_message_fields_buffer(&(message->UserName)); ntlm_free_message_fields_buffer(&(message->Workstation)); ntlm_free_message_fields_buffer(&(message->LmChallengeResponse)); ntlm_free_message_fields_buffer(&(message->NtChallengeResponse)); ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey)); return SEC_E_OK; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_675_0
crossvul-cpp_data_bad_1019_0
/*! @file GPMF_parser.c * * @brief GPMF Parser library * * @version 1.2.1 * * (C) Copyright 2017 GoPro Inc (http://gopro.com/). * * Licensed under either: * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 * - MIT license, http://opensource.org/licenses/MIT * at your option. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "GPMF_parser.h" #ifdef DBG #if _WINDOWS #define DBG_MSG printf #else #define DBG_MSG(...) #endif #else #define DBG_MSG(...) #endif GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes. { if (ms) { int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; if (size + 2 <= nestsize) return GPMF_OK; } return GPMF_ERROR_BAD_STRUCTURE; } GPMF_ERR GPMF_Validate(GPMF_stream *ms, GPMF_LEVELS recurse) { if (ms) { uint32_t currpos = ms->pos; int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; while (ms->pos+1 < ms->buffer_size_longs && nestsize > 0) { uint32_t key = ms->buffer[ms->pos]; if (ms->nest_level == 0 && key != GPMF_KEY_DEVICE && ms->device_count == 0 && ms->pos == 0) { DBG_MSG("ERROR: uninitized -- GPMF_ERROR_BAD_STRUCTURE\n"); return GPMF_ERROR_BAD_STRUCTURE; } if (GPMF_VALID_FOURCC(key)) { uint32_t type_size_repeat = ms->buffer[ms->pos + 1]; int32_t size = GPMF_DATA_SIZE(type_size_repeat) >> 2; uint8_t type = GPMF_SAMPLE_TYPE(type_size_repeat); if (size + 2 > nestsize) { DBG_MSG("ERROR: nest size too small within %c%c%c%c-- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } if (!GPMF_VALID_FOURCC(key)) { DBG_MSG("ERROR: invalid 4CC -- GPMF_ERROR_BAD_STRUCTURE\n"); return GPMF_ERROR_BAD_STRUCTURE; } if (type == GPMF_TYPE_NEST && recurse == GPMF_RECURSE_LEVELS) { uint32_t validnest; ms->pos += 2; ms->nest_level++; if (ms->nest_level > GPMF_NEST_LIMIT) { DBG_MSG("ERROR: nest level within %c%c%c%c too deep -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } ms->nest_size[ms->nest_level] = size; validnest = GPMF_Validate(ms, recurse); ms->nest_level--; if (GPMF_OK != validnest) { DBG_MSG("ERROR: invalid nest within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } else { if (ms->nest_level == 0) ms->device_count++; } ms->pos += size; nestsize -= 2 + size; while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; nestsize--; } } else { ms->pos += 2 + size; nestsize -= 2 + size; } if (ms->pos == ms->buffer_size_longs) { ms->pos = currpos; return GPMF_OK; } } else { if (key == GPMF_KEY_END) { do { ms->pos++; nestsize--; } while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == 0); } else if (ms->nest_level == 0 && ms->device_count > 0) { ms->pos = currpos; return GPMF_OK; } else { DBG_MSG("ERROR: bad struct within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } } } ms->pos = currpos; return GPMF_OK; } else { DBG_MSG("ERROR: Invalid handle -- GPMF_ERROR_MEMORY\n"); return GPMF_ERROR_MEMORY; } } GPMF_ERR GPMF_ResetState(GPMF_stream *ms) { if (ms) { ms->pos = 0; ms->nest_level = 0; ms->device_count = 0; ms->nest_size[ms->nest_level] = 0; ms->last_level_pos[ms->nest_level] = 0; ms->last_seek[ms->nest_level] = 0; ms->device_id = 0; ms->device_name[0] = 0; return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_Init(GPMF_stream *ms, uint32_t *buffer, int datasize) { if(ms) { ms->buffer = buffer; ms->buffer_size_longs = datasize >>2; GPMF_ResetState(ms); return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_CopyState(GPMF_stream *msrc, GPMF_stream *mdst) { if (msrc && mdst) { memcpy(mdst, msrc, sizeof(GPMF_stream)); return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_Next(GPMF_stream *ms, GPMF_LEVELS recurse) { if (ms) { if (ms->pos+1 < ms->buffer_size_longs) { uint32_t key, type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) return GPMF_ERROR_BAD_STRUCTURE; if (GPMF_TYPE_NEST == type && GPMF_KEY_DEVICE == ms->buffer[ms->pos] && ms->nest_level == 0) { ms->last_level_pos[ms->nest_level] = ms->pos; ms->nest_size[ms->nest_level] = size; if (recurse) ms->pos += 2; else ms->pos += 2 + size; } else { if (size + 2 > ms->nest_size[ms->nest_level]) return GPMF_ERROR_BAD_STRUCTURE; if (recurse && type == GPMF_TYPE_NEST) { ms->last_level_pos[ms->nest_level] = ms->pos; ms->pos += 2; ms->nest_size[ms->nest_level] -= size + 2; ms->nest_level++; if (ms->nest_level > GPMF_NEST_LIMIT) return GPMF_ERROR_BAD_STRUCTURE; ms->nest_size[ms->nest_level] = size; } else { if (recurse) { ms->pos += size + 2; ms->nest_size[ms->nest_level] -= size + 2; } else { if (ms->nest_size[ms->nest_level] - (size + 2) > 0) { ms->pos += size + 2; ms->nest_size[ms->nest_level] -= size + 2; } else { return GPMF_ERROR_LAST; } } } } while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; ms->nest_size[ms->nest_level]--; } while (ms->nest_level > 0 && ms->nest_size[ms->nest_level] == 0) { ms->nest_level--; //if (ms->nest_level == 0) //{ // ms->device_count++; //} } if (ms->pos < ms->buffer_size_longs) { while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; ms->nest_size[ms->nest_level]--; } key = ms->buffer[ms->pos]; if (!GPMF_VALID_FOURCC(key)) return GPMF_ERROR_BAD_STRUCTURE; if (key == GPMF_KEY_DEVICE_ID) ms->device_id = BYTESWAP32(ms->buffer[ms->pos + 2]); if (key == GPMF_KEY_DEVICE_NAME) { size = GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]); // in bytes if (size > sizeof(ms->device_name) - 1) size = sizeof(ms->device_name) - 1; memcpy(ms->device_name, &ms->buffer[ms->pos + 2], size); ms->device_name[size] = 0; } } else { // end of buffer return GPMF_ERROR_BUFFER_END; } return GPMF_OK; } else { // end of buffer return GPMF_ERROR_BUFFER_END; } } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_FindNext(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse) { GPMF_stream prevstate; if (ms) { memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (ms->pos < ms->buffer_size_longs) { while (0 == GPMF_Next(ms, recurse)) { if (ms->buffer[ms->pos] == fourcc) { return GPMF_OK; //found match } } // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } GPMF_ERR GPMF_Reserved(uint32_t key) { if(key == GPMF_KEY_DEVICE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_DEVICE_ID) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_DEVICE_NAME) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_STREAM) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_STREAM_NAME) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_SI_UNITS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_UNITS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_SCALE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TYPE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TOTAL_SAMPLES) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TICK) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TOCK) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_EMPTY_PAYLOADS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_REMARK) return GPMF_ERROR_RESERVED; return GPMF_OK; } uint32_t GPMF_PayloadSampleCount(GPMF_stream *ms) { uint32_t count = 0; if (ms) { uint32_t fourcc = GPMF_Key(ms); GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats { count=2; while (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) { count++; } } else { count = GPMF_Repeat(ms); } } return count; } GPMF_ERR GPMF_SeekToSamples(GPMF_stream *ms) { GPMF_stream prevstate; if (ms) { if (ms->pos+1 < ms->buffer_size_longs) { uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (type == GPMF_TYPE_NEST) GPMF_Next(ms, GPMF_RECURSE_LEVELS); // open STRM and recurse in while (0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL)) { uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) { memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_BAD_STRUCTURE; } type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type == GPMF_TYPE_NEST) // Nest with-in nest { return GPMF_OK; //found match } if (size + 2 == ms->nest_size[ms->nest_level]) { uint32_t key = GPMF_Key(ms); if (GPMF_ERROR_RESERVED == GPMF_Reserved(key)) return GPMF_ERROR_FIND; return GPMF_OK; //found match } if (ms->buffer[ms->pos] == ms->buffer[ms->pos + size + 2]) // Matching tags { return GPMF_OK; //found match } } // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } GPMF_ERR GPMF_FindPrev(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse) { GPMF_stream prevstate; if (ms) { uint32_t curr_level = ms->nest_level; memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (ms->pos < ms->buffer_size_longs && curr_level > 0) { do { ms->last_seek[curr_level] = ms->pos; ms->pos = ms->last_level_pos[curr_level - 1] + 2; ms->nest_size[curr_level] += ms->last_seek[curr_level] - ms->pos; do { if (ms->last_seek[curr_level] > ms->pos && ms->buffer[ms->pos] == fourcc) { return GPMF_OK; //found match } } while (ms->last_seek[curr_level] > ms->pos && 0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL)); curr_level--; } while (recurse == GPMF_RECURSE_LEVELS && curr_level > 0); // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } uint32_t GPMF_Key(GPMF_stream *ms) { if (ms) { uint32_t key = ms->buffer[ms->pos]; return key; } return 0; } uint32_t GPMF_Type(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos+1]); return type; } return 0; } uint32_t GPMF_StructSize(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t ssize = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) return 0; // as the structure is corrupted. i.e. GPMF_ERROR_BAD_STRUCTURE; return ssize; } return 0; } uint32_t GPMF_ElementsInStruct(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t ssize = GPMF_StructSize(ms); GPMF_SampleType type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type != GPMF_TYPE_NEST && type != GPMF_TYPE_COMPLEX) { int32_t tsize = GPMF_SizeofType(type); if (tsize > 0) return ssize / tsize; else return 0; } if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL)) { char tmp[64] = ""; uint32_t tmpsize = sizeof(tmp); char *data = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); if (GPMF_OK == GPMF_ExpandComplexTYPE(data, size, tmp, &tmpsize)) return tmpsize; } } } return 0; } uint32_t GPMF_Repeat(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t repeat = GPMF_SAMPLES(ms->buffer[ms->pos + 1]); return repeat; } return 0; } uint32_t GPMF_RawDataSize(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); if (GPMF_OK != IsValidSize(ms, size >> 2)) return 0; return size; } return 0; } uint32_t GPMF_NestLevel(GPMF_stream *ms) { if (ms) { return ms->nest_level; } return 0; } uint32_t GPMF_DeviceID(GPMF_stream *ms) { if (ms) { return ms->device_id; } return 0; } GPMF_ERR GPMF_DeviceName(GPMF_stream *ms, char *devicenamebuf, uint32_t devicename_buf_size) { if (ms && devicenamebuf) { uint32_t len = (uint32_t)strlen(ms->device_name); if (len >= devicename_buf_size) return GPMF_ERROR_MEMORY; memcpy(devicenamebuf, ms->device_name, len); devicenamebuf[len] = 0; return GPMF_OK; } return GPMF_ERROR_MEMORY; } void *GPMF_RawData(GPMF_stream *ms) { if (ms) { return (void *)&ms->buffer[ms->pos + 2]; } return NULL; } uint32_t GPMF_SizeofType(GPMF_SampleType type) { uint32_t ssize = 0; switch ((int)type) { case GPMF_TYPE_STRING_ASCII: ssize = 1; break; case GPMF_TYPE_SIGNED_BYTE: ssize = 1; break; case GPMF_TYPE_UNSIGNED_BYTE: ssize = 1; break; // These datatypes are always be stored in Big-Endian case GPMF_TYPE_SIGNED_SHORT: ssize = 2; break; case GPMF_TYPE_UNSIGNED_SHORT: ssize = 2; break; case GPMF_TYPE_FLOAT: ssize = 4; break; case GPMF_TYPE_FOURCC: ssize = 4; break; case GPMF_TYPE_SIGNED_LONG: ssize = 4; break; case GPMF_TYPE_UNSIGNED_LONG: ssize = 4; break; case GPMF_TYPE_Q15_16_FIXED_POINT: ssize = 4; break; case GPMF_TYPE_Q31_32_FIXED_POINT: ssize = 8; break; case GPMF_TYPE_DOUBLE: ssize = 8; break; case GPMF_TYPE_SIGNED_64BIT_INT: ssize = 8; break; case GPMF_TYPE_UNSIGNED_64BIT_INT: ssize = 8; break; //All unknown or larger than 8-bytes stored as is: case GPMF_TYPE_GUID: ssize = 16; break; case GPMF_TYPE_UTC_DATE_TIME: ssize = 16; break; } return ssize; } uint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize) { uint32_t i = 0, k = 0, count = 0; while (i<srcsize && k<*dstsize) { if (src[i] == '[' && i>0) { int j = 1; count = 0; while (src[i + j] >= '0' && src[i + j] <= '9') { count *= 10; count += src[i + j] - '0'; j++; } if (count > 1) { uint32_t l; for (l = 1; l<count; l++) { dst[k] = src[i - 1]; k++; } } i += j; if (src[i] == ']') i++; } else { dst[k] = src[i]; if (dst[k] == 0) break; i++, k++; } } if (k >= *dstsize) return GPMF_ERROR_MEMORY; // bad structure formed dst[k] = 0; *dstsize = k; return GPMF_OK; } uint32_t GPMF_SizeOfComplexTYPE(char *type, uint32_t typestringlength) { char *typearray = type; uint32_t size = 0, expand = 0; uint32_t i, len = typestringlength; for (i = 0; i < len; i++) if (typearray[i] == '[') expand = 1; if (expand) { char exptypearray[64]; uint32_t dstsize = sizeof(exptypearray); if (GPMF_OK == GPMF_ExpandComplexTYPE(typearray, len, exptypearray, &dstsize)) { typearray = exptypearray; len = dstsize; } else return 0; } for (i = 0; i < len; i++) { uint32_t typesize = GPMF_SizeofType((GPMF_SampleType)typearray[i]); if (typesize < 1) return 0; size += typesize; } return size; } GPMF_ERR GPMF_FormattedData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples) { if (ms && buffer) { uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2]; uint8_t *output = (uint8_t *)buffer; uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); uint32_t typesize = 1; uint32_t elements = 0; uint32_t typestringlength = 1; char complextype[64] = "L"; if (type == GPMF_TYPE_NEST) return GPMF_ERROR_BAD_STRUCTURE; if (GPMF_OK != IsValidSize(ms, remaining_sample_size>>2)) return GPMF_ERROR_BAD_STRUCTURE; if (sample_size * read_samples > buffersize) return GPMF_ERROR_MEMORY; remaining_sample_size -= sample_offset * sample_size; // skip samples data += sample_offset * sample_size; if (remaining_sample_size < sample_size * read_samples) return GPMF_ERROR_MEMORY; if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS)) { char *data1 = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); typestringlength = sizeof(complextype); if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength)) { elements = (uint32_t)strlen(complextype); if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength)) return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else { typesize = GPMF_SizeofType((GPMF_SampleType)type); if (type == GPMF_TYPE_FOURCC) typesize = 1; // Do not ByteSWAP if (typesize == 0) return GPMF_ERROR_MEMORY; elements = sample_size / typesize; } while (read_samples--) { uint32_t i,j; for (i = 0; i < elements; i++) { if (type == GPMF_TYPE_COMPLEX) { if (complextype[i] == GPMF_TYPE_FOURCC) { *output++ = *data++; *output++ = *data++; *output++ = *data++; *output++ = *data++; typesize = 0; } else typesize = GPMF_SizeofType(complextype[i]); } switch (typesize) { case 2: { uint16_t *data16 = (uint16_t *)data; uint16_t *output16 = (uint16_t *)output; *output16 = BYTESWAP16(*data16); output16++; data16++; data = (uint8_t *)data16; output = (uint8_t *)output16; } break; case 4: { uint32_t *data32 = (uint32_t *)data; uint32_t *output32 = (uint32_t *)output; *output32 = BYTESWAP32(*data32); output32++; data32++; data = (uint8_t *)data32; output = (uint8_t *)output32; } break; case 8: { uint32_t *data32 = (uint32_t *)data; uint32_t *output32 = (uint32_t *)output; *(output32+1) = BYTESWAP32(*data32); *(output32) = BYTESWAP32(*(data32+1)); data32 += 2; output32 += 2; data = (uint8_t *)data32; output = (uint8_t *)output32; } break; default: //1, 16 or more not byteswapped for (j = 0; j < typesize; j++) *output++ = *data++; break; } } } return GPMF_OK; } return GPMF_ERROR_MEMORY; } #define MACRO_CAST_SCALE_UNSIGNED_TYPE(casttype) \ { \ casttype *tmp = (casttype *)output; \ switch (scaletype) \ { \ case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int8_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint8_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int16_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint16_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int32_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint32_t *)scaledata8); break; \ case GPMF_TYPE_FLOAT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((float *)scaledata8); break; \ default: break; \ } \ output = (uint8_t *)tmp; \ } #define MACRO_CAST_SCALE_SIGNED_TYPE(casttype) \ { \ casttype *tmp = (casttype *)output; \ switch (scaletype) \ { \ case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((int8_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((uint8_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((int16_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((uint16_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((int32_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((uint32_t *)scaledata8); break; \ case GPMF_TYPE_FLOAT: *tmp++ = (casttype)*val / (casttype)*((float *)scaledata8); break; \ default: break; \ } \ output = (uint8_t *)tmp; \ } #define MACRO_CAST_SCALE \ switch (outputType) { \ case GPMF_TYPE_SIGNED_BYTE: MACRO_CAST_SCALE_SIGNED_TYPE(int8_t) break; \ case GPMF_TYPE_UNSIGNED_BYTE: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint8_t) break; \ case GPMF_TYPE_SIGNED_SHORT: MACRO_CAST_SCALE_SIGNED_TYPE(int16_t) break; \ case GPMF_TYPE_UNSIGNED_SHORT: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint16_t) break; \ case GPMF_TYPE_FLOAT: MACRO_CAST_SCALE_SIGNED_TYPE(float) break; \ case GPMF_TYPE_SIGNED_LONG: MACRO_CAST_SCALE_SIGNED_TYPE(int32_t) break; \ case GPMF_TYPE_UNSIGNED_LONG: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint32_t) break; \ case GPMF_TYPE_DOUBLE: MACRO_CAST_SCALE_SIGNED_TYPE(double) break; \ default: break; \ } #define MACRO_BSWAP_CAST_SCALE(swap, inputcast, tempcast) \ { \ inputcast *val; \ tempcast temp, *datatemp = (tempcast *)data; \ temp = swap(*datatemp); \ val = (inputcast *)&temp; \ MACRO_CAST_SCALE \ datatemp++; \ data = (uint8_t *)datatemp; \ } GPMF_ERR GPMF_ScaledData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType outputType) { if (ms && buffer) { uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2]; uint8_t *output = (uint8_t *)buffer; uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t output_sample_size = GPMF_SizeofType(outputType); uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); char complextype[64] = "L"; uint32_t inputtypesize = 0; uint32_t inputtypeelements = 0; uint8_t scaletype = 0; uint8_t scalecount = 0; uint32_t scaletypesize = 0; uint32_t *scaledata = NULL; uint32_t tmpbuffer[64]; uint32_t tmpbuffersize = sizeof(tmpbuffer); uint32_t elements = 1; type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type == GPMF_TYPE_NEST) return GPMF_ERROR_MEMORY; if (GPMF_OK != IsValidSize(ms, remaining_sample_size >> 2)) return GPMF_ERROR_BAD_STRUCTURE; remaining_sample_size -= sample_offset * sample_size; // skip samples data += sample_offset * sample_size; if (remaining_sample_size < sample_size * read_samples) return GPMF_ERROR_MEMORY; if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS)) { char *data1 = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); uint32_t typestringlength = sizeof(complextype); if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength)) { inputtypeelements = elements = typestringlength; if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength)) return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else { complextype[0] = type; inputtypesize = GPMF_SizeofType(type); if (inputtypesize == 0) return GPMF_ERROR_MEMORY; inputtypeelements = 1; elements = sample_size / inputtypesize; } if (output_sample_size * elements * read_samples > buffersize) return GPMF_ERROR_MEMORY; switch (outputType) { case GPMF_TYPE_SIGNED_BYTE: case GPMF_TYPE_UNSIGNED_BYTE: case GPMF_TYPE_SIGNED_SHORT: case GPMF_TYPE_UNSIGNED_SHORT: case GPMF_TYPE_FLOAT: case GPMF_TYPE_SIGNED_LONG: case GPMF_TYPE_UNSIGNED_LONG: case GPMF_TYPE_DOUBLE: // All supported formats. { GPMF_stream fs; GPMF_CopyState(ms, &fs); if (GPMF_OK == GPMF_FindPrev(&fs, GPMF_KEY_SCALE, GPMF_CURRENT_LEVEL)) { scaledata = (uint32_t *)GPMF_RawData(&fs); scaletype = GPMF_SAMPLE_TYPE(fs.buffer[fs.pos + 1]); switch (scaletype) { case GPMF_TYPE_SIGNED_BYTE: case GPMF_TYPE_UNSIGNED_BYTE: case GPMF_TYPE_SIGNED_SHORT: case GPMF_TYPE_UNSIGNED_SHORT: case GPMF_TYPE_SIGNED_LONG: case GPMF_TYPE_UNSIGNED_LONG: case GPMF_TYPE_FLOAT: scalecount = GPMF_SAMPLES(fs.buffer[fs.pos + 1]); scaletypesize = GPMF_SizeofType(scaletype); if (scalecount > 1) if (scalecount != elements) return GPMF_ERROR_SCALE_COUNT; GPMF_FormattedData(&fs, tmpbuffer, tmpbuffersize, 0, scalecount); scaledata = (uint32_t *)tmpbuffer; break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } } else { scaletype = 'L'; scalecount = 1; tmpbuffer[0] = 1; // set the scale to 1 is no scale was provided scaledata = (uint32_t *)tmpbuffer; } } while (read_samples--) { uint32_t i; uint8_t *scaledata8 = (uint8_t *)scaledata; for (i = 0; i < elements; i++) { switch (complextype[i % inputtypeelements]) { case GPMF_TYPE_FLOAT: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, float, uint32_t) break; case GPMF_TYPE_SIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, int8_t, uint8_t) break; case GPMF_TYPE_UNSIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, uint8_t, uint8_t) break; case GPMF_TYPE_SIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, int16_t, uint16_t) break; case GPMF_TYPE_UNSIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, uint16_t, uint16_t) break; case GPMF_TYPE_SIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, int32_t, uint32_t) break; case GPMF_TYPE_UNSIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, uint32_t, uint32_t) break; case GPMF_TYPE_SIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break; case GPMF_TYPE_UNSIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } if (scalecount > 1) scaledata8 += scaletypesize; } } break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } return GPMF_OK; } return GPMF_ERROR_MEMORY; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1019_0
crossvul-cpp_data_good_3372_0
/********************************************************************** regexec.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "regint.h" #define USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE #ifdef USE_CRNL_AS_LINE_TERMINATOR #define ONIGENC_IS_MBC_CRNL(enc,p,end) \ (ONIGENC_MBC_TO_CODE(enc,p,end) == 13 && \ ONIGENC_IS_MBC_NEWLINE(enc,(p+enclen(enc,p)),end)) #endif #ifdef USE_CAPTURE_HISTORY static void history_tree_free(OnigCaptureTreeNode* node); static void history_tree_clear(OnigCaptureTreeNode* node) { int i; if (IS_NOT_NULL(node)) { for (i = 0; i < node->num_childs; i++) { if (IS_NOT_NULL(node->childs[i])) { history_tree_free(node->childs[i]); } } for (i = 0; i < node->allocated; i++) { node->childs[i] = (OnigCaptureTreeNode* )0; } node->num_childs = 0; node->beg = ONIG_REGION_NOTPOS; node->end = ONIG_REGION_NOTPOS; node->group = -1; } } static void history_tree_free(OnigCaptureTreeNode* node) { history_tree_clear(node); xfree(node); } static void history_root_free(OnigRegion* r) { if (IS_NOT_NULL(r->history_root)) { history_tree_free(r->history_root); r->history_root = (OnigCaptureTreeNode* )0; } } static OnigCaptureTreeNode* history_node_new(void) { OnigCaptureTreeNode* node; node = (OnigCaptureTreeNode* )xmalloc(sizeof(OnigCaptureTreeNode)); CHECK_NULL_RETURN(node); node->childs = (OnigCaptureTreeNode** )0; node->allocated = 0; node->num_childs = 0; node->group = -1; node->beg = ONIG_REGION_NOTPOS; node->end = ONIG_REGION_NOTPOS; return node; } static int history_tree_add_child(OnigCaptureTreeNode* parent, OnigCaptureTreeNode* child) { #define HISTORY_TREE_INIT_ALLOC_SIZE 8 if (parent->num_childs >= parent->allocated) { int n, i; if (IS_NULL(parent->childs)) { n = HISTORY_TREE_INIT_ALLOC_SIZE; parent->childs = (OnigCaptureTreeNode** )xmalloc(sizeof(OnigCaptureTreeNode*) * n); } else { n = parent->allocated * 2; parent->childs = (OnigCaptureTreeNode** )xrealloc(parent->childs, sizeof(OnigCaptureTreeNode*) * n); } CHECK_NULL_RETURN_MEMERR(parent->childs); for (i = parent->allocated; i < n; i++) { parent->childs[i] = (OnigCaptureTreeNode* )0; } parent->allocated = n; } parent->childs[parent->num_childs] = child; parent->num_childs++; return 0; } static OnigCaptureTreeNode* history_tree_clone(OnigCaptureTreeNode* node) { int i; OnigCaptureTreeNode *clone, *child; clone = history_node_new(); CHECK_NULL_RETURN(clone); clone->beg = node->beg; clone->end = node->end; for (i = 0; i < node->num_childs; i++) { child = history_tree_clone(node->childs[i]); if (IS_NULL(child)) { history_tree_free(clone); return (OnigCaptureTreeNode* )0; } history_tree_add_child(clone, child); } return clone; } extern OnigCaptureTreeNode* onig_get_capture_tree(OnigRegion* region) { return region->history_root; } #endif /* USE_CAPTURE_HISTORY */ extern void onig_region_clear(OnigRegion* region) { int i; for (i = 0; i < region->num_regs; i++) { region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS; } #ifdef USE_CAPTURE_HISTORY history_root_free(region); #endif } extern int onig_region_resize(OnigRegion* region, int n) { region->num_regs = n; if (n < ONIG_NREGION) n = ONIG_NREGION; if (region->allocated == 0) { region->beg = (int* )xmalloc(n * sizeof(int)); region->end = (int* )xmalloc(n * sizeof(int)); if (region->beg == 0 || region->end == 0) return ONIGERR_MEMORY; region->allocated = n; } else if (region->allocated < n) { region->beg = (int* )xrealloc(region->beg, n * sizeof(int)); region->end = (int* )xrealloc(region->end, n * sizeof(int)); if (region->beg == 0 || region->end == 0) return ONIGERR_MEMORY; region->allocated = n; } return 0; } static int onig_region_resize_clear(OnigRegion* region, int n) { int r; r = onig_region_resize(region, n); if (r != 0) return r; onig_region_clear(region); return 0; } extern int onig_region_set(OnigRegion* region, int at, int beg, int end) { if (at < 0) return ONIGERR_INVALID_ARGUMENT; if (at >= region->allocated) { int r = onig_region_resize(region, at + 1); if (r < 0) return r; } region->beg[at] = beg; region->end[at] = end; return 0; } extern void onig_region_init(OnigRegion* region) { region->num_regs = 0; region->allocated = 0; region->beg = (int* )0; region->end = (int* )0; region->history_root = (OnigCaptureTreeNode* )0; } extern OnigRegion* onig_region_new(void) { OnigRegion* r; r = (OnigRegion* )xmalloc(sizeof(OnigRegion)); onig_region_init(r); return r; } extern void onig_region_free(OnigRegion* r, int free_self) { if (r) { if (r->allocated > 0) { if (r->beg) xfree(r->beg); if (r->end) xfree(r->end); r->allocated = 0; } #ifdef USE_CAPTURE_HISTORY history_root_free(r); #endif if (free_self) xfree(r); } } extern void onig_region_copy(OnigRegion* to, OnigRegion* from) { #define RREGC_SIZE (sizeof(int) * from->num_regs) int i; if (to == from) return; if (to->allocated == 0) { if (from->num_regs > 0) { to->beg = (int* )xmalloc(RREGC_SIZE); to->end = (int* )xmalloc(RREGC_SIZE); to->allocated = from->num_regs; } } else if (to->allocated < from->num_regs) { to->beg = (int* )xrealloc(to->beg, RREGC_SIZE); to->end = (int* )xrealloc(to->end, RREGC_SIZE); to->allocated = from->num_regs; } for (i = 0; i < from->num_regs; i++) { to->beg[i] = from->beg[i]; to->end[i] = from->end[i]; } to->num_regs = from->num_regs; #ifdef USE_CAPTURE_HISTORY history_root_free(to); if (IS_NOT_NULL(from->history_root)) { to->history_root = history_tree_clone(from->history_root); } #endif } /** stack **/ #define INVALID_STACK_INDEX -1 /* stack type */ /* used by normal-POP */ #define STK_ALT 0x0001 #define STK_LOOK_BEHIND_NOT 0x0002 #define STK_POS_NOT 0x0003 /* handled by normal-POP */ #define STK_MEM_START 0x0100 #define STK_MEM_END 0x8200 #define STK_REPEAT_INC 0x0300 #define STK_STATE_CHECK_MARK 0x1000 /* avoided by normal-POP */ #define STK_NULL_CHECK_START 0x3000 #define STK_NULL_CHECK_END 0x5000 /* for recursive call */ #define STK_MEM_END_MARK 0x8400 #define STK_POS 0x0500 /* used when POP-POS */ #define STK_STOP_BT 0x0600 /* mark for "(?>...)" */ #define STK_REPEAT 0x0700 #define STK_CALL_FRAME 0x0800 #define STK_RETURN 0x0900 #define STK_VOID 0x0a00 /* for fill a blank */ /* stack type check mask */ #define STK_MASK_POP_USED 0x00ff #define STK_MASK_TO_VOID_TARGET 0x10ff #define STK_MASK_MEM_END_OR_MARK 0x8000 /* MEM_END or MEM_END_MARK */ #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE #define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\ (msa).stack_p = (void* )0;\ (msa).options = (arg_option);\ (msa).region = (arg_region);\ (msa).start = (arg_start);\ (msa).best_len = ONIG_MISMATCH;\ (msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\ } while(0) #else #define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\ (msa).stack_p = (void* )0;\ (msa).options = (arg_option);\ (msa).region = (arg_region);\ (msa).start = (arg_start);\ (msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\ } while(0) #endif #ifdef USE_COMBINATION_EXPLOSION_CHECK #define STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE 16 #define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num) do { \ if ((state_num) > 0 && str_len >= STATE_CHECK_STRING_THRESHOLD_LEN) {\ unsigned int size = (unsigned int )(((str_len) + 1) * (state_num) + 7) >> 3;\ offset = ((offset) * (state_num)) >> 3;\ if (size > 0 && offset < size && size < STATE_CHECK_BUFF_MAX_SIZE) {\ if (size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) \ (msa).state_check_buff = (void* )xmalloc(size);\ else \ (msa).state_check_buff = (void* )xalloca(size);\ xmemset(((char* )((msa).state_check_buff)+(offset)), 0, \ (size_t )(size - (offset))); \ (msa).state_check_buff_size = size;\ }\ else {\ (msa).state_check_buff = (void* )0;\ (msa).state_check_buff_size = 0;\ }\ }\ else {\ (msa).state_check_buff = (void* )0;\ (msa).state_check_buff_size = 0;\ }\ } while(0) #define MATCH_ARG_FREE(msa) do {\ if ((msa).stack_p) xfree((msa).stack_p);\ if ((msa).state_check_buff_size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) { \ if ((msa).state_check_buff) xfree((msa).state_check_buff);\ }\ } while(0) #else #define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num) #define MATCH_ARG_FREE(msa) if ((msa).stack_p) xfree((msa).stack_p) #endif #define ALLOCA_PTR_NUM_LIMIT 50 #define STACK_INIT(stack_num) do {\ if (msa->stack_p) {\ is_alloca = 0;\ alloc_base = msa->stack_p;\ stk_base = (OnigStackType* )(alloc_base\ + (sizeof(OnigStackIndex) * msa->ptr_num));\ stk = stk_base;\ stk_end = stk_base + msa->stack_n;\ }\ else if (msa->ptr_num > ALLOCA_PTR_NUM_LIMIT) {\ is_alloca = 0;\ alloc_base = (char* )xmalloc(sizeof(OnigStackIndex) * msa->ptr_num\ + sizeof(OnigStackType) * (stack_num));\ stk_base = (OnigStackType* )(alloc_base\ + (sizeof(OnigStackIndex) * msa->ptr_num));\ stk = stk_base;\ stk_end = stk_base + (stack_num);\ }\ else {\ is_alloca = 1;\ alloc_base = (char* )xalloca(sizeof(OnigStackIndex) * msa->ptr_num\ + sizeof(OnigStackType) * (stack_num));\ stk_base = (OnigStackType* )(alloc_base\ + (sizeof(OnigStackIndex) * msa->ptr_num));\ stk = stk_base;\ stk_end = stk_base + (stack_num);\ }\ } while(0); #define STACK_SAVE do{\ msa->stack_n = stk_end - stk_base;\ if (is_alloca != 0) {\ size_t size = sizeof(OnigStackIndex) * msa->ptr_num \ + sizeof(OnigStackType) * msa->stack_n;\ msa->stack_p = xmalloc(size);\ xmemcpy(msa->stack_p, alloc_base, size);\ }\ else {\ msa->stack_p = alloc_base;\ };\ } while(0) #define UPDATE_FOR_STACK_REALLOC do{\ repeat_stk = (OnigStackIndex* )alloc_base;\ mem_start_stk = (OnigStackIndex* )(repeat_stk + reg->num_repeat);\ mem_end_stk = mem_start_stk + num_mem;\ mem_start_stk--; /* for index start from 1 */\ mem_end_stk--; /* for index start from 1 */\ } while(0) static unsigned int MatchStackLimitSize = DEFAULT_MATCH_STACK_LIMIT_SIZE; extern unsigned int onig_get_match_stack_limit_size(void) { return MatchStackLimitSize; } extern int onig_set_match_stack_limit_size(unsigned int size) { MatchStackLimitSize = size; return 0; } static int stack_double(int is_alloca, char** arg_alloc_base, OnigStackType** arg_stk_base, OnigStackType** arg_stk_end, OnigStackType** arg_stk, OnigMatchArg* msa) { unsigned int n; int used; size_t size; size_t new_size; char* alloc_base; char* new_alloc_base; OnigStackType *stk_base, *stk_end, *stk; alloc_base = *arg_alloc_base; stk_base = *arg_stk_base; stk_end = *arg_stk_end; stk = *arg_stk; n = stk_end - stk_base; size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n; n *= 2; new_size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n; if (is_alloca != 0) { new_alloc_base = (char* )xmalloc(new_size); if (IS_NULL(new_alloc_base)) { STACK_SAVE; return ONIGERR_MEMORY; } xmemcpy(new_alloc_base, alloc_base, size); } else { if (MatchStackLimitSize != 0 && n > MatchStackLimitSize) { if ((unsigned int )(stk_end - stk_base) == MatchStackLimitSize) return ONIGERR_MATCH_STACK_LIMIT_OVER; else n = MatchStackLimitSize; } new_alloc_base = (char* )xrealloc(alloc_base, new_size); if (IS_NULL(new_alloc_base)) { STACK_SAVE; return ONIGERR_MEMORY; } } alloc_base = new_alloc_base; used = stk - stk_base; *arg_alloc_base = alloc_base; *arg_stk_base = (OnigStackType* )(alloc_base + (sizeof(OnigStackIndex) * msa->ptr_num)); *arg_stk = *arg_stk_base + used; *arg_stk_end = *arg_stk_base + n; return 0; } #define STACK_ENSURE(n) do {\ if (stk_end - stk < (n)) {\ int r = stack_double(is_alloca, &alloc_base, &stk_base, &stk_end, &stk,\ msa);\ if (r != 0) { STACK_SAVE; return r; } \ is_alloca = 0;\ UPDATE_FOR_STACK_REALLOC;\ }\ } while(0) #define STACK_AT(index) (stk_base + (index)) #define GET_STACK_INDEX(stk) ((stk) - stk_base) #define STACK_PUSH_TYPE(stack_type) do {\ STACK_ENSURE(1);\ stk->type = (stack_type);\ STACK_INC;\ } while(0) #define IS_TO_VOID_TARGET(stk) (((stk)->type & STK_MASK_TO_VOID_TARGET) != 0) #ifdef USE_COMBINATION_EXPLOSION_CHECK #define STATE_CHECK_POS(s,snum) \ (((s) - str) * num_comb_exp_check + ((snum) - 1)) #define STATE_CHECK_VAL(v,snum) do {\ if (state_check_buff != NULL) {\ int x = STATE_CHECK_POS(s,snum);\ (v) = state_check_buff[x/8] & (1<<(x%8));\ }\ else (v) = 0;\ } while(0) #define ELSE_IF_STATE_CHECK_MARK(stk) \ else if ((stk)->type == STK_STATE_CHECK_MARK) { \ int x = STATE_CHECK_POS(stk->u.state.pstr, stk->u.state.state_check);\ state_check_buff[x/8] |= (1<<(x%8)); \ } #define STACK_PUSH(stack_type,pat,s,sprev) do {\ STACK_ENSURE(1);\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ stk->u.state.pstr = (s);\ stk->u.state.pstr_prev = (sprev);\ stk->u.state.state_check = 0;\ STACK_INC;\ } while(0) #define STACK_PUSH_ENSURED(stack_type,pat) do {\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ stk->u.state.state_check = 0;\ STACK_INC;\ } while(0) #define STACK_PUSH_ALT_WITH_STATE_CHECK(pat,s,sprev,snum) do {\ STACK_ENSURE(1);\ stk->type = STK_ALT;\ stk->u.state.pcode = (pat);\ stk->u.state.pstr = (s);\ stk->u.state.pstr_prev = (sprev);\ stk->u.state.state_check = ((state_check_buff != NULL) ? (snum) : 0);\ STACK_INC;\ } while(0) #define STACK_PUSH_STATE_CHECK(s,snum) do {\ if (state_check_buff != NULL) {\ STACK_ENSURE(1);\ stk->type = STK_STATE_CHECK_MARK;\ stk->u.state.pstr = (s);\ stk->u.state.state_check = (snum);\ STACK_INC;\ }\ } while(0) #else /* USE_COMBINATION_EXPLOSION_CHECK */ #define ELSE_IF_STATE_CHECK_MARK(stk) #define STACK_PUSH(stack_type,pat,s,sprev) do {\ STACK_ENSURE(1);\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ stk->u.state.pstr = (s);\ stk->u.state.pstr_prev = (sprev);\ STACK_INC;\ } while(0) #define STACK_PUSH_ENSURED(stack_type,pat) do {\ stk->type = (stack_type);\ stk->u.state.pcode = (pat);\ STACK_INC;\ } while(0) #endif /* USE_COMBINATION_EXPLOSION_CHECK */ #define STACK_PUSH_ALT(pat,s,sprev) STACK_PUSH(STK_ALT,pat,s,sprev) #define STACK_PUSH_POS(s,sprev) STACK_PUSH(STK_POS,NULL_UCHARP,s,sprev) #define STACK_PUSH_POS_NOT(pat,s,sprev) STACK_PUSH(STK_POS_NOT,pat,s,sprev) #define STACK_PUSH_STOP_BT STACK_PUSH_TYPE(STK_STOP_BT) #define STACK_PUSH_LOOK_BEHIND_NOT(pat,s,sprev) \ STACK_PUSH(STK_LOOK_BEHIND_NOT,pat,s,sprev) #define STACK_PUSH_REPEAT(id, pat) do {\ STACK_ENSURE(1);\ stk->type = STK_REPEAT;\ stk->u.repeat.num = (id);\ stk->u.repeat.pcode = (pat);\ stk->u.repeat.count = 0;\ STACK_INC;\ } while(0) #define STACK_PUSH_REPEAT_INC(sindex) do {\ STACK_ENSURE(1);\ stk->type = STK_REPEAT_INC;\ stk->u.repeat_inc.si = (sindex);\ STACK_INC;\ } while(0) #define STACK_PUSH_MEM_START(mnum, s) do {\ STACK_ENSURE(1);\ stk->type = STK_MEM_START;\ stk->u.mem.num = (mnum);\ stk->u.mem.pstr = (s);\ stk->u.mem.start = mem_start_stk[mnum];\ stk->u.mem.end = mem_end_stk[mnum];\ mem_start_stk[mnum] = GET_STACK_INDEX(stk);\ mem_end_stk[mnum] = INVALID_STACK_INDEX;\ STACK_INC;\ } while(0) #define STACK_PUSH_MEM_END(mnum, s) do {\ STACK_ENSURE(1);\ stk->type = STK_MEM_END;\ stk->u.mem.num = (mnum);\ stk->u.mem.pstr = (s);\ stk->u.mem.start = mem_start_stk[mnum];\ stk->u.mem.end = mem_end_stk[mnum];\ mem_end_stk[mnum] = GET_STACK_INDEX(stk);\ STACK_INC;\ } while(0) #define STACK_PUSH_MEM_END_MARK(mnum) do {\ STACK_ENSURE(1);\ stk->type = STK_MEM_END_MARK;\ stk->u.mem.num = (mnum);\ STACK_INC;\ } while(0) #define STACK_GET_MEM_START(mnum, k) do {\ int level = 0;\ k = stk;\ while (k > stk_base) {\ k--;\ if ((k->type & STK_MASK_MEM_END_OR_MARK) != 0 \ && k->u.mem.num == (mnum)) {\ level++;\ }\ else if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\ if (level == 0) break;\ level--;\ }\ }\ } while(0) #define STACK_GET_MEM_RANGE(k, mnum, start, end) do {\ int level = 0;\ while (k < stk) {\ if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\ if (level == 0) (start) = k->u.mem.pstr;\ level++;\ }\ else if (k->type == STK_MEM_END && k->u.mem.num == (mnum)) {\ level--;\ if (level == 0) {\ (end) = k->u.mem.pstr;\ break;\ }\ }\ k++;\ }\ } while(0) #define STACK_PUSH_NULL_CHECK_START(cnum, s) do {\ STACK_ENSURE(1);\ stk->type = STK_NULL_CHECK_START;\ stk->u.null_check.num = (cnum);\ stk->u.null_check.pstr = (s);\ STACK_INC;\ } while(0) #define STACK_PUSH_NULL_CHECK_END(cnum) do {\ STACK_ENSURE(1);\ stk->type = STK_NULL_CHECK_END;\ stk->u.null_check.num = (cnum);\ STACK_INC;\ } while(0) #define STACK_PUSH_CALL_FRAME(pat) do {\ STACK_ENSURE(1);\ stk->type = STK_CALL_FRAME;\ stk->u.call_frame.ret_addr = (pat);\ STACK_INC;\ } while(0) #define STACK_PUSH_RETURN do {\ STACK_ENSURE(1);\ stk->type = STK_RETURN;\ STACK_INC;\ } while(0) #ifdef ONIG_DEBUG #define STACK_BASE_CHECK(p, at) \ if ((p) < stk_base) {\ fprintf(stderr, "at %s\n", at);\ goto stack_error;\ } #else #define STACK_BASE_CHECK(p, at) #endif #define STACK_POP_ONE do {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP_ONE"); \ } while(0) #define STACK_POP do {\ switch (pop_level) {\ case STACK_POP_LEVEL_FREE:\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP"); \ if ((stk->type & STK_MASK_POP_USED) != 0) break;\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ break;\ case STACK_POP_LEVEL_MEM_START:\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP 2"); \ if ((stk->type & STK_MASK_POP_USED) != 0) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ break;\ default:\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP 3"); \ if ((stk->type & STK_MASK_POP_USED) != 0) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ else if (stk->type == STK_REPEAT_INC) {\ STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\ }\ else if (stk->type == STK_MEM_END) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ break;\ }\ } while(0) #define STACK_POP_TIL_POS_NOT do {\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP_TIL_POS_NOT"); \ if (stk->type == STK_POS_NOT) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ else if (stk->type == STK_REPEAT_INC) {\ STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\ }\ else if (stk->type == STK_MEM_END) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ } while(0) #define STACK_POP_TIL_LOOK_BEHIND_NOT do {\ while (1) {\ stk--;\ STACK_BASE_CHECK(stk, "STACK_POP_TIL_LOOK_BEHIND_NOT"); \ if (stk->type == STK_LOOK_BEHIND_NOT) break;\ else if (stk->type == STK_MEM_START) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ else if (stk->type == STK_REPEAT_INC) {\ STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\ }\ else if (stk->type == STK_MEM_END) {\ mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\ mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\ }\ ELSE_IF_STATE_CHECK_MARK(stk);\ }\ } while(0) #define STACK_POS_END(k) do {\ k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_POS_END"); \ if (IS_TO_VOID_TARGET(k)) {\ k->type = STK_VOID;\ }\ else if (k->type == STK_POS) {\ k->type = STK_VOID;\ break;\ }\ }\ } while(0) #define STACK_STOP_BT_END do {\ OnigStackType *k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_STOP_BT_END"); \ if (IS_TO_VOID_TARGET(k)) {\ k->type = STK_VOID;\ }\ else if (k->type == STK_STOP_BT) {\ k->type = STK_VOID;\ break;\ }\ }\ } while(0) #define STACK_NULL_CHECK(isnull,id,s) do {\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ (isnull) = (k->u.null_check.pstr == (s));\ break;\ }\ }\ }\ } while(0) #define STACK_NULL_CHECK_REC(isnull,id,s) do {\ int level = 0;\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK_REC"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ if (level == 0) {\ (isnull) = (k->u.null_check.pstr == (s));\ break;\ }\ else level--;\ }\ }\ else if (k->type == STK_NULL_CHECK_END) {\ level++;\ }\ }\ } while(0) #define STACK_NULL_CHECK_MEMST(isnull,id,s,reg) do {\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ if (k->u.null_check.pstr != (s)) {\ (isnull) = 0;\ break;\ }\ else {\ UChar* endp;\ (isnull) = 1;\ while (k < stk) {\ if (k->type == STK_MEM_START) {\ if (k->u.mem.end == INVALID_STACK_INDEX) {\ (isnull) = 0; break;\ }\ if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\ endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\ else\ endp = (UChar* )k->u.mem.end;\ if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\ (isnull) = 0; break;\ }\ else if (endp != s) {\ (isnull) = -1; /* empty, but position changed */ \ }\ }\ k++;\ }\ break;\ }\ }\ }\ }\ } while(0) #define STACK_NULL_CHECK_MEMST_REC(isnull,id,s,reg) do {\ int level = 0;\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST_REC"); \ if (k->type == STK_NULL_CHECK_START) {\ if (k->u.null_check.num == (id)) {\ if (level == 0) {\ if (k->u.null_check.pstr != (s)) {\ (isnull) = 0;\ break;\ }\ else {\ UChar* endp;\ (isnull) = 1;\ while (k < stk) {\ if (k->type == STK_MEM_START) {\ if (k->u.mem.end == INVALID_STACK_INDEX) {\ (isnull) = 0; break;\ }\ if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\ endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\ else\ endp = (UChar* )k->u.mem.end;\ if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\ (isnull) = 0; break;\ }\ else if (endp != s) {\ (isnull) = -1; /* empty, but position changed */ \ }\ }\ k++;\ }\ break;\ }\ }\ else {\ level--;\ }\ }\ }\ else if (k->type == STK_NULL_CHECK_END) {\ if (k->u.null_check.num == (id)) level++;\ }\ }\ } while(0) #define STACK_GET_REPEAT(id, k) do {\ int level = 0;\ k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_GET_REPEAT"); \ if (k->type == STK_REPEAT) {\ if (level == 0) {\ if (k->u.repeat.num == (id)) {\ break;\ }\ }\ }\ else if (k->type == STK_CALL_FRAME) level--;\ else if (k->type == STK_RETURN) level++;\ }\ } while(0) #define STACK_RETURN(addr) do {\ int level = 0;\ OnigStackType* k = stk;\ while (1) {\ k--;\ STACK_BASE_CHECK(k, "STACK_RETURN"); \ if (k->type == STK_CALL_FRAME) {\ if (level == 0) {\ (addr) = k->u.call_frame.ret_addr;\ break;\ }\ else level--;\ }\ else if (k->type == STK_RETURN)\ level++;\ }\ } while(0) #define STRING_CMP(s1,s2,len) do {\ while (len-- > 0) {\ if (*s1++ != *s2++) goto fail;\ }\ } while(0) #define STRING_CMP_IC(case_fold_flag,s1,ps2,len) do {\ if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \ goto fail; \ } while(0) static int string_cmp_ic(OnigEncoding enc, int case_fold_flag, UChar* s1, UChar** ps2, int mblen) { UChar buf1[ONIGENC_MBC_CASE_FOLD_MAXLEN]; UChar buf2[ONIGENC_MBC_CASE_FOLD_MAXLEN]; UChar *p1, *p2, *end1, *s2, *end2; int len1, len2; s2 = *ps2; end1 = s1 + mblen; end2 = s2 + mblen; while (s1 < end1) { len1 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s1, end1, buf1); len2 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s2, end2, buf2); if (len1 != len2) return 0; p1 = buf1; p2 = buf2; while (len1-- > 0) { if (*p1 != *p2) return 0; p1++; p2++; } } *ps2 = s2; return 1; } #define STRING_CMP_VALUE(s1,s2,len,is_fail) do {\ is_fail = 0;\ while (len-- > 0) {\ if (*s1++ != *s2++) {\ is_fail = 1; break;\ }\ }\ } while(0) #define STRING_CMP_VALUE_IC(case_fold_flag,s1,ps2,len,is_fail) do {\ if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \ is_fail = 1; \ else \ is_fail = 0; \ } while(0) #define IS_EMPTY_STR (str == end) #define ON_STR_BEGIN(s) ((s) == str) #define ON_STR_END(s) ((s) == end) #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE #define DATA_ENSURE_CHECK1 (s < right_range) #define DATA_ENSURE_CHECK(n) (s + (n) <= right_range) #define DATA_ENSURE(n) if (s + (n) > right_range) goto fail #else #define DATA_ENSURE_CHECK1 (s < end) #define DATA_ENSURE_CHECK(n) (s + (n) <= end) #define DATA_ENSURE(n) if (s + (n) > end) goto fail #endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */ #ifdef USE_CAPTURE_HISTORY static int make_capture_history_tree(OnigCaptureTreeNode* node, OnigStackType** kp, OnigStackType* stk_top, UChar* str, regex_t* reg) { int n, r; OnigCaptureTreeNode* child; OnigStackType* k = *kp; while (k < stk_top) { if (k->type == STK_MEM_START) { n = k->u.mem.num; if (n <= ONIG_MAX_CAPTURE_HISTORY_GROUP && BIT_STATUS_AT(reg->capture_history, n) != 0) { child = history_node_new(); CHECK_NULL_RETURN_MEMERR(child); child->group = n; child->beg = (int )(k->u.mem.pstr - str); r = history_tree_add_child(node, child); if (r != 0) return r; *kp = (k + 1); r = make_capture_history_tree(child, kp, stk_top, str, reg); if (r != 0) return r; k = *kp; child->end = (int )(k->u.mem.pstr - str); } } else if (k->type == STK_MEM_END) { if (k->u.mem.num == node->group) { node->end = (int )(k->u.mem.pstr - str); *kp = k; return 0; } } k++; } return 1; /* 1: root node ending. */ } #endif #ifdef USE_BACKREF_WITH_LEVEL static int mem_is_in_memp(int mem, int num, UChar* memp) { int i; MemNumType m; for (i = 0; i < num; i++) { GET_MEMNUM_INC(m, memp); if (mem == (int )m) return 1; } return 0; } static int backref_match_at_nested_level(regex_t* reg , OnigStackType* top, OnigStackType* stk_base , int ignore_case, int case_fold_flag , int nest, int mem_num, UChar* memp, UChar** s, const UChar* send) { UChar *ss, *p, *pstart, *pend = NULL_UCHARP; int level; OnigStackType* k; level = 0; k = top; k--; while (k >= stk_base) { if (k->type == STK_CALL_FRAME) { level--; } else if (k->type == STK_RETURN) { level++; } else if (level == nest) { if (k->type == STK_MEM_START) { if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) { pstart = k->u.mem.pstr; if (pend != NULL_UCHARP) { if (pend - pstart > send - *s) return 0; /* or goto next_mem; */ p = pstart; ss = *s; if (ignore_case != 0) { if (string_cmp_ic(reg->enc, case_fold_flag, pstart, &ss, (int )(pend - pstart)) == 0) return 0; /* or goto next_mem; */ } else { while (p < pend) { if (*p++ != *ss++) return 0; /* or goto next_mem; */ } } *s = ss; return 1; } } } else if (k->type == STK_MEM_END) { if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) { pend = k->u.mem.pstr; } } } k--; } return 0; } #endif /* USE_BACKREF_WITH_LEVEL */ #ifdef ONIG_DEBUG_STATISTICS #define USE_TIMEOFDAY #ifdef USE_TIMEOFDAY #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif static struct timeval ts, te; #define GETTIME(t) gettimeofday(&(t), (struct timezone* )0) #define TIMEDIFF(te,ts) (((te).tv_usec - (ts).tv_usec) + \ (((te).tv_sec - (ts).tv_sec)*1000000)) #else #ifdef HAVE_SYS_TIMES_H #include <sys/times.h> #endif static struct tms ts, te; #define GETTIME(t) times(&(t)) #define TIMEDIFF(te,ts) ((te).tms_utime - (ts).tms_utime) #endif static int OpCounter[256]; static int OpPrevCounter[256]; static unsigned long OpTime[256]; static int OpCurr = OP_FINISH; static int OpPrevTarget = OP_FAIL; static int MaxStackDepth = 0; #define MOP_IN(opcode) do {\ if (opcode == OpPrevTarget) OpPrevCounter[OpCurr]++;\ OpCurr = opcode;\ OpCounter[opcode]++;\ GETTIME(ts);\ } while(0) #define MOP_OUT do {\ GETTIME(te);\ OpTime[OpCurr] += TIMEDIFF(te, ts);\ } while(0) extern void onig_statistics_init(void) { int i; for (i = 0; i < 256; i++) { OpCounter[i] = OpPrevCounter[i] = 0; OpTime[i] = 0; } MaxStackDepth = 0; } extern int onig_print_statistics(FILE* f) { int r; int i; r = fprintf(f, " count prev time\n"); if (r < 0) return -1; for (i = 0; OnigOpInfo[i].opcode >= 0; i++) { r = fprintf(f, "%8d: %8d: %10ld: %s\n", OpCounter[i], OpPrevCounter[i], OpTime[i], OnigOpInfo[i].name); if (r < 0) return -1; } r = fprintf(f, "\nmax stack depth: %d\n", MaxStackDepth); if (r < 0) return -1; return 0; } #define STACK_INC do {\ stk++;\ if (stk - stk_base > MaxStackDepth) \ MaxStackDepth = stk - stk_base;\ } while(0) #else #define STACK_INC stk++ #define MOP_IN(opcode) #define MOP_OUT #endif /* matching region of POSIX API */ typedef int regoff_t; typedef struct { regoff_t rm_so; regoff_t rm_eo; } posix_regmatch_t; /* match data(str - end) from position (sstart). */ /* if sstart == str then set sprev to NULL. */ static int match_at(regex_t* reg, const UChar* str, const UChar* end, #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE const UChar* right_range, #endif const UChar* sstart, UChar* sprev, OnigMatchArg* msa) { static UChar FinishCode[] = { OP_FINISH }; int i, n, num_mem, best_len, pop_level; LengthType tlen, tlen2; MemNumType mem; RelAddrType addr; UChar *s, *q, *sbegin; int is_alloca; char *alloc_base; OnigStackType *stk_base, *stk, *stk_end; OnigStackType *stkp; /* used as any purpose. */ OnigStackIndex si; OnigStackIndex *repeat_stk; OnigStackIndex *mem_start_stk, *mem_end_stk; #ifdef USE_COMBINATION_EXPLOSION_CHECK int scv; unsigned char* state_check_buff = msa->state_check_buff; int num_comb_exp_check = reg->num_comb_exp_check; #endif UChar *p = reg->p; OnigOptionType option = reg->options; OnigEncoding encode = reg->enc; OnigCaseFoldType case_fold_flag = reg->case_fold_flag; //n = reg->num_repeat + reg->num_mem * 2; pop_level = reg->stack_pop_level; num_mem = reg->num_mem; STACK_INIT(INIT_MATCH_STACK_SIZE); UPDATE_FOR_STACK_REALLOC; for (i = 1; i <= num_mem; i++) { mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX; } #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "match_at: str: %d, end: %d, start: %d, sprev: %d\n", (int )str, (int )end, (int )sstart, (int )sprev); fprintf(stderr, "size: %d, start offset: %d\n", (int )(end - str), (int )(sstart - str)); #endif STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */ best_len = ONIG_MISMATCH; s = (UChar* )sstart; while (1) { #ifdef ONIG_DEBUG_MATCH { UChar *q, *bp, buf[50]; int len; fprintf(stderr, "%4d> \"", (int )(s - str)); bp = buf; for (i = 0, q = s; i < 7 && q < end; i++) { len = enclen(encode, q); while (len-- > 0) *bp++ = *q++; } if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; } else { xmemcpy(bp, "\"", 1); bp += 1; } *bp = 0; fputs((char* )buf, stderr); for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr); onig_print_compiled_byte_code(stderr, p, NULL, encode); fprintf(stderr, "\n"); } #endif sbegin = s; switch (*p++) { case OP_END: MOP_IN(OP_END); n = s - sstart; if (n > best_len) { OnigRegion* region; #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE if (IS_FIND_LONGEST(option)) { if (n > msa->best_len) { msa->best_len = n; msa->best_s = (UChar* )sstart; } else goto end_best_len; } #endif best_len = n; region = msa->region; if (region) { #ifdef USE_POSIX_API_REGION_OPTION if (IS_POSIX_REGION(msa->options)) { posix_regmatch_t* rmt = (posix_regmatch_t* )region; rmt[0].rm_so = sstart - str; rmt[0].rm_eo = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str; rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS; } } } else { #endif /* USE_POSIX_API_REGION_OPTION */ region->beg[0] = sstart - str; region->end[0] = s - str; for (i = 1; i <= num_mem; i++) { if (mem_end_stk[i] != INVALID_STACK_INDEX) { if (BIT_STATUS_AT(reg->bt_mem_start, i)) region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str; else region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str; region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i) ? STACK_AT(mem_end_stk[i])->u.mem.pstr : (UChar* )((void* )mem_end_stk[i])) - str; } else { region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS; } } #ifdef USE_CAPTURE_HISTORY if (reg->capture_history != 0) { int r; OnigCaptureTreeNode* node; if (IS_NULL(region->history_root)) { region->history_root = node = history_node_new(); CHECK_NULL_RETURN_MEMERR(node); } else { node = region->history_root; history_tree_clear(node); } node->group = 0; node->beg = sstart - str; node->end = s - str; stkp = stk_base; r = make_capture_history_tree(region->history_root, &stkp, stk, (UChar* )str, reg); if (r < 0) { best_len = r; /* error code */ goto finish; } } #endif /* USE_CAPTURE_HISTORY */ #ifdef USE_POSIX_API_REGION_OPTION } /* else IS_POSIX_REGION() */ #endif } /* if (region) */ } /* n > best_len */ #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE end_best_len: #endif MOP_OUT; if (IS_FIND_CONDITION(option)) { if (IS_FIND_NOT_EMPTY(option) && s == sstart) { best_len = ONIG_MISMATCH; goto fail; /* for retry */ } if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) { goto fail; /* for retry */ } } /* default behavior: return first-matching result. */ goto finish; break; case OP_EXACT1: MOP_IN(OP_EXACT1); DATA_ENSURE(1); if (*p != *s) goto fail; p++; s++; MOP_OUT; break; case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC); { int len; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) { goto fail; } p++; q++; } } MOP_OUT; break; case OP_EXACT2: MOP_IN(OP_EXACT2); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT3: MOP_IN(OP_EXACT3); DATA_ENSURE(3); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT4: MOP_IN(OP_EXACT4); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACT5: MOP_IN(OP_EXACT5); DATA_ENSURE(5); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; sprev = s; p++; s++; MOP_OUT; continue; break; case OP_EXACTN: MOP_IN(OP_EXACTN); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen); while (tlen-- > 0) { if (*p++ != *s++) goto fail; } sprev = s - 1; MOP_OUT; continue; break; case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC); { int len; UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; GET_LENGTH_INC(tlen, p); endp = p + tlen; while (p < endp) { sprev = s; DATA_ENSURE(1); len = ONIGENC_MBC_CASE_FOLD(encode, /* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */ case_fold_flag, &s, end, lowbuf); DATA_ENSURE(0); q = lowbuf; while (len-- > 0) { if (*p != *q) goto fail; p++; q++; } } } MOP_OUT; continue; break; case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1); DATA_ENSURE(2); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; break; case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2); DATA_ENSURE(4); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3); DATA_ENSURE(6); if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; sprev = s; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; MOP_OUT; continue; break; case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 2); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 2; MOP_OUT; continue; break; case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N); GET_LENGTH_INC(tlen, p); DATA_ENSURE(tlen * 3); while (tlen-- > 0) { if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; if (*p != *s) goto fail; p++; s++; } sprev = s - 3; MOP_OUT; continue; break; case OP_EXACTMBN: MOP_IN(OP_EXACTMBN); GET_LENGTH_INC(tlen, p); /* mb-len */ GET_LENGTH_INC(tlen2, p); /* string len */ tlen2 *= tlen; DATA_ENSURE(tlen2); while (tlen2-- > 0) { if (*p != *s) goto fail; p++; s++; } sprev = s - tlen; MOP_OUT; continue; break; case OP_CCLASS: MOP_IN(OP_CCLASS); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */ MOP_OUT; break; case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB); if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail; cclass_mb: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len; DATA_ENSURE(1); mb_len = enclen(encode, s); DATA_ENSURE(mb_len); ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (! onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (! onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; MOP_OUT; break; case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb; } else { if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT); DATA_ENSURE(1); if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; s += enclen(encode, s); MOP_OUT; break; case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_HEAD(encode, s)) { s++; GET_LENGTH_INC(tlen, p); p += tlen; goto cc_mb_not_success; } cclass_mb_not: GET_LENGTH_INC(tlen, p); { OnigCodePoint code; UChar *ss; int mb_len = enclen(encode, s); if (! DATA_ENSURE_CHECK(mb_len)) { DATA_ENSURE(1); s = (UChar* )end; p += tlen; goto cc_mb_not_success; } ss = s; s += mb_len; code = ONIGENC_MBC_TO_CODE(encode, ss, s); #ifdef PLATFORM_UNALIGNED_WORD_ACCESS if (onig_is_in_code_range(p, code)) goto fail; #else q = p; ALIGNMENT_RIGHT(q); if (onig_is_in_code_range(q, code)) goto fail; #endif } p += tlen; cc_mb_not_success: MOP_OUT; break; case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT); DATA_ENSURE(1); if (ONIGENC_IS_MBC_HEAD(encode, s)) { p += SIZE_BITSET; goto cclass_mb_not; } else { if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail; p += SIZE_BITSET; GET_LENGTH_INC(tlen, p); p += tlen; s++; } MOP_OUT; break; case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE); { OnigCodePoint code; void *node; int mb_len; UChar *ss; DATA_ENSURE(1); GET_POINTER_INC(node, p); mb_len = enclen(encode, s); ss = s; s += mb_len; DATA_ENSURE(0); code = ONIGENC_MBC_TO_CODE(encode, ss, s); if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail; } MOP_OUT; break; case OP_ANYCHAR: MOP_IN(OP_ANYCHAR); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; s += n; MOP_OUT; break; case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML); DATA_ENSURE(1); n = enclen(encode, s); DATA_ENSURE(n); s += n; MOP_OUT; break; case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR); while (DATA_ENSURE_CHECK1) { STACK_PUSH_ALT(p, s, sprev); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } p++; MOP_OUT; break; case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT); while (DATA_ENSURE_CHECK1) { if (*p == *s) { STACK_PUSH_ALT(p + 1, s, sprev); } n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } p++; MOP_OUT; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); DATA_ENSURE(n); if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail; sprev = s; s += n; } MOP_OUT; break; case OP_STATE_CHECK_ANYCHAR_ML_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR); GET_STATE_CHECK_NUM_INC(mem, p); while (DATA_ENSURE_CHECK1) { STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem); n = enclen(encode, s); if (n > 1) { DATA_ENSURE(n); sprev = s; s += n; } else { sprev = s; s++; } } MOP_OUT; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_WORD: MOP_IN(OP_WORD); DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_NOT_WORD: MOP_IN(OP_NOT_WORD); DATA_ENSURE(1); if (ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; s += enclen(encode, s); MOP_OUT; break; case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND); if (ON_STR_BEGIN(s)) { DATA_ENSURE(1); if (! ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (! ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) == ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND); if (ON_STR_BEGIN(s)) { if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) goto fail; } else if (ON_STR_END(s)) { if (ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } else { if (ONIGENC_IS_MBC_WORD(encode, s, end) != ONIGENC_IS_MBC_WORD(encode, sprev, end)) goto fail; } MOP_OUT; continue; break; #ifdef USE_WORD_BEGIN_END case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN); if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) { if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) { MOP_OUT; continue; } } goto fail; break; case OP_WORD_END: MOP_IN(OP_WORD_END); if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) { if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) { MOP_OUT; continue; } } goto fail; break; #endif case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF); if (! ON_STR_BEGIN(s)) goto fail; MOP_OUT; continue; break; case OP_END_BUF: MOP_IN(OP_END_BUF); if (! ON_STR_END(s)) goto fail; MOP_OUT; continue; break; case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE); if (ON_STR_BEGIN(s)) { if (IS_NOTBOL(msa->options)) goto fail; MOP_OUT; continue; } else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) { MOP_OUT; continue; } goto fail; break; case OP_END_LINE: MOP_IN(OP_END_LINE); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { MOP_OUT; continue; } #endif goto fail; break; case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF); if (ON_STR_END(s)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) { #endif if (IS_NOTEOL(msa->options)) goto fail; MOP_OUT; continue; #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE } #endif } else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) && ON_STR_END(s + enclen(encode, s))) { MOP_OUT; continue; } #ifdef USE_CRNL_AS_LINE_TERMINATOR else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) { UChar* ss = s + enclen(encode, s); ss += enclen(encode, ss); if (ON_STR_END(ss)) { MOP_OUT; continue; } } #endif goto fail; break; case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION); if (s != msa->start) goto fail; MOP_OUT; continue; break; case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_START(mem, s); MOP_OUT; continue; break; case OP_MEMORY_START: MOP_IN(OP_MEMORY_START); GET_MEMNUM_INC(mem, p); mem_start_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH); GET_MEMNUM_INC(mem, p); STACK_PUSH_MEM_END(mem, s); MOP_OUT; continue; break; case OP_MEMORY_END: MOP_IN(OP_MEMORY_END); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); MOP_OUT; continue; break; #ifdef USE_SUBEXP_CALL case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC); GET_MEMNUM_INC(mem, p); STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */ STACK_PUSH_MEM_END(mem, s); mem_start_stk[mem] = GET_STACK_INDEX(stkp); MOP_OUT; continue; break; case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC); GET_MEMNUM_INC(mem, p); mem_end_stk[mem] = (OnigStackIndex )((void* )s); STACK_GET_MEM_START(mem, stkp); if (BIT_STATUS_AT(reg->bt_mem_start, mem)) mem_start_stk[mem] = GET_STACK_INDEX(stkp); else mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr); STACK_PUSH_MEM_END_MARK(mem); MOP_OUT; continue; break; #endif case OP_BACKREF1: MOP_IN(OP_BACKREF1); mem = 1; goto backref; break; case OP_BACKREF2: MOP_IN(OP_BACKREF2); mem = 2; goto backref; break; case OP_BACKREFN: MOP_IN(OP_BACKREFN); GET_MEMNUM_INC(mem, p); backref: { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP(pstart, s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC); GET_MEMNUM_INC(mem, p); { int len; UChar *pstart, *pend; /* if you want to remove following line, you should check in parse and compile time. */ if (mem > num_mem) goto fail; if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail; if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; STRING_CMP_IC(case_fold_flag, pstart, &s, n); while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; MOP_OUT; continue; } break; case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE(pstart, swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC); { int len, is_fail; UChar *pstart, *pend, *swork; GET_LENGTH_INC(tlen, p); for (i = 0; i < tlen; i++) { GET_MEMNUM_INC(mem, p); if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue; if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue; if (BIT_STATUS_AT(reg->bt_mem_start, mem)) pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr; else pstart = (UChar* )((void* )mem_start_stk[mem]); pend = (BIT_STATUS_AT(reg->bt_mem_end, mem) ? STACK_AT(mem_end_stk[mem])->u.mem.pstr : (UChar* )((void* )mem_end_stk[mem])); n = pend - pstart; DATA_ENSURE(n); sprev = s; swork = s; STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail); if (is_fail) continue; s = swork; while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * (tlen - i - 1)); break; /* success */ } if (i == tlen) goto fail; MOP_OUT; continue; } break; #ifdef USE_BACKREF_WITH_LEVEL case OP_BACKREF_WITH_LEVEL: { int len; OnigOptionType ic; LengthType level; GET_OPTION_INC(ic, p); GET_LENGTH_INC(level, p); GET_LENGTH_INC(tlen, p); sprev = s; if (backref_match_at_nested_level(reg, stk, stk_base, ic , case_fold_flag, (int )level, (int )tlen, p, &s, end)) { while (sprev + (len = enclen(encode, sprev)) < s) sprev += len; p += (SIZE_MEMNUM * tlen); } else goto fail; MOP_OUT; continue; } break; #endif #if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */ case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH); GET_OPTION_INC(option, p); STACK_PUSH_ALT(p, s, sprev); p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL; MOP_OUT; continue; break; case OP_SET_OPTION: MOP_IN(OP_SET_OPTION); GET_OPTION_INC(option, p); MOP_OUT; continue; break; #endif case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START); GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_PUSH_NULL_CHECK_START(mem, s); MOP_OUT; continue; break; case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK(isnull, mem, s); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "NULL_CHECK_END: skip id:%d, s:%d\n", (int )mem, (int )s); #endif null_check_found: /* empty loop founded, skip next instruction */ switch (*p++) { case OP_JUMP: case OP_PUSH: p += SIZE_RELADDR; break; case OP_REPEAT_INC: case OP_REPEAT_INC_NG: case OP_REPEAT_INC_SG: case OP_REPEAT_INC_NG_SG: p += SIZE_MEMNUM; break; default: goto unexpected_bytecode_error; break; } } } MOP_OUT; continue; break; #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ STACK_NULL_CHECK_MEMST(isnull, mem, s, reg); if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "NULL_CHECK_END_MEMST: skip id:%d, s:%d\n", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } } MOP_OUT; continue; break; #endif #ifdef USE_SUBEXP_CALL case OP_NULL_CHECK_END_MEMST_PUSH: MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH); { int isnull; GET_MEMNUM_INC(mem, p); /* mem: null check id */ #ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg); #else STACK_NULL_CHECK_REC(isnull, mem, s); #endif if (isnull) { #ifdef ONIG_DEBUG_MATCH fprintf(stderr, "NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n", (int )mem, (int )s); #endif if (isnull == -1) goto fail; goto null_check_found; } else { STACK_PUSH_NULL_CHECK_END(mem); } } MOP_OUT; continue; break; #endif case OP_JUMP: MOP_IN(OP_JUMP); GET_RELADDR_INC(addr, p); p += addr; MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_PUSH: MOP_IN(OP_PUSH); GET_RELADDR_INC(addr, p); STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; break; #ifdef USE_COMBINATION_EXPLOSION_CHECK case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; GET_RELADDR_INC(addr, p); STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); MOP_OUT; continue; break; case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP); GET_STATE_CHECK_NUM_INC(mem, p); GET_RELADDR_INC(addr, p); STATE_CHECK_VAL(scv, mem); if (scv) { p += addr; } else { STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem); } MOP_OUT; continue; break; case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK); GET_STATE_CHECK_NUM_INC(mem, p); STATE_CHECK_VAL(scv, mem); if (scv) goto fail; STACK_PUSH_STATE_CHECK(s, mem); MOP_OUT; continue; break; #endif /* USE_COMBINATION_EXPLOSION_CHECK */ case OP_POP: MOP_IN(OP_POP); STACK_POP_ONE; MOP_OUT; continue; break; case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1); GET_RELADDR_INC(addr, p); if (*p == *s && DATA_ENSURE_CHECK1) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p += (addr + 1); MOP_OUT; continue; break; case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT); GET_RELADDR_INC(addr, p); if (*p == *s) { p++; STACK_PUSH_ALT(p + addr, s, sprev); MOP_OUT; continue; } p++; MOP_OUT; continue; break; case OP_REPEAT: MOP_IN(OP_REPEAT); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p + addr, s, sprev); } } MOP_OUT; continue; break; case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG); { GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ GET_RELADDR_INC(addr, p); STACK_ENSURE(1); repeat_stk[mem] = GET_STACK_INDEX(stk); STACK_PUSH_REPEAT(mem, p); if (reg->repeat_range[mem].lower == 0) { STACK_PUSH_ALT(p, s, sprev); p += addr; } } MOP_OUT; continue; break; case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc: stkp->u.repeat.count++; if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) { /* end of repeat. Nothing to do. */ } else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { STACK_PUSH_ALT(p, s, sprev); p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */ } else { p = stkp->u.repeat.pcode; } STACK_PUSH_REPEAT_INC(si); MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc; break; case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ si = repeat_stk[mem]; stkp = STACK_AT(si); repeat_inc_ng: stkp->u.repeat.count++; if (stkp->u.repeat.count < reg->repeat_range[mem].upper) { if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) { UChar* pcode = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); STACK_PUSH_ALT(pcode, s, sprev); } else { p = stkp->u.repeat.pcode; STACK_PUSH_REPEAT_INC(si); } } else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) { STACK_PUSH_REPEAT_INC(si); } MOP_OUT; CHECK_INTERRUPT_IN_MATCH_AT; continue; break; case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG); GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */ STACK_GET_REPEAT(mem, stkp); si = GET_STACK_INDEX(stkp); goto repeat_inc_ng; break; case OP_PUSH_POS: MOP_IN(OP_PUSH_POS); STACK_PUSH_POS(s, sprev); MOP_OUT; continue; break; case OP_POP_POS: MOP_IN(OP_POP_POS); { STACK_POS_END(stkp); s = stkp->u.state.pstr; sprev = stkp->u.state.pstr_prev; } MOP_OUT; continue; break; case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT); GET_RELADDR_INC(addr, p); STACK_PUSH_POS_NOT(p + addr, s, sprev); MOP_OUT; continue; break; case OP_FAIL_POS: MOP_IN(OP_FAIL_POS); STACK_POP_TIL_POS_NOT; goto fail; break; case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT); STACK_PUSH_STOP_BT; MOP_OUT; continue; break; case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT); STACK_STOP_BT_END; MOP_OUT; continue; break; case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND); GET_LENGTH_INC(tlen, p); s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(s)) goto fail; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); MOP_OUT; continue; break; case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT); GET_RELADDR_INC(addr, p); GET_LENGTH_INC(tlen, p); q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen); if (IS_NULL(q)) { /* too short case -> success. ex. /(?<!XXX)a/.match("a") If you want to change to fail, replace following line. */ p += addr; /* goto fail; */ } else { STACK_PUSH_LOOK_BEHIND_NOT(p + addr, s, sprev); s = q; sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s); } MOP_OUT; continue; break; case OP_FAIL_LOOK_BEHIND_NOT: MOP_IN(OP_FAIL_LOOK_BEHIND_NOT); STACK_POP_TIL_LOOK_BEHIND_NOT; goto fail; break; #ifdef USE_SUBEXP_CALL case OP_CALL: MOP_IN(OP_CALL); GET_ABSADDR_INC(addr, p); STACK_PUSH_CALL_FRAME(p); p = reg->p + addr; MOP_OUT; continue; break; case OP_RETURN: MOP_IN(OP_RETURN); STACK_RETURN(p); STACK_PUSH_RETURN; MOP_OUT; continue; break; #endif case OP_FINISH: goto finish; break; fail: MOP_OUT; /* fall */ case OP_FAIL: MOP_IN(OP_FAIL); STACK_POP; p = stk->u.state.pcode; s = stk->u.state.pstr; sprev = stk->u.state.pstr_prev; #ifdef USE_COMBINATION_EXPLOSION_CHECK if (stk->u.state.state_check != 0) { stk->type = STK_STATE_CHECK_MARK; stk++; } #endif MOP_OUT; continue; break; default: goto bytecode_error; } /* end of switch */ sprev = sbegin; } /* end of while(1) */ finish: STACK_SAVE; return best_len; #ifdef ONIG_DEBUG stack_error: STACK_SAVE; return ONIGERR_STACK_BUG; #endif bytecode_error: STACK_SAVE; return ONIGERR_UNDEFINED_BYTECODE; unexpected_bytecode_error: STACK_SAVE; return ONIGERR_UNEXPECTED_BYTECODE; } static UChar* slow_search(OnigEncoding enc, UChar* target, UChar* target_end, const UChar* text, const UChar* text_end, UChar* text_range) { UChar *t, *p, *s, *end; end = (UChar* )text_end; end -= target_end - target - 1; if (end > text_range) end = text_range; s = (UChar* )text; while (s < end) { if (*s == *target) { p = s + 1; t = target + 1; while (t < target_end) { if (*t != *p++) break; t++; } if (t == target_end) return s; } s += enclen(enc, s); } return (UChar* )NULL; } static int str_lower_case_match(OnigEncoding enc, int case_fold_flag, const UChar* t, const UChar* tend, const UChar* p, const UChar* end) { int lowlen; UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN]; while (t < tend) { lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf); q = lowbuf; while (lowlen > 0) { if (*t++ != *q++) return 0; lowlen--; } } return 1; } static UChar* slow_search_ic(OnigEncoding enc, int case_fold_flag, UChar* target, UChar* target_end, const UChar* text, const UChar* text_end, UChar* text_range) { UChar *s, *end; end = (UChar* )text_end; end -= target_end - target - 1; if (end > text_range) end = text_range; s = (UChar* )text; while (s < end) { if (str_lower_case_match(enc, case_fold_flag, target, target_end, s, text_end)) return s; s += enclen(enc, s); } return (UChar* )NULL; } static UChar* slow_search_backward(OnigEncoding enc, UChar* target, UChar* target_end, const UChar* text, const UChar* adjust_text, const UChar* text_end, const UChar* text_start) { UChar *t, *p, *s; s = (UChar* )text_end; s -= (target_end - target); if (s > text_start) s = (UChar* )text_start; else s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s); while (s >= text) { if (*s == *target) { p = s + 1; t = target + 1; while (t < target_end) { if (*t != *p++) break; t++; } if (t == target_end) return s; } s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s); } return (UChar* )NULL; } static UChar* slow_search_backward_ic(OnigEncoding enc, int case_fold_flag, UChar* target, UChar* target_end, const UChar* text, const UChar* adjust_text, const UChar* text_end, const UChar* text_start) { UChar *s; s = (UChar* )text_end; s -= (target_end - target); if (s > text_start) s = (UChar* )text_start; else s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s); while (s >= text) { if (str_lower_case_match(enc, case_fold_flag, target, target_end, s, text_end)) return s; s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s); } return (UChar* )NULL; } static UChar* bm_search_notrev(regex_t* reg, const UChar* target, const UChar* target_end, const UChar* text, const UChar* text_end, const UChar* text_range) { const UChar *s, *se, *t, *p, *end; const UChar *tail; int skip, tlen1; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "bm_search_notrev: text: %d, text_end: %d, text_range: %d\n", (int )text, (int )text_end, (int )text_range); #endif tail = target_end - 1; tlen1 = tail - target; end = text_range; if (end + tlen1 > text_end) end = text_end - tlen1; s = text; if (IS_NULL(reg->int_map)) { while (s < end) { p = se = s + tlen1; t = tail; while (*p == *t) { if (t == target) return (UChar* )s; p--; t--; } skip = reg->map[*se]; t = s; do { s += enclen(reg->enc, s); } while ((s - t) < skip && s < end); } } else { while (s < end) { p = se = s + tlen1; t = tail; while (*p == *t) { if (t == target) return (UChar* )s; p--; t--; } skip = reg->int_map[*se]; t = s; do { s += enclen(reg->enc, s); } while ((s - t) < skip && s < end); } } return (UChar* )NULL; } static UChar* bm_search(regex_t* reg, const UChar* target, const UChar* target_end, const UChar* text, const UChar* text_end, const UChar* text_range) { const UChar *s, *t, *p, *end; const UChar *tail; end = text_range + (target_end - target) - 1; if (end > text_end) end = text_end; tail = target_end - 1; s = text + (target_end - target) - 1; if (IS_NULL(reg->int_map)) { while (s < end) { p = s; t = tail; while (*p == *t) { if (t == target) return (UChar* )p; p--; t--; } s += reg->map[*s]; } } else { /* see int_map[] */ while (s < end) { p = s; t = tail; while (*p == *t) { if (t == target) return (UChar* )p; p--; t--; } s += reg->int_map[*s]; } } return (UChar* )NULL; } #ifdef USE_INT_MAP_BACKWARD static int set_bm_backward_skip(UChar* s, UChar* end, OnigEncoding enc ARG_UNUSED, int** skip) { int i, len; if (IS_NULL(*skip)) { *skip = (int* )xmalloc(sizeof(int) * ONIG_CHAR_TABLE_SIZE); if (IS_NULL(*skip)) return ONIGERR_MEMORY; } len = end - s; for (i = 0; i < ONIG_CHAR_TABLE_SIZE; i++) (*skip)[i] = len; for (i = len - 1; i > 0; i--) (*skip)[s[i]] = i; return 0; } static UChar* bm_search_backward(regex_t* reg, const UChar* target, const UChar* target_end, const UChar* text, const UChar* adjust_text, const UChar* text_end, const UChar* text_start) { const UChar *s, *t, *p; s = text_end - (target_end - target); if (text_start < s) s = text_start; else s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s); while (s >= text) { p = s; t = target; while (t < target_end && *p == *t) { p++; t++; } if (t == target_end) return (UChar* )s; s -= reg->int_map_backward[*s]; s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s); } return (UChar* )NULL; } #endif static UChar* map_search(OnigEncoding enc, UChar map[], const UChar* text, const UChar* text_range) { const UChar *s = text; while (s < text_range) { if (map[*s]) return (UChar* )s; s += enclen(enc, s); } return (UChar* )NULL; } static UChar* map_search_backward(OnigEncoding enc, UChar map[], const UChar* text, const UChar* adjust_text, const UChar* text_start) { const UChar *s = text_start; while (s >= text) { if (map[*s]) return (UChar* )s; s = onigenc_get_prev_char_head(enc, adjust_text, s); } return (UChar* )NULL; } extern int onig_match(regex_t* reg, const UChar* str, const UChar* end, const UChar* at, OnigRegion* region, OnigOptionType option) { int r; UChar *prev; OnigMatchArg msa; MATCH_ARG_INIT(msa, reg, option, region, at); #ifdef USE_COMBINATION_EXPLOSION_CHECK { int offset = at - str; STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check); } #endif if (region #ifdef USE_POSIX_API_REGION_OPTION && !IS_POSIX_REGION(option) #endif ) { r = onig_region_resize_clear(region, reg->num_mem + 1); } else r = 0; if (r == 0) { if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) { if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) { r = ONIGERR_INVALID_WIDE_CHAR_VALUE; goto end; } } prev = (UChar* )onigenc_get_prev_char_head(reg->enc, str, at); r = match_at(reg, str, end, #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE end, #endif at, prev, &msa); } end: MATCH_ARG_FREE(msa); return r; } static int forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s, UChar* range, UChar** low, UChar** high, UChar** low_prev) { UChar *p, *pprev = (UChar* )NULL; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n", (int )str, (int )end, (int )s, (int )range); #endif p = s; if (reg->dmin > 0) { if (ONIGENC_IS_SINGLEBYTE(reg->enc)) { p += reg->dmin; } else { UChar *q = p + reg->dmin; while (p < q) p += enclen(reg->enc, p); } } retry: switch (reg->optimize) { case ONIG_OPTIMIZE_EXACT: p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_IC: p = slow_search_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM: p = bm_search(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_EXACT_BM_NOT_REV: p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range); break; case ONIG_OPTIMIZE_MAP: p = map_search(reg->enc, reg->map, p, range); break; } if (p && p < range) { if (p - reg->dmin < s) { retry_gate: pprev = p; p += enclen(reg->enc, p); goto retry; } if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCHOR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; } break; case ANCHOR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = (UChar* )onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) goto retry_gate; #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) goto retry_gate; break; } } if (reg->dmax == 0) { *low = p; if (low_prev) { if (*low > s) *low_prev = onigenc_get_prev_char_head(reg->enc, s, p); else *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), p); } } else { if (reg->dmax != ONIG_INFINITE_DISTANCE) { *low = p - reg->dmax; if (*low > s) { *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s, *low, (const UChar** )low_prev); if (low_prev && IS_NULL(*low_prev)) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : s), *low); } else { if (low_prev) *low_prev = onigenc_get_prev_char_head(reg->enc, (pprev ? pprev : str), *low); } } } /* no needs to adjust *high, *high is used as range check only */ *high = p - reg->dmin; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n", (int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax); #endif return 1; /* success */ } return 0; /* fail */ } #define BM_BACKWARD_SEARCH_LENGTH_THRESHOLD 100 static int backward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s, const UChar* range, UChar* adjrange, UChar** low, UChar** high) { UChar *p; range += reg->dmin; p = s; retry: switch (reg->optimize) { case ONIG_OPTIMIZE_EXACT: exact_method: p = slow_search_backward(reg->enc, reg->exact, reg->exact_end, range, adjrange, end, p); break; case ONIG_OPTIMIZE_EXACT_IC: p = slow_search_backward_ic(reg->enc, reg->case_fold_flag, reg->exact, reg->exact_end, range, adjrange, end, p); break; case ONIG_OPTIMIZE_EXACT_BM: case ONIG_OPTIMIZE_EXACT_BM_NOT_REV: #ifdef USE_INT_MAP_BACKWARD if (IS_NULL(reg->int_map_backward)) { int r; if (s - range < BM_BACKWARD_SEARCH_LENGTH_THRESHOLD) goto exact_method; r = set_bm_backward_skip(reg->exact, reg->exact_end, reg->enc, &(reg->int_map_backward)); if (r) return r; } p = bm_search_backward(reg, reg->exact, reg->exact_end, range, adjrange, end, p); #else goto exact_method; #endif break; case ONIG_OPTIMIZE_MAP: p = map_search_backward(reg->enc, reg->map, range, adjrange, p); break; } if (p) { if (reg->sub_anchor) { UChar* prev; switch (reg->sub_anchor) { case ANCHOR_BEGIN_LINE: if (!ON_STR_BEGIN(p)) { prev = onigenc_get_prev_char_head(reg->enc, str, p); if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } } break; case ANCHOR_END_LINE: if (ON_STR_END(p)) { #ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE prev = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(prev)) goto fail; if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) { p = prev; goto retry; } #endif } else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end) #ifdef USE_CRNL_AS_LINE_TERMINATOR && ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end) #endif ) { p = onigenc_get_prev_char_head(reg->enc, adjrange, p); if (IS_NULL(p)) goto fail; goto retry; } break; } } /* no needs to adjust *high, *high is used as range check only */ if (reg->dmax != ONIG_INFINITE_DISTANCE) { *low = p - reg->dmax; *high = p - reg->dmin; *high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high); } #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search_range: low: %d, high: %d\n", (int )(*low - str), (int )(*high - str)); #endif return 1; /* success */ } fail: #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "backward_search_range: fail.\n"); #endif return 0; /* fail */ } extern int onig_search(regex_t* reg, const UChar* str, const UChar* end, const UChar* start, const UChar* range, OnigRegion* region, OnigOptionType option) { int r; UChar *s, *prev; OnigMatchArg msa; const UChar *orig_start = start; #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE const UChar *orig_range = range; #endif #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "onig_search (entry point): str: %d, end: %d, start: %d, range: %d\n", (int )str, (int )(end - str), (int )(start - str), (int )(range - str)); #endif if (region #ifdef USE_POSIX_API_REGION_OPTION && !IS_POSIX_REGION(option) #endif ) { r = onig_region_resize_clear(region, reg->num_mem + 1); if (r) goto finish_no_msa; } if (start > end || start < str) goto mismatch_no_msa; if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) { if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) { r = ONIGERR_INVALID_WIDE_CHAR_VALUE; goto finish_no_msa; } } #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE #define MATCH_AND_RETURN_CHECK(upper_range) \ r = match_at(reg, str, end, (upper_range), s, prev, &msa); \ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ if (! IS_FIND_LONGEST(reg->options)) {\ goto match;\ }\ }\ else goto finish; /* error */ \ } #else #define MATCH_AND_RETURN_CHECK(upper_range) \ r = match_at(reg, str, end, (upper_range), s, prev, &msa); \ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ goto match;\ }\ else goto finish; /* error */ \ } #endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */ #else #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE #define MATCH_AND_RETURN_CHECK(none) \ r = match_at(reg, str, end, s, prev, &msa);\ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ if (! IS_FIND_LONGEST(reg->options)) {\ goto match;\ }\ }\ else goto finish; /* error */ \ } #else #define MATCH_AND_RETURN_CHECK(none) \ r = match_at(reg, str, end, s, prev, &msa);\ if (r != ONIG_MISMATCH) {\ if (r >= 0) {\ goto match;\ }\ else goto finish; /* error */ \ } #endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */ #endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */ /* anchor optimize: resume search range */ if (reg->anchor != 0 && str < end) { UChar *min_semi_end, *max_semi_end; if (reg->anchor & ANCHOR_BEGIN_POSITION) { /* search start-position only */ begin_position: if (range > start) range = start + 1; else range = start; } else if (reg->anchor & ANCHOR_BEGIN_BUF) { /* search str-position only */ if (range > start) { if (start != str) goto mismatch_no_msa; range = str + 1; } else { if (range <= str) { start = str; range = str; } else goto mismatch_no_msa; } } else if (reg->anchor & ANCHOR_END_BUF) { min_semi_end = max_semi_end = (UChar* )end; end_buf: if ((OnigLen )(max_semi_end - str) < reg->anchor_dmin) goto mismatch_no_msa; if (range > start) { if ((OnigLen )(min_semi_end - start) > reg->anchor_dmax) { start = min_semi_end - reg->anchor_dmax; if (start < end) start = onigenc_get_right_adjust_char_head(reg->enc, str, start); } if ((OnigLen )(max_semi_end - (range - 1)) < reg->anchor_dmin) { range = max_semi_end - reg->anchor_dmin + 1; } if (start > range) goto mismatch_no_msa; /* If start == range, match with empty at end. Backward search is used. */ } else { if ((OnigLen )(min_semi_end - range) > reg->anchor_dmax) { range = min_semi_end - reg->anchor_dmax; } if ((OnigLen )(max_semi_end - start) < reg->anchor_dmin) { start = max_semi_end - reg->anchor_dmin; start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start); } if (range > start) goto mismatch_no_msa; } } else if (reg->anchor & ANCHOR_SEMI_END_BUF) { UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1); max_semi_end = (UChar* )end; if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) { min_semi_end = pre_end; #ifdef USE_CRNL_AS_LINE_TERMINATOR pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1); if (IS_NOT_NULL(pre_end) && ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) { min_semi_end = pre_end; } #endif if (min_semi_end > str && start <= min_semi_end) { goto end_buf; } } else { min_semi_end = (UChar* )end; goto end_buf; } } else if ((reg->anchor & ANCHOR_ANYCHAR_STAR_ML)) { goto begin_position; } } else if (str == end) { /* empty string */ static const UChar* address_for_empty_string = (UChar* )""; #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "onig_search: empty string.\n"); #endif if (reg->threshold_len == 0) { start = end = str = address_for_empty_string; s = (UChar* )start; prev = (UChar* )NULL; MATCH_ARG_INIT(msa, reg, option, region, start); #ifdef USE_COMBINATION_EXPLOSION_CHECK msa.state_check_buff = (void* )0; msa.state_check_buff_size = 0; /* NO NEED, for valgrind */ #endif MATCH_AND_RETURN_CHECK(end); goto mismatch; } goto mismatch_no_msa; } #ifdef ONIG_DEBUG_SEARCH fprintf(stderr, "onig_search(apply anchor): end: %d, start: %d, range: %d\n", (int )(end - str), (int )(start - str), (int )(range - str)); #endif MATCH_ARG_INIT(msa, reg, option, region, orig_start); #ifdef USE_COMBINATION_EXPLOSION_CHECK { int offset = (MIN(start, range) - str); STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check); } #endif s = (UChar* )start; if (range > start) { /* forward search */ if (s > str) prev = onigenc_get_prev_char_head(reg->enc, str, s); else prev = (UChar* )NULL; if (reg->optimize != ONIG_OPTIMIZE_NONE) { UChar *sch_range, *low, *high, *low_prev; sch_range = (UChar* )range; if (reg->dmax != 0) { if (reg->dmax == ONIG_INFINITE_DISTANCE) sch_range = (UChar* )end; else { sch_range += reg->dmax; if (sch_range > end) sch_range = (UChar* )end; } } if ((end - start) < reg->threshold_len) goto mismatch; if (reg->dmax != ONIG_INFINITE_DISTANCE) { do { if (! forward_search_range(reg, str, end, s, sch_range, &low, &high, &low_prev)) goto mismatch; if (s < low) { s = low; prev = low_prev; } while (s <= high) { MATCH_AND_RETURN_CHECK(orig_range); prev = s; s += enclen(reg->enc, s); } } while (s < range); goto mismatch; } else { /* check only. */ if (! forward_search_range(reg, str, end, s, sch_range, &low, &high, (UChar** )NULL)) goto mismatch; if ((reg->anchor & ANCHOR_ANYCHAR_STAR) != 0) { do { MATCH_AND_RETURN_CHECK(orig_range); prev = s; s += enclen(reg->enc, s); if ((reg->anchor & (ANCHOR_LOOK_BEHIND | ANCHOR_PREC_READ_NOT)) == 0) { while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) { prev = s; s += enclen(reg->enc, s); } } } while (s < range); goto mismatch; } } } do { MATCH_AND_RETURN_CHECK(orig_range); prev = s; s += enclen(reg->enc, s); } while (s < range); if (s == range) { /* because empty match with /$/. */ MATCH_AND_RETURN_CHECK(orig_range); } } else { /* backward search */ #ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE if (orig_start < end) orig_start += enclen(reg->enc, orig_start); /* is upper range */ #endif if (reg->optimize != ONIG_OPTIMIZE_NONE) { UChar *low, *high, *adjrange, *sch_start; if (range < end) adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range); else adjrange = (UChar* )end; if (reg->dmax != ONIG_INFINITE_DISTANCE && (end - range) >= reg->threshold_len) { do { sch_start = s + reg->dmax; if (sch_start > end) sch_start = (UChar* )end; if (backward_search_range(reg, str, end, sch_start, range, adjrange, &low, &high) <= 0) goto mismatch; if (s > high) s = high; while (s >= low) { prev = onigenc_get_prev_char_head(reg->enc, str, s); MATCH_AND_RETURN_CHECK(orig_start); s = prev; } } while (s >= range); goto mismatch; } else { /* check only. */ if ((end - range) < reg->threshold_len) goto mismatch; sch_start = s; if (reg->dmax != 0) { if (reg->dmax == ONIG_INFINITE_DISTANCE) sch_start = (UChar* )end; else { sch_start += reg->dmax; if (sch_start > end) sch_start = (UChar* )end; else sch_start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, start, sch_start); } } if (backward_search_range(reg, str, end, sch_start, range, adjrange, &low, &high) <= 0) goto mismatch; } } do { prev = onigenc_get_prev_char_head(reg->enc, str, s); MATCH_AND_RETURN_CHECK(orig_start); s = prev; } while (s >= range); } mismatch: #ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE if (IS_FIND_LONGEST(reg->options)) { if (msa.best_len >= 0) { s = msa.best_s; goto match; } } #endif r = ONIG_MISMATCH; finish: MATCH_ARG_FREE(msa); /* If result is mismatch and no FIND_NOT_EMPTY option, then the region is not set in match_at(). */ if (IS_FIND_NOT_EMPTY(reg->options) && region #ifdef USE_POSIX_API_REGION_OPTION && !IS_POSIX_REGION(option) #endif ) { onig_region_clear(region); } #ifdef ONIG_DEBUG if (r != ONIG_MISMATCH) fprintf(stderr, "onig_search: error %d\n", r); #endif return r; mismatch_no_msa: r = ONIG_MISMATCH; finish_no_msa: #ifdef ONIG_DEBUG if (r != ONIG_MISMATCH) fprintf(stderr, "onig_search: error %d\n", r); #endif return r; match: MATCH_ARG_FREE(msa); return s - str; } extern int onig_scan(regex_t* reg, const UChar* str, const UChar* end, OnigRegion* region, OnigOptionType option, int (*scan_callback)(int, int, OnigRegion*, void*), void* callback_arg) { int r; int n; int rs; const UChar* start; if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) { if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; ONIG_OPTION_OFF(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING); } n = 0; start = str; while (1) { r = onig_search(reg, str, end, start, end, region, option); if (r >= 0) { rs = scan_callback(n, r, region, callback_arg); n++; if (rs != 0) return rs; if (region->end[0] == start - str) start++; else start = str + region->end[0]; if (start > end) break; } else if (r == ONIG_MISMATCH) { break; } else { /* error */ return r; } } return n; } extern OnigEncoding onig_get_encoding(regex_t* reg) { return reg->enc; } extern OnigOptionType onig_get_options(regex_t* reg) { return reg->options; } extern OnigCaseFoldType onig_get_case_fold_flag(regex_t* reg) { return reg->case_fold_flag; } extern OnigSyntaxType* onig_get_syntax(regex_t* reg) { return reg->syntax; } extern int onig_number_of_captures(regex_t* reg) { return reg->num_mem; } extern int onig_number_of_capture_histories(regex_t* reg) { #ifdef USE_CAPTURE_HISTORY int i, n; n = 0; for (i = 0; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) { if (BIT_STATUS_AT(reg->capture_history, i) != 0) n++; } return n; #else return 0; #endif } extern void onig_copy_encoding(OnigEncoding to, OnigEncoding from) { *to = *from; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3372_0
crossvul-cpp_data_good_372_0
/* * Copyright 2013-2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bson/bson-iter.h" #include "bson/bson-config.h" #include "bson/bson-decimal128.h" #include "bson-types.h" #define ITER_TYPE(i) ((bson_type_t) * ((i)->raw + (i)->type)) /* *-------------------------------------------------------------------------- * * bson_iter_init -- * * Initializes @iter to be used to iterate @bson. * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init (bson_iter_t *iter, /* OUT */ const bson_t *bson) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); if (BSON_UNLIKELY (bson->len < 5)) { memset (iter, 0, sizeof *iter); return false; } iter->raw = bson_get_data (bson); iter->len = bson->len; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_from_data -- * * Initializes @iter to be used to iterate @data of length @length * * Returns: * true if bson_iter_t was initialized. otherwise false. * * Side effects: * @iter is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_init_from_data (bson_iter_t *iter, /* OUT */ const uint8_t *data, /* IN */ size_t length) /* IN */ { uint32_t len_le; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } memcpy (&len_le, data, sizeof (len_le)); if (BSON_UNLIKELY ((size_t) BSON_UINT32_FROM_LE (len_le) != length)) { memset (iter, 0, sizeof *iter); return false; } if (BSON_UNLIKELY (data[length - 1])) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = length; iter->off = 0; iter->type = 0; iter->key = 0; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; iter->next_off = 4; iter->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_recurse -- * * Creates a new sub-iter looking at the document or array that @iter * is currently pointing at. * * Returns: * true if successful and @child was initialized. * * Side effects: * @child is initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_recurse (const bson_iter_t *iter, /* IN */ bson_iter_t *child) /* OUT */ { const uint8_t *data = NULL; uint32_t len = 0; BSON_ASSERT (iter); BSON_ASSERT (child); if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { bson_iter_document (iter, &len, &data); } else if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { bson_iter_array (iter, &len, &data); } else { return false; } child->raw = data; child->len = len; child->off = 0; child->type = 0; child->key = 0; child->d1 = 0; child->d2 = 0; child->d3 = 0; child->d4 = 0; child->next_off = 4; child->err_off = 0; return true; } /* *-------------------------------------------------------------------------- * * bson_iter_init_find -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_w_len -- * * Initializes a #bson_iter_t and moves the iter to the first field * matching @key. * * Returns: * true if the field named @key was found; otherwise false. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_w_len (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key, /* IN */ int keylen) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_w_len (iter, key, keylen); } /* *-------------------------------------------------------------------------- * * bson_iter_init_find_case -- * * A case-insensitive version of bson_iter_init_find(). * * Returns: * true if the field was found and @iter is observing that field. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_init_find_case (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_case (iter, key); } /* *-------------------------------------------------------------------------- * * bson_iter_find_w_len -- * * Searches through @iter starting from the current position for a key * matching @key. @keylen indicates the length of @key, or -1 to * determine the length with strlen(). * * Returns: * true if the field @key was found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_w_len (bson_iter_t *iter, /* INOUT */ const char *key, /* IN */ int keylen) /* IN */ { const char *ikey; if (keylen < 0) { keylen = (int) strlen (key); } while (bson_iter_next (iter)) { ikey = bson_iter_key (iter); if ((0 == strncmp (key, ikey, keylen)) && (ikey[keylen] == '\0')) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-sensitive search meaning "KEY" and * "key" would NOT match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); return bson_iter_find_w_len (iter, key, -1); } /* *-------------------------------------------------------------------------- * * bson_iter_find_case -- * * Searches through @iter starting from the current position for a key * matching @key. This is a case-insensitive search meaning "KEY" and * "key" would match. * * Returns: * true if @key is found. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_find_case (bson_iter_t *iter, /* INOUT */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (key); while (bson_iter_next (iter)) { if (!bson_strcasecmp (key, bson_iter_key (iter))) { return true; } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_find_descendant -- * * Locates a descendant using the "parent.child.key" notation. This * operates similar to bson_iter_find() except that it can recurse * into children documents using the dot notation. * * Returns: * true if the descendant was found and @descendant was initialized. * * Side effects: * @descendant may be initialized. * *-------------------------------------------------------------------------- */ bool bson_iter_find_descendant (bson_iter_t *iter, /* INOUT */ const char *dotkey, /* IN */ bson_iter_t *descendant) /* OUT */ { bson_iter_t tmp; const char *dot; size_t sublen; BSON_ASSERT (iter); BSON_ASSERT (dotkey); BSON_ASSERT (descendant); if ((dot = strchr (dotkey, '.'))) { sublen = dot - dotkey; } else { sublen = strlen (dotkey); } if (bson_iter_find_w_len (iter, dotkey, (int) sublen)) { if (!dot) { *descendant = *iter; return true; } if (BSON_ITER_HOLDS_DOCUMENT (iter) || BSON_ITER_HOLDS_ARRAY (iter)) { if (bson_iter_recurse (iter, &tmp)) { return bson_iter_find_descendant (&tmp, dot + 1, descendant); } } } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_key -- * * Retrieves the key of the current field. The resulting key is valid * while @iter is valid. * * Returns: * A string that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_key (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); return bson_iter_key_unsafe (iter); } /* *-------------------------------------------------------------------------- * * bson_iter_type -- * * Retrieves the type of the current field. It may be useful to check * the type using the BSON_ITER_HOLDS_*() macros. * * Returns: * A bson_type_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bson_type_t bson_iter_type (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (iter->raw); BSON_ASSERT (iter->len); return bson_iter_type_unsafe (iter); } /* *-------------------------------------------------------------------------- * * _bson_iter_next_internal -- * * Internal function to advance @iter to the next field and retrieve * the key and BSON type before error-checking. @next_keylen is * the key length of the next field being iterated or 0 if this is * not known. * * Return: * true if an element was decoded, else false. * * Side effects: * @key and @bson_type are set. * * If the return value is false: * - @iter is invalidated: @iter->raw is NULLed * - @unsupported is set to true if the bson type is unsupported * - otherwise if the BSON is corrupt, @iter->err_off is nonzero * - otherwise @bson_type is set to BSON_TYPE_EOD * *-------------------------------------------------------------------------- */ static bool _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ uint32_t next_keylen, /* IN */ const char **key, /* OUT */ uint32_t *bson_type, /* OUT */ bool *unsupported) /* OUT */ { const uint8_t *data; uint32_t o; unsigned int len; BSON_ASSERT (iter); *unsupported = false; if (!iter->raw) { *key = NULL; *bson_type = BSON_TYPE_EOD; return false; } data = iter->raw; len = iter->len; iter->off = iter->next_off; iter->type = iter->off; iter->key = iter->off + 1; iter->d1 = 0; iter->d2 = 0; iter->d3 = 0; iter->d4 = 0; if (next_keylen == 0) { /* iterate from start to end of NULL-terminated key string */ for (o = iter->key; o < len; o++) { if (!data[o]) { iter->d1 = ++o; goto fill_data_fields; } } } else { o = iter->key + next_keylen + 1; iter->d1 = o; goto fill_data_fields; } goto mark_invalid; fill_data_fields: *key = bson_iter_key_unsafe (iter); *bson_type = ITER_TYPE (iter); switch (*bson_type) { case BSON_TYPE_DATE_TIME: case BSON_TYPE_DOUBLE: case BSON_TYPE_INT64: case BSON_TYPE_TIMESTAMP: iter->next_off = o + 8; break; case BSON_TYPE_CODE: case BSON_TYPE_SYMBOL: case BSON_TYPE_UTF8: { uint32_t l; if ((o + 4) >= len) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l > (len - (o + 4))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 4 + l; /* * Make sure the string length includes the NUL byte. */ if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) { iter->err_off = o; goto mark_invalid; } /* * Make sure the last byte is a NUL byte. */ if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) { iter->err_off = o + 4 + l - 1; goto mark_invalid; } } break; case BSON_TYPE_BINARY: { bson_subtype_t subtype; uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 5; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l >= (len - o - 4)) { iter->err_off = o; goto mark_invalid; } subtype = *(iter->raw + iter->d2); if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { int32_t binary_len; if (l < 4) { iter->err_off = o; goto mark_invalid; } /* subtype 2 has a redundant length header in the data */ memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len)); binary_len = BSON_UINT32_FROM_LE (binary_len); if (binary_len + 4 != l) { iter->err_off = iter->d3; goto mark_invalid; } } iter->next_off = o + 5 + l; } break; case BSON_TYPE_ARRAY: case BSON_TYPE_DOCUMENT: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l > len) || (l > (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; } break; case BSON_TYPE_OID: iter->next_off = o + 12; break; case BSON_TYPE_BOOL: { char val; if (iter->d1 >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&val, iter->raw + iter->d1, 1); if (val != 0x00 && val != 0x01) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_REGEX: { bool eor = false; bool eoo = false; for (; o < len; o++) { if (!data[o]) { iter->d2 = ++o; eor = true; break; } } if (!eor) { iter->err_off = iter->next_off; goto mark_invalid; } for (; o < len; o++) { if (!data[o]) { eoo = true; break; } } if (!eoo) { iter->err_off = iter->next_off; goto mark_invalid; } iter->next_off = o + 1; } break; case BSON_TYPE_DBPOINTER: { uint32_t l; if (o >= (len - 4)) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); /* Check valid string length. l counts '\0' but not 4 bytes for itself. */ if (l == 0 || l > (len - o - 4)) { iter->err_off = o; goto mark_invalid; } if (*(iter->raw + o + l + 3)) { /* not null terminated */ iter->err_off = o + l + 3; goto mark_invalid; } iter->d3 = o + 4 + l; iter->next_off = o + 4 + l + 12; } break; case BSON_TYPE_CODEWSCOPE: { uint32_t l; uint32_t doclen; if ((len < 19) || (o >= (len - 14))) { iter->err_off = o; goto mark_invalid; } iter->d2 = o + 4; iter->d3 = o + 8; memcpy (&l, iter->raw + iter->d1, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if ((l < 14) || (l >= (len - o))) { iter->err_off = o; goto mark_invalid; } iter->next_off = o + l; if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } memcpy (&l, iter->raw + iter->d2, sizeof (l)); l = BSON_UINT32_FROM_LE (l); if (l == 0 || l >= (len - o - 4 - 4)) { iter->err_off = o; goto mark_invalid; } if ((o + 4 + 4 + l + 4) >= iter->next_off) { iter->err_off = o + 4; goto mark_invalid; } iter->d4 = o + 4 + 4 + l; memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen)); doclen = BSON_UINT32_FROM_LE (doclen); if ((o + 4 + 4 + l + doclen) != iter->next_off) { iter->err_off = o + 4 + 4 + l; goto mark_invalid; } } break; case BSON_TYPE_INT32: iter->next_off = o + 4; break; case BSON_TYPE_DECIMAL128: iter->next_off = o + 16; break; case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: iter->next_off = o; break; default: *unsupported = true; /* FALL THROUGH */ case BSON_TYPE_EOD: iter->err_off = o; goto mark_invalid; } /* * Check to see if any of the field locations would overflow the * current BSON buffer. If so, set the error location to the offset * of where the field starts. */ if (iter->next_off >= len) { iter->err_off = o; goto mark_invalid; } iter->err_off = 0; return true; mark_invalid: iter->raw = NULL; iter->len = 0; iter->next_off = 0; return false; } /* *-------------------------------------------------------------------------- * * bson_iter_next -- * * Advances @iter to the next field of the underlying BSON document. * If all fields have been exhausted, then %false is returned. * * It is a programming error to use @iter after this function has * returned false. * * Returns: * true if the iter was advanced to the next record. * otherwise false and @iter should be considered invalid. * * Side effects: * @iter may be invalidated. * *-------------------------------------------------------------------------- */ bool bson_iter_next (bson_iter_t *iter) /* INOUT */ { uint32_t bson_type; const char *key; bool unsupported; return _bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported); } /* *-------------------------------------------------------------------------- * * bson_iter_binary -- * * Retrieves the BSON_TYPE_BINARY field. The subtype is stored in * @subtype. The length of @binary in bytes is stored in @binary_len. * * @binary should not be modified or freed and is only valid while * @iter's bson_t is valid and unmodified. * * Parameters: * @iter: A bson_iter_t * @subtype: A location for the binary subtype. * @binary_len: A location for the length of @binary. * @binary: A location for a pointer to the binary data. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_binary (const bson_iter_t *iter, /* IN */ bson_subtype_t *subtype, /* OUT */ uint32_t *binary_len, /* OUT */ const uint8_t **binary) /* OUT */ { bson_subtype_t backup; BSON_ASSERT (iter); BSON_ASSERT (!binary || binary_len); if (ITER_TYPE (iter) == BSON_TYPE_BINARY) { if (!subtype) { subtype = &backup; } *subtype = (bson_subtype_t) * (iter->raw + iter->d2); if (binary) { memcpy (binary_len, (iter->raw + iter->d1), sizeof (*binary_len)); *binary_len = BSON_UINT32_FROM_LE (*binary_len); *binary = iter->raw + iter->d3; if (*subtype == BSON_SUBTYPE_BINARY_DEPRECATED) { *binary_len -= sizeof (int32_t); *binary += sizeof (int32_t); } } return; } if (binary) { *binary = NULL; } if (binary_len) { *binary_len = 0; } if (subtype) { *subtype = BSON_SUBTYPE_BINARY; } } /* *-------------------------------------------------------------------------- * * bson_iter_bool -- * * Retrieves the current field of type BSON_TYPE_BOOL. * * Returns: * true or false, dependent on bson document. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { return bson_iter_bool_unsafe (iter); } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_as_bool -- * * If @iter is on a boolean field, returns the boolean. If it is on a * non-boolean field such as int32, int64, or double, it will convert * the value to a boolean. * * Zero is false, and non-zero is true. * * Returns: * true or false, dependent on field type. * * Side effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_as_bool (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return !(bson_iter_double (iter) == 0.0); case BSON_TYPE_INT64: return !(bson_iter_int64 (iter) == 0); case BSON_TYPE_INT32: return !(bson_iter_int32 (iter) == 0); case BSON_TYPE_UTF8: return true; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: return false; default: return true; } } /* *-------------------------------------------------------------------------- * * bson_iter_double -- * * Retrieves the current field of type BSON_TYPE_DOUBLE. * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { return bson_iter_double_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_double -- * * If @iter is on a field of type BSON_TYPE_DOUBLE, * returns the double. If it is on an integer field * such as int32, int64, or bool, it will convert * the value to a double. * * * Returns: * A double. * * Side effects: * None. * *-------------------------------------------------------------------------- */ double bson_iter_as_double (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (double) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return bson_iter_double (iter); case BSON_TYPE_INT32: return (double) bson_iter_int32 (iter); case BSON_TYPE_INT64: return (double) bson_iter_int64 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_int32 -- * * Retrieves the value of the field of type BSON_TYPE_INT32. * * Returns: * A 32-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int32_t bson_iter_int32 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { return bson_iter_int32_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_int64 -- * * Retrieves a 64-bit signed integer for the current BSON_TYPE_INT64 * field. * * Returns: * A 64-bit signed integer. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_as_int64 -- * * If @iter is not an int64 field, it will try to convert the value to * an int64. Such field types include: * * - bool * - double * - int32 * * Returns: * An int64_t. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_as_int64 (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); switch ((int) ITER_TYPE (iter)) { case BSON_TYPE_BOOL: return (int64_t) bson_iter_bool (iter); case BSON_TYPE_DOUBLE: return (int64_t) bson_iter_double (iter); case BSON_TYPE_INT64: return bson_iter_int64 (iter); case BSON_TYPE_INT32: return (int64_t) bson_iter_int32 (iter); default: return 0; } } /* *-------------------------------------------------------------------------- * * bson_iter_decimal128 -- * * This function retrieves the current field of type *%BSON_TYPE_DECIMAL128. * The result is valid while @iter is valid, and is stored in @dec. * * Returns: * * True on success, false on failure. * * Side Effects: * None. * *-------------------------------------------------------------------------- */ bool bson_iter_decimal128 (const bson_iter_t *iter, /* IN */ bson_decimal128_t *dec) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { bson_iter_decimal128_unsafe (iter, dec); return true; } return false; } /* *-------------------------------------------------------------------------- * * bson_iter_oid -- * * Retrieves the current field of type %BSON_TYPE_OID. The result is * valid while @iter is valid. * * Returns: * A bson_oid_t that should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_oid_t * bson_iter_oid (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { return bson_iter_oid_unsafe (iter); } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_regex -- * * Fetches the current field from the iter which should be of type * BSON_TYPE_REGEX. * * Returns: * Regex from @iter. This should not be modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_regex (const bson_iter_t *iter, /* IN */ const char **options) /* IN */ { const char *ret = NULL; const char *ret_options = NULL; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_REGEX) { ret = (const char *) (iter->raw + iter->d1); ret_options = (const char *) (iter->raw + iter->d2); } if (options) { *options = ret_options; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_utf8 -- * * Retrieves the current field of type %BSON_TYPE_UTF8 as a UTF-8 * encoded string. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the string. * * Returns: * A string that should not be modified or freed. * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ const char * bson_iter_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_UTF8) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dup_utf8 -- * * Copies the current UTF-8 element into a newly allocated string. The * string should be freed using bson_free() when the caller is * finished with it. * * Returns: * A newly allocated char* that should be freed with bson_free(). * * Side effects: * @length will be set to the result strings length if non-NULL. * *-------------------------------------------------------------------------- */ char * bson_iter_dup_utf8 (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { uint32_t local_length = 0; const char *str; char *ret = NULL; BSON_ASSERT (iter); if ((str = bson_iter_utf8 (iter, &local_length))) { ret = bson_malloc0 (local_length + 1); memcpy (ret, str, local_length); ret[local_length] = '\0'; } if (length) { *length = local_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_code -- * * Retrieves the current field of type %BSON_TYPE_CODE. The length of * the resulting string is stored in @length. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the code length. * * Returns: * A NUL-terminated string containing the code which should not be * modified or freed. * * Side effects: * None. * *-------------------------------------------------------------------------- */ const char * bson_iter_code (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODE) { if (length) { *length = bson_iter_utf8_len_unsafe (iter); } return (const char *) (iter->raw + iter->d2); } if (length) { *length = 0; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_codewscope -- * * Similar to bson_iter_code() but with a scope associated encoded as * a BSON document. @scope should not be modified or freed. It is * valid while @iter is valid. * * Parameters: * @iter: A #bson_iter_t. * @length: A location for the length of resulting string. * @scope_len: A location for the length of @scope. * @scope: A location for the scope encoded as BSON. * * Returns: * A NUL-terminated string that should not be modified or freed. * * Side effects: * @length is set to the resulting string length in bytes. * @scope_len is set to the length of @scope in bytes. * @scope is set to the scope documents buffer which can be * turned into a bson document with bson_init_static(). * *-------------------------------------------------------------------------- */ const char * bson_iter_codewscope (const bson_iter_t *iter, /* IN */ uint32_t *length, /* OUT */ uint32_t *scope_len, /* OUT */ const uint8_t **scope) /* OUT */ { uint32_t len; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODEWSCOPE) { if (length) { memcpy (&len, iter->raw + iter->d2, sizeof (len)); /* The string length was checked > 0 in _bson_iter_next_internal. */ len = BSON_UINT32_FROM_LE (len); BSON_ASSERT (len > 0); *length = len - 1; } memcpy (&len, iter->raw + iter->d4, sizeof (len)); *scope_len = BSON_UINT32_FROM_LE (len); *scope = iter->raw + iter->d4; return (const char *) (iter->raw + iter->d3); } if (length) { *length = 0; } if (scope_len) { *scope_len = 0; } if (scope) { *scope = NULL; } return NULL; } /* *-------------------------------------------------------------------------- * * bson_iter_dbpointer -- * * Retrieves a BSON_TYPE_DBPOINTER field. @collection_len will be set * to the length of the collection name. The collection name will be * placed into @collection. The oid will be placed into @oid. * * @collection and @oid should not be modified. * * Parameters: * @iter: A #bson_iter_t. * @collection_len: A location for the length of @collection. * @collection: A location for the collection name. * @oid: A location for the oid. * * Returns: * None. * * Side effects: * @collection_len is set to the length of @collection in bytes * excluding the null byte. * @collection is set to the collection name, including a terminating * null byte. * @oid is initialized with the oid. * *-------------------------------------------------------------------------- */ void bson_iter_dbpointer (const bson_iter_t *iter, /* IN */ uint32_t *collection_len, /* OUT */ const char **collection, /* OUT */ const bson_oid_t **oid) /* OUT */ { BSON_ASSERT (iter); if (collection) { *collection = NULL; } if (oid) { *oid = NULL; } if (ITER_TYPE (iter) == BSON_TYPE_DBPOINTER) { if (collection_len) { memcpy ( collection_len, (iter->raw + iter->d1), sizeof (*collection_len)); *collection_len = BSON_UINT32_FROM_LE (*collection_len); if ((*collection_len) > 0) { (*collection_len)--; } } if (collection) { *collection = (const char *) (iter->raw + iter->d2); } if (oid) { *oid = (const bson_oid_t *) (iter->raw + iter->d3); } } } /* *-------------------------------------------------------------------------- * * bson_iter_symbol -- * * Retrieves the symbol of the current field of type BSON_TYPE_SYMBOL. * * Parameters: * @iter: A bson_iter_t. * @length: A location for the length of the symbol. * * Returns: * A string containing the symbol as UTF-8. The value should not be * modified or freed. * * Side effects: * @length is set to the resulting strings length in bytes, * excluding the null byte. * *-------------------------------------------------------------------------- */ const char * bson_iter_symbol (const bson_iter_t *iter, /* IN */ uint32_t *length) /* OUT */ { const char *ret = NULL; uint32_t ret_length = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_SYMBOL) { ret = (const char *) (iter->raw + iter->d2); ret_length = bson_iter_utf8_len_unsafe (iter); } if (length) { *length = ret_length; } return ret; } /* *-------------------------------------------------------------------------- * * bson_iter_date_time -- * * Fetches the number of milliseconds elapsed since the UNIX epoch. * This value can be negative as times before 1970 are valid. * * Returns: * A signed 64-bit integer containing the number of milliseconds. * * Side effects: * None. * *-------------------------------------------------------------------------- */ int64_t bson_iter_date_time (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_int64_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_time_t -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME as a * time_t. * * Returns: * A #time_t of the number of seconds since UNIX epoch in UTC. * * Side effects: * None. * *-------------------------------------------------------------------------- */ time_t bson_iter_time_t (const bson_iter_t *iter) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { return bson_iter_time_t_unsafe (iter); } return 0; } /* *-------------------------------------------------------------------------- * * bson_iter_timestamp -- * * Fetches the current field if it is a BSON_TYPE_TIMESTAMP. * * Parameters: * @iter: A #bson_iter_t. * @timestamp: a location for the timestamp. * @increment: A location for the increment. * * Returns: * None. * * Side effects: * @timestamp is initialized. * @increment is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timestamp (const bson_iter_t *iter, /* IN */ uint32_t *timestamp, /* OUT */ uint32_t *increment) /* OUT */ { uint64_t encoded; uint32_t ret_timestamp = 0; uint32_t ret_increment = 0; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { memcpy (&encoded, iter->raw + iter->d1, sizeof (encoded)); encoded = BSON_UINT64_FROM_LE (encoded); ret_timestamp = (encoded >> 32) & 0xFFFFFFFF; ret_increment = encoded & 0xFFFFFFFF; } if (timestamp) { *timestamp = ret_timestamp; } if (increment) { *increment = ret_increment; } } /* *-------------------------------------------------------------------------- * * bson_iter_timeval -- * * Retrieves the current field of type BSON_TYPE_DATE_TIME and stores * it into the struct timeval provided. tv->tv_sec is set to the * number of seconds since the UNIX epoch in UTC. * * Since BSON_TYPE_DATE_TIME does not support fractions of a second, * tv->tv_usec will always be set to zero. * * Returns: * None. * * Side effects: * @tv is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_timeval (const bson_iter_t *iter, /* IN */ struct timeval *tv) /* OUT */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { bson_iter_timeval_unsafe (iter, tv); return; } memset (tv, 0, sizeof *tv); } /** * bson_iter_document: * @iter: a bson_iter_t. * @document_len: A location for the document length. * @document: A location for a pointer to the document buffer. * */ /* *-------------------------------------------------------------------------- * * bson_iter_document -- * * Retrieves the data to the document BSON structure and stores the * length of the document buffer in @document_len and the document * buffer in @document. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_document(iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the bson_t structure as no data can be * modified in the process of its use (as it is static/const). * * Returns: * None. * * Side effects: * @document_len is initialized. * @document is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_document (const bson_iter_t *iter, /* IN */ uint32_t *document_len, /* OUT */ const uint8_t **document) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (document_len); BSON_ASSERT (document); *document = NULL; *document_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_DOCUMENT) { memcpy (document_len, (iter->raw + iter->d1), sizeof (*document_len)); *document_len = BSON_UINT32_FROM_LE (*document_len); *document = (iter->raw + iter->d1); } } /** * bson_iter_array: * @iter: a #bson_iter_t. * @array_len: A location for the array length. * @array: A location for a pointer to the array buffer. */ /* *-------------------------------------------------------------------------- * * bson_iter_array -- * * Retrieves the data to the array BSON structure and stores the * length of the array buffer in @array_len and the array buffer in * @array. * * If you would like to iterate over the child contents, you might * consider creating a bson_t on the stack such as the following. It * allows you to call functions taking a const bson_t* only. * * bson_t b; * uint32_t len; * const uint8_t *data; * * bson_iter_array (iter, &len, &data); * * if (bson_init_static (&b, data, len)) { * ... * } * * There is no need to cleanup the #bson_t structure as no data can be * modified in the process of its use. * * Returns: * None. * * Side effects: * @array_len is initialized. * @array is initialized. * *-------------------------------------------------------------------------- */ void bson_iter_array (const bson_iter_t *iter, /* IN */ uint32_t *array_len, /* OUT */ const uint8_t **array) /* OUT */ { BSON_ASSERT (iter); BSON_ASSERT (array_len); BSON_ASSERT (array); *array = NULL; *array_len = 0; if (ITER_TYPE (iter) == BSON_TYPE_ARRAY) { memcpy (array_len, (iter->raw + iter->d1), sizeof (*array_len)); *array_len = BSON_UINT32_FROM_LE (*array_len); *array = (iter->raw + iter->d1); } } #define VISIT_FIELD(name) visitor->visit_##name && visitor->visit_##name #define VISIT_AFTER VISIT_FIELD (after) #define VISIT_BEFORE VISIT_FIELD (before) #define VISIT_CORRUPT \ if (visitor->visit_corrupt) \ visitor->visit_corrupt #define VISIT_DOUBLE VISIT_FIELD (double) #define VISIT_UTF8 VISIT_FIELD (utf8) #define VISIT_DOCUMENT VISIT_FIELD (document) #define VISIT_ARRAY VISIT_FIELD (array) #define VISIT_BINARY VISIT_FIELD (binary) #define VISIT_UNDEFINED VISIT_FIELD (undefined) #define VISIT_OID VISIT_FIELD (oid) #define VISIT_BOOL VISIT_FIELD (bool) #define VISIT_DATE_TIME VISIT_FIELD (date_time) #define VISIT_NULL VISIT_FIELD (null) #define VISIT_REGEX VISIT_FIELD (regex) #define VISIT_DBPOINTER VISIT_FIELD (dbpointer) #define VISIT_CODE VISIT_FIELD (code) #define VISIT_SYMBOL VISIT_FIELD (symbol) #define VISIT_CODEWSCOPE VISIT_FIELD (codewscope) #define VISIT_INT32 VISIT_FIELD (int32) #define VISIT_TIMESTAMP VISIT_FIELD (timestamp) #define VISIT_INT64 VISIT_FIELD (int64) #define VISIT_DECIMAL128 VISIT_FIELD (decimal128) #define VISIT_MAXKEY VISIT_FIELD (maxkey) #define VISIT_MINKEY VISIT_FIELD (minkey) bool bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ const bson_visitor_t *visitor, /* IN */ void *data) /* IN */ { uint32_t bson_type; const char *key; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (visitor); while (_bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported)) { if (*key && !bson_utf8_validate (key, strlen (key), false)) { iter->err_off = iter->off; break; } if (VISIT_BEFORE (iter, key, data)) { return true; } switch (bson_type) { case BSON_TYPE_DOUBLE: if (VISIT_DOUBLE (iter, key, bson_iter_double (iter), data)) { return true; } break; case BSON_TYPE_UTF8: { uint32_t utf8_len; const char *utf8; utf8 = bson_iter_utf8 (iter, &utf8_len); if (!bson_utf8_validate (utf8, utf8_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_UTF8 (iter, key, utf8_len, utf8, data)) { return true; } } break; case BSON_TYPE_DOCUMENT: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_document (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_DOCUMENT (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_ARRAY: { const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; bson_iter_array (iter, &doclen, &docbuf); if (bson_init_static (&b, docbuf, doclen) && VISIT_ARRAY (iter, key, &b, data)) { return true; } } break; case BSON_TYPE_BINARY: { const uint8_t *binary = NULL; bson_subtype_t subtype = BSON_SUBTYPE_BINARY; uint32_t binary_len = 0; bson_iter_binary (iter, &subtype, &binary_len, &binary); if (VISIT_BINARY (iter, key, subtype, binary_len, binary, data)) { return true; } } break; case BSON_TYPE_UNDEFINED: if (VISIT_UNDEFINED (iter, key, data)) { return true; } break; case BSON_TYPE_OID: if (VISIT_OID (iter, key, bson_iter_oid (iter), data)) { return true; } break; case BSON_TYPE_BOOL: if (VISIT_BOOL (iter, key, bson_iter_bool (iter), data)) { return true; } break; case BSON_TYPE_DATE_TIME: if (VISIT_DATE_TIME (iter, key, bson_iter_date_time (iter), data)) { return true; } break; case BSON_TYPE_NULL: if (VISIT_NULL (iter, key, data)) { return true; } break; case BSON_TYPE_REGEX: { const char *regex = NULL; const char *options = NULL; regex = bson_iter_regex (iter, &options); if (!bson_utf8_validate (regex, strlen (regex), true)) { iter->err_off = iter->off; return true; } if (VISIT_REGEX (iter, key, regex, options, data)) { return true; } } break; case BSON_TYPE_DBPOINTER: { uint32_t collection_len = 0; const char *collection = NULL; const bson_oid_t *oid = NULL; bson_iter_dbpointer (iter, &collection_len, &collection, &oid); if (!bson_utf8_validate (collection, collection_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_DBPOINTER ( iter, key, collection_len, collection, oid, data)) { return true; } } break; case BSON_TYPE_CODE: { uint32_t code_len; const char *code; code = bson_iter_code (iter, &code_len); if (!bson_utf8_validate (code, code_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_CODE (iter, key, code_len, code, data)) { return true; } } break; case BSON_TYPE_SYMBOL: { uint32_t symbol_len; const char *symbol; symbol = bson_iter_symbol (iter, &symbol_len); if (!bson_utf8_validate (symbol, symbol_len, true)) { iter->err_off = iter->off; return true; } if (VISIT_SYMBOL (iter, key, symbol_len, symbol, data)) { return true; } } break; case BSON_TYPE_CODEWSCOPE: { uint32_t length = 0; const char *code; const uint8_t *docbuf = NULL; uint32_t doclen = 0; bson_t b; code = bson_iter_codewscope (iter, &length, &doclen, &docbuf); if (!bson_utf8_validate (code, length, true)) { iter->err_off = iter->off; return true; } if (bson_init_static (&b, docbuf, doclen) && VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { return true; } } break; case BSON_TYPE_INT32: if (VISIT_INT32 (iter, key, bson_iter_int32 (iter), data)) { return true; } break; case BSON_TYPE_TIMESTAMP: { uint32_t timestamp; uint32_t increment; bson_iter_timestamp (iter, &timestamp, &increment); if (VISIT_TIMESTAMP (iter, key, timestamp, increment, data)) { return true; } } break; case BSON_TYPE_INT64: if (VISIT_INT64 (iter, key, bson_iter_int64 (iter), data)) { return true; } break; case BSON_TYPE_DECIMAL128: { bson_decimal128_t dec; bson_iter_decimal128 (iter, &dec); if (VISIT_DECIMAL128 (iter, key, &dec, data)) { return true; } } break; case BSON_TYPE_MAXKEY: if (VISIT_MAXKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_MINKEY: if (VISIT_MINKEY (iter, bson_iter_key_unsafe (iter), data)) { return true; } break; case BSON_TYPE_EOD: default: break; } if (VISIT_AFTER (iter, bson_iter_key_unsafe (iter), data)) { return true; } } if (iter->err_off) { if (unsupported && visitor->visit_unsupported_type && bson_utf8_validate (key, strlen (key), false)) { visitor->visit_unsupported_type (iter, key, bson_type, data); return false; } VISIT_CORRUPT (iter, data); } #undef VISIT_FIELD return false; } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_bool -- * * Overwrites the current BSON_TYPE_BOOLEAN field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_bool (bson_iter_t *iter, /* IN */ bool value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_BOOL) { memcpy ((void *) (iter->raw + iter->d1), &value, 1); } } void bson_iter_overwrite_oid (bson_iter_t *iter, const bson_oid_t *value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_OID) { memcpy ( (void *) (iter->raw + iter->d1), value->bytes, sizeof (value->bytes)); } } void bson_iter_overwrite_timestamp (bson_iter_t *iter, uint32_t timestamp, uint32_t increment) { uint64_t value; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_TIMESTAMP) { value = ((((uint64_t) timestamp) << 32U) | ((uint64_t) increment)); value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } void bson_iter_overwrite_date_time (bson_iter_t *iter, int64_t value) { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DATE_TIME) { value = BSON_UINT64_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int32 -- * * Overwrites the current BSON_TYPE_INT32 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int32 (bson_iter_t *iter, /* IN */ int32_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT32) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT32_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_int64 -- * * Overwrites the current BSON_TYPE_INT64 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_int64 (bson_iter_t *iter, /* IN */ int64_t value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_INT64) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN value = BSON_UINT64_TO_LE (value); #endif memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_double -- * * Overwrites the current BSON_TYPE_DOUBLE field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_double (bson_iter_t *iter, /* IN */ double value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DOUBLE) { value = BSON_DOUBLE_TO_LE (value); memcpy ((void *) (iter->raw + iter->d1), &value, sizeof (value)); } } /* *-------------------------------------------------------------------------- * * bson_iter_overwrite_decimal128 -- * * Overwrites the current BSON_TYPE_DECIMAL128 field with a new value. * This is performed in-place and therefore no keys are moved. * * Returns: * None. * * Side effects: * None. * *-------------------------------------------------------------------------- */ void bson_iter_overwrite_decimal128 (bson_iter_t *iter, /* IN */ bson_decimal128_t *value) /* IN */ { BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_DECIMAL128) { #if BSON_BYTE_ORDER != BSON_LITTLE_ENDIAN uint64_t data[2]; data[0] = BSON_UINT64_TO_LE (value->low); data[1] = BSON_UINT64_TO_LE (value->high); memcpy ((void *) (iter->raw + iter->d1), data, sizeof (data)); #else memcpy ((void *) (iter->raw + iter->d1), value, sizeof (*value)); #endif } } /* *-------------------------------------------------------------------------- * * bson_iter_value -- * * Retrieves a bson_value_t containing the boxed value of the current * element. The result of this function valid until the state of * iter has been changed (through the use of bson_iter_next()). * * Returns: * A bson_value_t that should not be modified or freed. If you need * to hold on to the value, use bson_value_copy(). * * Side effects: * None. * *-------------------------------------------------------------------------- */ const bson_value_t * bson_iter_value (bson_iter_t *iter) /* IN */ { bson_value_t *value; BSON_ASSERT (iter); value = &iter->value; value->value_type = ITER_TYPE (iter); switch (value->value_type) { case BSON_TYPE_DOUBLE: value->value.v_double = bson_iter_double (iter); break; case BSON_TYPE_UTF8: value->value.v_utf8.str = (char *) bson_iter_utf8 (iter, &value->value.v_utf8.len); break; case BSON_TYPE_DOCUMENT: bson_iter_document (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_ARRAY: bson_iter_array (iter, &value->value.v_doc.data_len, (const uint8_t **) &value->value.v_doc.data); break; case BSON_TYPE_BINARY: bson_iter_binary (iter, &value->value.v_binary.subtype, &value->value.v_binary.data_len, (const uint8_t **) &value->value.v_binary.data); break; case BSON_TYPE_OID: bson_oid_copy (bson_iter_oid (iter), &value->value.v_oid); break; case BSON_TYPE_BOOL: value->value.v_bool = bson_iter_bool (iter); break; case BSON_TYPE_DATE_TIME: value->value.v_datetime = bson_iter_date_time (iter); break; case BSON_TYPE_REGEX: value->value.v_regex.regex = (char *) bson_iter_regex ( iter, (const char **) &value->value.v_regex.options); break; case BSON_TYPE_DBPOINTER: { const bson_oid_t *oid; bson_iter_dbpointer (iter, &value->value.v_dbpointer.collection_len, (const char **) &value->value.v_dbpointer.collection, &oid); bson_oid_copy (oid, &value->value.v_dbpointer.oid); break; } case BSON_TYPE_CODE: value->value.v_code.code = (char *) bson_iter_code (iter, &value->value.v_code.code_len); break; case BSON_TYPE_SYMBOL: value->value.v_symbol.symbol = (char *) bson_iter_symbol (iter, &value->value.v_symbol.len); break; case BSON_TYPE_CODEWSCOPE: value->value.v_codewscope.code = (char *) bson_iter_codewscope ( iter, &value->value.v_codewscope.code_len, &value->value.v_codewscope.scope_len, (const uint8_t **) &value->value.v_codewscope.scope_data); break; case BSON_TYPE_INT32: value->value.v_int32 = bson_iter_int32 (iter); break; case BSON_TYPE_TIMESTAMP: bson_iter_timestamp (iter, &value->value.v_timestamp.timestamp, &value->value.v_timestamp.increment); break; case BSON_TYPE_INT64: value->value.v_int64 = bson_iter_int64 (iter); break; case BSON_TYPE_DECIMAL128: bson_iter_decimal128 (iter, &(value->value.v_decimal128)); break; case BSON_TYPE_NULL: case BSON_TYPE_UNDEFINED: case BSON_TYPE_MAXKEY: case BSON_TYPE_MINKEY: break; case BSON_TYPE_EOD: default: return NULL; } return value; } uint32_t bson_iter_key_len (const bson_iter_t *iter) { /* * f i e l d n a m e \0 _ * ^ ^ * | | * iter->key iter->d1 * */ BSON_ASSERT (iter->d1 > iter->key); return iter->d1 - iter->key - 1; } bool bson_iter_init_from_data_at_offset (bson_iter_t *iter, const uint8_t *data, size_t length, uint32_t offset, uint32_t keylen) { const char *key; uint32_t bson_type; bool unsupported; BSON_ASSERT (iter); BSON_ASSERT (data); if (BSON_UNLIKELY ((length < 5) || (length > INT_MAX))) { memset (iter, 0, sizeof *iter); return false; } iter->raw = (uint8_t *) data; iter->len = (uint32_t) length; iter->off = 0; iter->type = 0; iter->key = 0; iter->next_off = offset; iter->err_off = 0; if (!_bson_iter_next_internal ( iter, keylen, &key, &bson_type, &unsupported)) { memset (iter, 0, sizeof *iter); return false; } return true; } uint32_t bson_iter_offset (bson_iter_t *iter) { return iter->off; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_372_0
crossvul-cpp_data_good_3254_2
/* * NET An implementation of the SOCKET network access protocol. * * Version: @(#)socket.c 1.1.93 18/02/95 * * Authors: Orest Zborowski, <obz@Kodak.COM> * Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * * Fixes: * Anonymous : NOTSOCK/BADF cleanup. Error fix in * shutdown() * Alan Cox : verify_area() fixes * Alan Cox : Removed DDI * Jonathan Kamens : SOCK_DGRAM reconnect bug * Alan Cox : Moved a load of checks to the very * top level. * Alan Cox : Move address structures to/from user * mode above the protocol layers. * Rob Janssen : Allow 0 length sends. * Alan Cox : Asynchronous I/O support (cribbed from the * tty drivers). * Niibe Yutaka : Asynchronous I/O for writes (4.4BSD style) * Jeff Uphoff : Made max number of sockets command-line * configurable. * Matti Aarnio : Made the number of sockets dynamic, * to be allocated when needed, and mr. * Uphoff's max is used as max to be * allowed to allocate. * Linus : Argh. removed all the socket allocation * altogether: it's in the inode now. * Alan Cox : Made sock_alloc()/sock_release() public * for NetROM and future kernel nfsd type * stuff. * Alan Cox : sendmsg/recvmsg basics. * Tom Dyas : Export net symbols. * Marcin Dalecki : Fixed problems with CONFIG_NET="n". * Alan Cox : Added thread locking to sys_* calls * for sockets. May have errors at the * moment. * Kevin Buhr : Fixed the dumb errors in the above. * Andi Kleen : Some small cleanups, optimizations, * and fixed a copy_from_user() bug. * Tigran Aivazian : sys_send(args) calls sys_sendto(args, NULL, 0) * Tigran Aivazian : Made listen(2) backlog sanity checks * protocol-independent * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * * This module is effectively the top level interface to the BSD socket * paradigm. * * Based upon Swansea University Computer Society NET3.039 */ #include <linux/mm.h> #include <linux/socket.h> #include <linux/file.h> #include <linux/net.h> #include <linux/interrupt.h> #include <linux/thread_info.h> #include <linux/rcupdate.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/mutex.h> #include <linux/if_bridge.h> #include <linux/if_frad.h> #include <linux/if_vlan.h> #include <linux/ptp_classify.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/highmem.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/compat.h> #include <linux/kmod.h> #include <linux/audit.h> #include <linux/wireless.h> #include <linux/nsproxy.h> #include <linux/magic.h> #include <linux/slab.h> #include <linux/xattr.h> #include <linux/uaccess.h> #include <asm/unistd.h> #include <net/compat.h> #include <net/wext.h> #include <net/cls_cgroup.h> #include <net/sock.h> #include <linux/netfilter.h> #include <linux/if_tun.h> #include <linux/ipv6_route.h> #include <linux/route.h> #include <linux/sockios.h> #include <linux/atalk.h> #include <net/busy_poll.h> #include <linux/errqueue.h> #ifdef CONFIG_NET_RX_BUSY_POLL unsigned int sysctl_net_busy_read __read_mostly; unsigned int sysctl_net_busy_poll __read_mostly; #endif static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to); static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from); static int sock_mmap(struct file *file, struct vm_area_struct *vma); static int sock_close(struct inode *inode, struct file *file); static unsigned int sock_poll(struct file *file, struct poll_table_struct *wait); static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #ifdef CONFIG_COMPAT static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #endif static int sock_fasync(int fd, struct file *filp, int on); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more); static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags); /* * Socket files have a set of 'special' operations as well as the generic file ones. These don't appear * in the operation structures but are done directly via the socketcall() multiplexor. */ static const struct file_operations socket_file_ops = { .owner = THIS_MODULE, .llseek = no_llseek, .read_iter = sock_read_iter, .write_iter = sock_write_iter, .poll = sock_poll, .unlocked_ioctl = sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_sock_ioctl, #endif .mmap = sock_mmap, .release = sock_close, .fasync = sock_fasync, .sendpage = sock_sendpage, .splice_write = generic_splice_sendpage, .splice_read = sock_splice_read, }; /* * The protocol list. Each protocol is registered in here. */ static DEFINE_SPINLOCK(net_family_lock); static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly; /* * Statistics counters of the socket lists */ static DEFINE_PER_CPU(int, sockets_in_use); /* * Support routines. * Move socket addresses back and forth across the kernel/user * divide and look after the messy bits. */ /** * move_addr_to_kernel - copy a socket address into kernel space * @uaddr: Address in user space * @kaddr: Address in kernel space * @ulen: Length in user space * * The address is copied into kernel space. If the provided address is * too long an error code of -EINVAL is returned. If the copy gives * invalid addresses -EFAULT is returned. On a success 0 is returned. */ int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr) { if (ulen < 0 || ulen > sizeof(struct sockaddr_storage)) return -EINVAL; if (ulen == 0) return 0; if (copy_from_user(kaddr, uaddr, ulen)) return -EFAULT; return audit_sockaddr(ulen, kaddr); } /** * move_addr_to_user - copy an address to user space * @kaddr: kernel space address * @klen: length of address in kernel * @uaddr: user space address * @ulen: pointer to user length field * * The value pointed to by ulen on entry is the buffer length available. * This is overwritten with the buffer space used. -EINVAL is returned * if an overlong buffer is specified or a negative buffer size. -EFAULT * is returned if either the buffer or the length field are not * accessible. * After copying the data up to the limit the user specifies, the true * length of the data is written over the length limit the user * specified. Zero is returned for a success. */ static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen, void __user *uaddr, int __user *ulen) { int err; int len; BUG_ON(klen > sizeof(struct sockaddr_storage)); err = get_user(len, ulen); if (err) return err; if (len > klen) len = klen; if (len < 0) return -EINVAL; if (len) { if (audit_sockaddr(klen, kaddr)) return -ENOMEM; if (copy_to_user(uaddr, kaddr, len)) return -EFAULT; } /* * "fromlen shall refer to the value before truncation.." * 1003.1g */ return __put_user(klen, ulen); } static struct kmem_cache *sock_inode_cachep __read_mostly; static struct inode *sock_alloc_inode(struct super_block *sb) { struct socket_alloc *ei; struct socket_wq *wq; ei = kmem_cache_alloc(sock_inode_cachep, GFP_KERNEL); if (!ei) return NULL; wq = kmalloc(sizeof(*wq), GFP_KERNEL); if (!wq) { kmem_cache_free(sock_inode_cachep, ei); return NULL; } init_waitqueue_head(&wq->wait); wq->fasync_list = NULL; wq->flags = 0; RCU_INIT_POINTER(ei->socket.wq, wq); ei->socket.state = SS_UNCONNECTED; ei->socket.flags = 0; ei->socket.ops = NULL; ei->socket.sk = NULL; ei->socket.file = NULL; return &ei->vfs_inode; } static void sock_destroy_inode(struct inode *inode) { struct socket_alloc *ei; struct socket_wq *wq; ei = container_of(inode, struct socket_alloc, vfs_inode); wq = rcu_dereference_protected(ei->socket.wq, 1); kfree_rcu(wq, rcu); kmem_cache_free(sock_inode_cachep, ei); } static void init_once(void *foo) { struct socket_alloc *ei = (struct socket_alloc *)foo; inode_init_once(&ei->vfs_inode); } static void init_inodecache(void) { sock_inode_cachep = kmem_cache_create("sock_inode_cache", sizeof(struct socket_alloc), 0, (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT), init_once); BUG_ON(sock_inode_cachep == NULL); } static const struct super_operations sockfs_ops = { .alloc_inode = sock_alloc_inode, .destroy_inode = sock_destroy_inode, .statfs = simple_statfs, }; /* * sockfs_dname() is called from d_path(). */ static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "socket:[%lu]", d_inode(dentry)->i_ino); } static const struct dentry_operations sockfs_dentry_operations = { .d_dname = sockfs_dname, }; static int sockfs_xattr_get(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *suffix, void *value, size_t size) { if (value) { if (dentry->d_name.len + 1 > size) return -ERANGE; memcpy(value, dentry->d_name.name, dentry->d_name.len + 1); } return dentry->d_name.len + 1; } #define XATTR_SOCKPROTONAME_SUFFIX "sockprotoname" #define XATTR_NAME_SOCKPROTONAME (XATTR_SYSTEM_PREFIX XATTR_SOCKPROTONAME_SUFFIX) #define XATTR_NAME_SOCKPROTONAME_LEN (sizeof(XATTR_NAME_SOCKPROTONAME)-1) static const struct xattr_handler sockfs_xattr_handler = { .name = XATTR_NAME_SOCKPROTONAME, .get = sockfs_xattr_get, }; static int sockfs_security_xattr_set(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *suffix, const void *value, size_t size, int flags) { /* Handled by LSM. */ return -EAGAIN; } static const struct xattr_handler sockfs_security_xattr_handler = { .prefix = XATTR_SECURITY_PREFIX, .set = sockfs_security_xattr_set, }; static const struct xattr_handler *sockfs_xattr_handlers[] = { &sockfs_xattr_handler, &sockfs_security_xattr_handler, NULL }; static struct dentry *sockfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo_xattr(fs_type, "socket:", &sockfs_ops, sockfs_xattr_handlers, &sockfs_dentry_operations, SOCKFS_MAGIC); } static struct vfsmount *sock_mnt __read_mostly; static struct file_system_type sock_fs_type = { .name = "sockfs", .mount = sockfs_mount, .kill_sb = kill_anon_super, }; /* * Obtains the first available file descriptor and sets it up for use. * * These functions create file structures and maps them to fd space * of the current process. On success it returns file descriptor * and file struct implicitly stored in sock->file. * Note that another thread may close file descriptor before we return * from this function. We use the fact that now we do not refer * to socket after mapping. If one day we will need it, this * function will increment ref. count on file by 1. * * In any case returned fd MAY BE not valid! * This race condition is unavoidable * with shared fd spaces, we cannot solve it inside kernel, * but we take care of internal coherence yet. */ struct file *sock_alloc_file(struct socket *sock, int flags, const char *dname) { struct qstr name = { .name = "" }; struct path path; struct file *file; if (dname) { name.name = dname; name.len = strlen(name.name); } else if (sock->sk) { name.name = sock->sk->sk_prot_creator->name; name.len = strlen(name.name); } path.dentry = d_alloc_pseudo(sock_mnt->mnt_sb, &name); if (unlikely(!path.dentry)) return ERR_PTR(-ENOMEM); path.mnt = mntget(sock_mnt); d_instantiate(path.dentry, SOCK_INODE(sock)); file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &socket_file_ops); if (IS_ERR(file)) { /* drop dentry, keep inode */ ihold(d_inode(path.dentry)); path_put(&path); return file; } sock->file = file; file->f_flags = O_RDWR | (flags & O_NONBLOCK); file->private_data = sock; return file; } EXPORT_SYMBOL(sock_alloc_file); static int sock_map_fd(struct socket *sock, int flags) { struct file *newfile; int fd = get_unused_fd_flags(flags); if (unlikely(fd < 0)) return fd; newfile = sock_alloc_file(sock, flags, NULL); if (likely(!IS_ERR(newfile))) { fd_install(fd, newfile); return fd; } put_unused_fd(fd); return PTR_ERR(newfile); } struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; } EXPORT_SYMBOL(sock_from_file); /** * sockfd_lookup - Go from a file number to its socket slot * @fd: file handle * @err: pointer to an error code return * * The file handle passed in is locked and the socket it is bound * too is returned. If an error occurs the err pointer is overwritten * with a negative errno code and NULL is returned. The function checks * for both invalid handles and passing a handle which is not a socket. * * On a success the socket object pointer is returned. */ struct socket *sockfd_lookup(int fd, int *err) { struct file *file; struct socket *sock; file = fget(fd); if (!file) { *err = -EBADF; return NULL; } sock = sock_from_file(file, err); if (!sock) fput(file); return sock; } EXPORT_SYMBOL(sockfd_lookup); static struct socket *sockfd_lookup_light(int fd, int *err, int *fput_needed) { struct fd f = fdget(fd); struct socket *sock; *err = -EBADF; if (f.file) { sock = sock_from_file(f.file, err); if (likely(sock)) { *fput_needed = f.flags; return sock; } fdput(f); } return NULL; } static ssize_t sockfs_listxattr(struct dentry *dentry, char *buffer, size_t size) { ssize_t len; ssize_t used = 0; len = security_inode_listsecurity(d_inode(dentry), buffer, size); if (len < 0) return len; used += len; if (buffer) { if (size < used) return -ERANGE; buffer += len; } len = (XATTR_NAME_SOCKPROTONAME_LEN + 1); used += len; if (buffer) { if (size < used) return -ERANGE; memcpy(buffer, XATTR_NAME_SOCKPROTONAME, len); buffer += len; } return used; } static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr) { int err = simple_setattr(dentry, iattr); if (!err && (iattr->ia_valid & ATTR_UID)) { struct socket *sock = SOCKET_I(d_inode(dentry)); sock->sk->sk_uid = iattr->ia_uid; } return err; } static const struct inode_operations sockfs_inode_ops = { .listxattr = sockfs_listxattr, .setattr = sockfs_setattr, }; /** * sock_alloc - allocate a socket * * Allocate a new inode and socket object. The two are bound together * and initialised. The socket is then returned. If we are out of inodes * NULL is returned. */ struct socket *sock_alloc(void) { struct inode *inode; struct socket *sock; inode = new_inode_pseudo(sock_mnt->mnt_sb); if (!inode) return NULL; sock = SOCKET_I(inode); kmemcheck_annotate_bitfield(sock, type); inode->i_ino = get_next_ino(); inode->i_mode = S_IFSOCK | S_IRWXUGO; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); inode->i_op = &sockfs_inode_ops; this_cpu_add(sockets_in_use, 1); return sock; } EXPORT_SYMBOL(sock_alloc); /** * sock_release - close a socket * @sock: socket to close * * The socket is released from the protocol stack if it has a release * callback, and the inode is then released if the socket is bound to * an inode not a file. */ void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) pr_err("%s: fasync list not empty!\n", __func__); this_cpu_sub(sockets_in_use, 1); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } EXPORT_SYMBOL(sock_release); void __sock_tx_timestamp(__u16 tsflags, __u8 *tx_flags) { u8 flags = *tx_flags; if (tsflags & SOF_TIMESTAMPING_TX_HARDWARE) flags |= SKBTX_HW_TSTAMP; if (tsflags & SOF_TIMESTAMPING_TX_SOFTWARE) flags |= SKBTX_SW_TSTAMP; if (tsflags & SOF_TIMESTAMPING_TX_SCHED) flags |= SKBTX_SCHED_TSTAMP; *tx_flags = flags; } EXPORT_SYMBOL(__sock_tx_timestamp); static inline int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg) { int ret = sock->ops->sendmsg(sock, msg, msg_data_left(msg)); BUG_ON(ret == -EIOCBQUEUED); return ret; } int sock_sendmsg(struct socket *sock, struct msghdr *msg) { int err = security_socket_sendmsg(sock, msg, msg_data_left(msg)); return err ?: sock_sendmsg_nosec(sock, msg); } EXPORT_SYMBOL(sock_sendmsg); int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size) { iov_iter_kvec(&msg->msg_iter, WRITE | ITER_KVEC, vec, num, size); return sock_sendmsg(sock, msg); } EXPORT_SYMBOL(kernel_sendmsg); static bool skb_is_err_queue(const struct sk_buff *skb) { /* pkt_type of skbs enqueued on the error queue are set to * PACKET_OUTGOING in skb_set_err_queue(). This is only safe to do * in recvmsg, since skbs received on a local socket will never * have a pkt_type of PACKET_OUTGOING. */ return skb->pkt_type == PACKET_OUTGOING; } /* * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP) */ void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && SKB_EXT_ERR(skb)->opt_stats) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } EXPORT_SYMBOL_GPL(__sock_recv_timestamp); void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int ack; if (!sock_flag(sk, SOCK_WIFI_STATUS)) return; if (!skb->wifi_acked_valid) return; ack = skb->wifi_acked; put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack); } EXPORT_SYMBOL_GPL(__sock_recv_wifi_status); static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && SOCK_SKB_CB(skb)->dropcount) put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL, sizeof(__u32), &SOCK_SKB_CB(skb)->dropcount); } void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { sock_recv_timestamp(msg, sk, skb); sock_recv_drops(msg, sk, skb); } EXPORT_SYMBOL_GPL(__sock_recv_ts_and_drops); static inline int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg, int flags) { return sock->ops->recvmsg(sock, msg, msg_data_left(msg), flags); } int sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags) { int err = security_socket_recvmsg(sock, msg, msg_data_left(msg), flags); return err ?: sock_recvmsg_nosec(sock, msg, flags); } EXPORT_SYMBOL(sock_recvmsg); /** * kernel_recvmsg - Receive a message from a socket (kernel space) * @sock: The socket to receive the message from * @msg: Received message * @vec: Input s/g array for message data * @num: Size of input s/g array * @size: Number of bytes to read * @flags: Message flags (MSG_DONTWAIT, etc...) * * On return the msg structure contains the scatter/gather array passed in the * vec argument. The array is modified so that it consists of the unfilled * portion of the original array. * * The returned value is the total number of bytes received, or an error. */ int kernel_recvmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size, int flags) { mm_segment_t oldfs = get_fs(); int result; iov_iter_kvec(&msg->msg_iter, READ | ITER_KVEC, vec, num, size); set_fs(KERNEL_DS); result = sock_recvmsg(sock, msg, flags); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_recvmsg); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more) { struct socket *sock; int flags; sock = file->private_data; flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; /* more is a combination of MSG_MORE and MSG_SENDPAGE_NOTLAST */ flags |= more; return kernel_sendpage(sock, page, offset, size, flags); } static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct socket *sock = file->private_data; if (unlikely(!sock->ops->splice_read)) return -EINVAL; return sock->ops->splice_read(sock, ppos, pipe, len, flags); } static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *to, .msg_iocb = iocb}; ssize_t res; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (iocb->ki_pos != 0) return -ESPIPE; if (!iov_iter_count(to)) /* Match SYS5 behaviour */ return 0; res = sock_recvmsg(sock, &msg, msg.msg_flags); *to = msg.msg_iter; return res; } static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *from, .msg_iocb = iocb}; ssize_t res; if (iocb->ki_pos != 0) return -ESPIPE; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (sock->type == SOCK_SEQPACKET) msg.msg_flags |= MSG_EOR; res = sock_sendmsg(sock, &msg); *from = msg.msg_iter; return res; } /* * Atomic setting of ioctl hooks to avoid race * with module unload. */ static DEFINE_MUTEX(br_ioctl_mutex); static int (*br_ioctl_hook) (struct net *, unsigned int cmd, void __user *arg); void brioctl_set(int (*hook) (struct net *, unsigned int, void __user *)) { mutex_lock(&br_ioctl_mutex); br_ioctl_hook = hook; mutex_unlock(&br_ioctl_mutex); } EXPORT_SYMBOL(brioctl_set); static DEFINE_MUTEX(vlan_ioctl_mutex); static int (*vlan_ioctl_hook) (struct net *, void __user *arg); void vlan_ioctl_set(int (*hook) (struct net *, void __user *)) { mutex_lock(&vlan_ioctl_mutex); vlan_ioctl_hook = hook; mutex_unlock(&vlan_ioctl_mutex); } EXPORT_SYMBOL(vlan_ioctl_set); static DEFINE_MUTEX(dlci_ioctl_mutex); static int (*dlci_ioctl_hook) (unsigned int, void __user *); void dlci_ioctl_set(int (*hook) (unsigned int, void __user *)) { mutex_lock(&dlci_ioctl_mutex); dlci_ioctl_hook = hook; mutex_unlock(&dlci_ioctl_mutex); } EXPORT_SYMBOL(dlci_ioctl_set); static long sock_do_ioctl(struct net *net, struct socket *sock, unsigned int cmd, unsigned long arg) { int err; void __user *argp = (void __user *)arg; err = sock->ops->ioctl(sock, cmd, arg); /* * If this ioctl is unknown try to hand it down * to the NIC driver. */ if (err == -ENOIOCTLCMD) err = dev_ioctl(net, cmd, argp); return err; } /* * With an ioctl, arg may well be a user mode pointer, but we don't know * what to do with it - that's up to the protocol still. */ static struct ns_common *get_net_ns(struct ns_common *ns) { return &get_net(container_of(ns, struct net, ns))->ns; } static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) { struct socket *sock; struct sock *sk; void __user *argp = (void __user *)arg; int pid, err; struct net *net; sock = file->private_data; sk = sock->sk; net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) { err = dev_ioctl(net, cmd, argp); } else #ifdef CONFIG_WEXT_CORE if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) { err = dev_ioctl(net, cmd, argp); } else #endif switch (cmd) { case FIOSETOWN: case SIOCSPGRP: err = -EFAULT; if (get_user(pid, (int __user *)argp)) break; f_setown(sock->file, pid, 1); err = 0; break; case FIOGETOWN: case SIOCGPGRP: err = put_user(f_getown(sock->file), (int __user *)argp); break; case SIOCGIFBR: case SIOCSIFBR: case SIOCBRADDBR: case SIOCBRDELBR: err = -ENOPKG; if (!br_ioctl_hook) request_module("bridge"); mutex_lock(&br_ioctl_mutex); if (br_ioctl_hook) err = br_ioctl_hook(net, cmd, argp); mutex_unlock(&br_ioctl_mutex); break; case SIOCGIFVLAN: case SIOCSIFVLAN: err = -ENOPKG; if (!vlan_ioctl_hook) request_module("8021q"); mutex_lock(&vlan_ioctl_mutex); if (vlan_ioctl_hook) err = vlan_ioctl_hook(net, argp); mutex_unlock(&vlan_ioctl_mutex); break; case SIOCADDDLCI: case SIOCDELDLCI: err = -ENOPKG; if (!dlci_ioctl_hook) request_module("dlci"); mutex_lock(&dlci_ioctl_mutex); if (dlci_ioctl_hook) err = dlci_ioctl_hook(cmd, argp); mutex_unlock(&dlci_ioctl_mutex); break; case SIOCGSKNS: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) break; err = open_related_ns(&net->ns, get_net_ns); break; default: err = sock_do_ioctl(net, sock, cmd, arg); break; } return err; } int sock_create_lite(int family, int type, int protocol, struct socket **res) { int err; struct socket *sock = NULL; err = security_socket_create(family, type, protocol, 1); if (err) goto out; sock = sock_alloc(); if (!sock) { err = -ENOMEM; goto out; } sock->type = type; err = security_socket_post_create(sock, family, type, protocol, 1); if (err) goto out_release; out: *res = sock; return err; out_release: sock_release(sock); sock = NULL; goto out; } EXPORT_SYMBOL(sock_create_lite); /* No kernel lock held - perfect */ static unsigned int sock_poll(struct file *file, poll_table *wait) { unsigned int busy_flag = 0; struct socket *sock; /* * We can't return errors to poll, so it's either yes or no. */ sock = file->private_data; if (sk_can_busy_loop(sock->sk)) { /* this socket can poll_ll so tell the system call */ busy_flag = POLL_BUSY_LOOP; /* once, only if requested by syscall */ if (wait && (wait->_key & POLL_BUSY_LOOP)) sk_busy_loop(sock->sk, 1); } return busy_flag | sock->ops->poll(file, sock, wait); } static int sock_mmap(struct file *file, struct vm_area_struct *vma) { struct socket *sock = file->private_data; return sock->ops->mmap(file, sock, vma); } static int sock_close(struct inode *inode, struct file *filp) { sock_release(SOCKET_I(inode)); return 0; } /* * Update the socket async list * * Fasync_list locking strategy. * * 1. fasync_list is modified only under process context socket lock * i.e. under semaphore. * 2. fasync_list is used under read_lock(&sk->sk_callback_lock) * or under socket lock */ static int sock_fasync(int fd, struct file *filp, int on) { struct socket *sock = filp->private_data; struct sock *sk = sock->sk; struct socket_wq *wq; if (sk == NULL) return -EINVAL; lock_sock(sk); wq = rcu_dereference_protected(sock->wq, lockdep_sock_is_held(sk)); fasync_helper(fd, filp, on, &wq->fasync_list); if (!wq->fasync_list) sock_reset_flag(sk, SOCK_FASYNC); else sock_set_flag(sk, SOCK_FASYNC); release_sock(sk); return 0; } /* This function may be called only under rcu_lock */ int sock_wake_async(struct socket_wq *wq, int how, int band) { if (!wq || !wq->fasync_list) return -1; switch (how) { case SOCK_WAKE_WAITD: if (test_bit(SOCKWQ_ASYNC_WAITDATA, &wq->flags)) break; goto call_kill; case SOCK_WAKE_SPACE: if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &wq->flags)) break; /* fall through */ case SOCK_WAKE_IO: call_kill: kill_fasync(&wq->fasync_list, SIGIO, band); break; case SOCK_WAKE_URG: kill_fasync(&wq->fasync_list, SIGURG, band); } return 0; } EXPORT_SYMBOL(sock_wake_async); int __sock_create(struct net *net, int family, int type, int protocol, struct socket **res, int kern) { int err; struct socket *sock; const struct net_proto_family *pf; /* * Check protocol is in range */ if (family < 0 || family >= NPROTO) return -EAFNOSUPPORT; if (type < 0 || type >= SOCK_MAX) return -EINVAL; /* Compatibility. This uglymoron is moved from INET layer to here to avoid deadlock in module load. */ if (family == PF_INET && type == SOCK_PACKET) { pr_info_once("%s uses obsolete (PF_INET,SOCK_PACKET)\n", current->comm); family = PF_PACKET; } err = security_socket_create(family, type, protocol, kern); if (err) return err; /* * Allocate the socket and allow the family to set things up. if * the protocol is 0, the family is instructed to select an appropriate * default. */ sock = sock_alloc(); if (!sock) { net_warn_ratelimited("socket: no more sockets\n"); return -ENFILE; /* Not exactly a match, but its the closest posix thing */ } sock->type = type; #ifdef CONFIG_MODULES /* Attempt to load a protocol module if the find failed. * * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user * requested real, full-featured networking support upon configuration. * Otherwise module support will break! */ if (rcu_access_pointer(net_families[family]) == NULL) request_module("net-pf-%d", family); #endif rcu_read_lock(); pf = rcu_dereference(net_families[family]); err = -EAFNOSUPPORT; if (!pf) goto out_release; /* * We will call the ->create function, that possibly is in a loadable * module, so we have to bump that loadable module refcnt first. */ if (!try_module_get(pf->owner)) goto out_release; /* Now protected by module ref count */ rcu_read_unlock(); err = pf->create(net, sock, protocol, kern); if (err < 0) goto out_module_put; /* * Now to bump the refcnt of the [loadable] module that owns this * socket at sock_release time we decrement its refcnt. */ if (!try_module_get(sock->ops->owner)) goto out_module_busy; /* * Now that we're done with the ->create function, the [loadable] * module can have its refcnt decremented */ module_put(pf->owner); err = security_socket_post_create(sock, family, type, protocol, kern); if (err) goto out_sock_release; *res = sock; return 0; out_module_busy: err = -EAFNOSUPPORT; out_module_put: sock->ops = NULL; module_put(pf->owner); out_sock_release: sock_release(sock); return err; out_release: rcu_read_unlock(); goto out_sock_release; } EXPORT_SYMBOL(__sock_create); int sock_create(int family, int type, int protocol, struct socket **res) { return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0); } EXPORT_SYMBOL(sock_create); int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res) { return __sock_create(net, family, type, protocol, res, 1); } EXPORT_SYMBOL(sock_create_kern); SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) { int retval; struct socket *sock; int flags; /* Check the SOCK_* constants for consistency. */ BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK); flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; retval = sock_create(family, type, protocol, &sock); if (retval < 0) goto out; retval = sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK)); if (retval < 0) goto out_release; out: /* It may be already another descriptor 8) Not kernel problem. */ return retval; out_release: sock_release(sock); return retval; } /* * Create a pair of connected sockets. */ SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol, int __user *, usockvec) { struct socket *sock1, *sock2; int fd1, fd2, err; struct file *newfile1, *newfile2; int flags; flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; /* * Obtain the first socket and check if the underlying protocol * supports the socketpair call. */ err = sock_create(family, type, protocol, &sock1); if (err < 0) goto out; err = sock_create(family, type, protocol, &sock2); if (err < 0) goto out_release_1; err = sock1->ops->socketpair(sock1, sock2); if (err < 0) goto out_release_both; fd1 = get_unused_fd_flags(flags); if (unlikely(fd1 < 0)) { err = fd1; goto out_release_both; } fd2 = get_unused_fd_flags(flags); if (unlikely(fd2 < 0)) { err = fd2; goto out_put_unused_1; } newfile1 = sock_alloc_file(sock1, flags, NULL); if (IS_ERR(newfile1)) { err = PTR_ERR(newfile1); goto out_put_unused_both; } newfile2 = sock_alloc_file(sock2, flags, NULL); if (IS_ERR(newfile2)) { err = PTR_ERR(newfile2); goto out_fput_1; } err = put_user(fd1, &usockvec[0]); if (err) goto out_fput_both; err = put_user(fd2, &usockvec[1]); if (err) goto out_fput_both; audit_fd_pair(fd1, fd2); fd_install(fd1, newfile1); fd_install(fd2, newfile2); /* fd1 and fd2 may be already another descriptors. * Not kernel problem. */ return 0; out_fput_both: fput(newfile2); fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); goto out; out_fput_1: fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); sock_release(sock2); goto out; out_put_unused_both: put_unused_fd(fd2); out_put_unused_1: put_unused_fd(fd1); out_release_both: sock_release(sock2); out_release_1: sock_release(sock1); out: return err; } /* * Bind a name to a socket. Nothing much to do here since it's * the protocol's responsibility to handle the local address. * * We move the socket address to kernel space before we call * the protocol layer (having also checked the address is ok). */ SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { err = move_addr_to_kernel(umyaddr, addrlen, &address); if (err >= 0) { err = security_socket_bind(sock, (struct sockaddr *)&address, addrlen); if (!err) err = sock->ops->bind(sock, (struct sockaddr *) &address, addrlen); } fput_light(sock->file, fput_needed); } return err; } /* * Perform a listen. Basically, we allow the protocol to do anything * necessary for a listen, and if that works, we mark the socket as * ready for listening. */ SYSCALL_DEFINE2(listen, int, fd, int, backlog) { struct socket *sock; int err, fput_needed; int somaxconn; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn; if ((unsigned int)backlog > somaxconn) backlog = somaxconn; err = security_socket_listen(sock, backlog); if (!err) err = sock->ops->listen(sock, backlog); fput_light(sock->file, fput_needed); } return err; } /* * For accept, we attempt to create a new socket, set up the link * with the client, wake up the client, then return the new * connected fd. We collect the address of the connector in kernel * space and move it to user at the very end. This is unclean because * we open the socket then return an error. * * 1003.1g adds the ability to recvmsg() to query connection pending * status to recvmsg. We need to add that support in a way thats * clean when we restucture accept also. */ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen, int, flags) { struct socket *sock, *newsock; struct file *newfile; int err, len, newfd, fput_needed; struct sockaddr_storage address; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = -ENFILE; newsock = sock_alloc(); if (!newsock) goto out_put; newsock->type = sock->type; newsock->ops = sock->ops; /* * We don't need try_module_get here, as the listening socket (sock) * has the protocol module (sock->ops->owner) held. */ __module_get(newsock->ops->owner); newfd = get_unused_fd_flags(flags); if (unlikely(newfd < 0)) { err = newfd; sock_release(newsock); goto out_put; } newfile = sock_alloc_file(newsock, flags, sock->sk->sk_prot_creator->name); if (IS_ERR(newfile)) { err = PTR_ERR(newfile); put_unused_fd(newfd); sock_release(newsock); goto out_put; } err = security_socket_accept(sock, newsock); if (err) goto out_fd; err = sock->ops->accept(sock, newsock, sock->file->f_flags, false); if (err < 0) goto out_fd; if (upeer_sockaddr) { if (newsock->ops->getname(newsock, (struct sockaddr *)&address, &len, 2) < 0) { err = -ECONNABORTED; goto out_fd; } err = move_addr_to_user(&address, len, upeer_sockaddr, upeer_addrlen); if (err < 0) goto out_fd; } /* File flags are not inherited via accept() unlike another OSes. */ fd_install(newfd, newfile); err = newfd; out_put: fput_light(sock->file, fput_needed); out: return err; out_fd: fput(newfile); put_unused_fd(newfd); goto out_put; } SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen) { return sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0); } /* * Attempt to connect to a socket with the server address. The address * is in user space so we verify it is OK and move it to kernel space. * * For 1003.1g we need to add clean support for a bind to AF_UNSPEC to * break bindings * * NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and * other SEQPACKET protocols that take time to connect() as it doesn't * include the -EINPROGRESS status for such sockets. */ SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = move_addr_to_kernel(uservaddr, addrlen, &address); if (err < 0) goto out_put; err = security_socket_connect(sock, (struct sockaddr *)&address, addrlen); if (err) goto out_put; err = sock->ops->connect(sock, (struct sockaddr *)&address, addrlen, sock->file->f_flags); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the local address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = security_socket_getsockname(sock); if (err) goto out_put; err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 0); if (err) goto out_put; err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the remote address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getpeername(sock); if (err) { fput_light(sock->file, fput_needed); return err; } err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 1); if (!err) err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); fput_light(sock->file, fput_needed); } return err; } /* * Send a datagram to a given address. We move the address into kernel * space and check the user space data area is readable before invoking * the protocol. */ SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; err = import_single_range(WRITE, buff, len, &iov, &msg.msg_iter); if (unlikely(err)) return err; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_name = NULL; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Send a datagram down a socket. */ SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len, unsigned int, flags) { return sys_sendto(fd, buff, len, flags, NULL, 0); } /* * Receive a frame from the socket and optionally record the address of the * sender. We verify the buffers are writable and if needed move the * sender address from kernel to user space. */ SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; err = import_single_range(READ, ubuf, size, &iov, &msg.msg_iter); if (unlikely(err)) return err; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; msg.msg_iocb = NULL; msg.msg_flags = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } /* * Receive a datagram from a socket. */ SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags) { return sys_recvfrom(fd, ubuf, size, flags, NULL, NULL); } /* * Set a socket option. Because we don't know the option lengths we have * to pass the user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname, char __user *, optval, int, optlen) { int err, fput_needed; struct socket *sock; if (optlen < 0) return -EINVAL; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_setsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, optval, optlen); else err = sock->ops->setsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Get a socket option. Because we don't know the option lengths we have * to pass a user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname, char __user *, optval, int __user *, optlen) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, optval, optlen); else err = sock->ops->getsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Shutdown a socket. */ SYSCALL_DEFINE2(shutdown, int, fd, int, how) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_shutdown(sock, how); if (!err) err = sock->ops->shutdown(sock, how); fput_light(sock->file, fput_needed); } return err; } /* A couple of helpful macros for getting the address of the 32/64 bit * fields which are the same type (int / unsigned) on our platforms. */ #define COMPAT_MSG(msg, member) ((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member) #define COMPAT_NAMELEN(msg) COMPAT_MSG(msg, msg_namelen) #define COMPAT_FLAGS(msg) COMPAT_MSG(msg, msg_flags) struct used_address { struct sockaddr_storage name; unsigned int name_len; }; static int copy_msghdr_from_user(struct msghdr *kmsg, struct user_msghdr __user *umsg, struct sockaddr __user **save_addr, struct iovec **iov) { struct sockaddr __user *uaddr; struct iovec __user *uiov; size_t nr_segs; ssize_t err; if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) || __get_user(uaddr, &umsg->msg_name) || __get_user(kmsg->msg_namelen, &umsg->msg_namelen) || __get_user(uiov, &umsg->msg_iov) || __get_user(nr_segs, &umsg->msg_iovlen) || __get_user(kmsg->msg_control, &umsg->msg_control) || __get_user(kmsg->msg_controllen, &umsg->msg_controllen) || __get_user(kmsg->msg_flags, &umsg->msg_flags)) return -EFAULT; if (!uaddr) kmsg->msg_namelen = 0; if (kmsg->msg_namelen < 0) return -EINVAL; if (kmsg->msg_namelen > sizeof(struct sockaddr_storage)) kmsg->msg_namelen = sizeof(struct sockaddr_storage); if (save_addr) *save_addr = uaddr; if (uaddr && kmsg->msg_namelen) { if (!save_addr) { err = move_addr_to_kernel(uaddr, kmsg->msg_namelen, kmsg->msg_name); if (err < 0) return err; } } else { kmsg->msg_name = NULL; kmsg->msg_namelen = 0; } if (nr_segs > UIO_MAXIOV) return -EMSGSIZE; kmsg->msg_iocb = NULL; return import_iovec(save_addr ? READ : WRITE, uiov, nr_segs, UIO_FASTIOV, iov, &kmsg->msg_iter); } static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, struct used_address *used_address, unsigned int allowed_msghdr_flags) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __aligned(sizeof(__kernel_size_t)); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int ctl_len; ssize_t err; msg_sys->msg_name = &address; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, NULL, &iov); else err = copy_msghdr_from_user(msg_sys, msg, NULL, &iov); if (err < 0) return err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; flags |= (msg_sys->msg_flags & allowed_msghdr_flags); ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { BUILD_BUG_ON(sizeof(struct cmsghdr) != CMSG_ALIGN(sizeof(struct cmsghdr))); if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && msg_sys->msg_name && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg_sys->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys); goto out_freectl; } err = sock_sendmsg(sock, msg_sys); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; if (msg_sys->msg_name) memcpy(&used_address->name, msg_sys->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: kfree(iov); return err; } /* * BSD sendmsg interface */ long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL, 0); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmsg(fd, msg, flags); } /* * Linux sendmmsg interface */ int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct used_address used_address; unsigned int oflags = flags; if (vlen > UIO_MAXIOV) vlen = UIO_MAXIOV; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; used_address.name_len = UINT_MAX; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; err = 0; flags |= MSG_BATCH; while (datagrams < vlen) { if (datagrams == vlen - 1) flags = oflags; if (MSG_CMSG_COMPAT & flags) { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags, &used_address, MSG_EOR); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags, &used_address, MSG_EOR); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; if (msg_data_left(&msg_sys)) break; cond_resched(); } fput_light(sock->file, fput_needed); /* We only return an error if no datagrams were able to be sent */ if (datagrams != 0) return datagrams; return err; } SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmmsg(fd, mmsg, vlen, flags); } static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, int nosec) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; unsigned long cmsg_ptr; int len; ssize_t err; /* kernel mode address */ struct sockaddr_storage addr; /* user mode address pointers */ struct sockaddr __user *uaddr; int __user *uaddr_len = COMPAT_NAMELEN(msg); msg_sys->msg_name = &addr; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, &uaddr, &iov); else err = copy_msghdr_from_user(msg_sys, msg, &uaddr, &iov); if (err < 0) return err; cmsg_ptr = (unsigned long)msg_sys->msg_control; msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); /* We assume all kernel code knows the size of sockaddr_storage */ msg_sys->msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, flags); if (err < 0) goto out_freeiov; len = err; if (uaddr != NULL) { err = move_addr_to_user(&addr, msg_sys->msg_namelen, uaddr, uaddr_len); if (err < 0) goto out_freeiov; } err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT), COMPAT_FLAGS(msg)); if (err) goto out_freeiov; if (MSG_CMSG_COMPAT & flags) err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg_compat->msg_controllen); else err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg->msg_controllen); if (err) goto out_freeiov; err = len; out_freeiov: kfree(iov); return err; } /* * BSD recvmsg interface */ long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_recvmsg(sock, msg, &msg_sys, flags, 0); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_recvmsg(fd, msg, flags); } /* * Linux recvmmsg interface */ int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct timespec64 end_time; struct timespec64 timeout64; if (timeout && poll_select_set_timeout(&end_time, timeout->tv_sec, timeout->tv_nsec)) return -EINVAL; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; err = sock_error(sock->sk); if (err) { datagrams = err; goto out_put; } entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; while (datagrams < vlen) { /* * No need to ask LSM for more than the first datagram. */ if (MSG_CMSG_COMPAT & flags) { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */ if (flags & MSG_WAITFORONE) flags |= MSG_DONTWAIT; if (timeout) { ktime_get_ts64(&timeout64); *timeout = timespec64_to_timespec( timespec64_sub(end_time, timeout64)); if (timeout->tv_sec < 0) { timeout->tv_sec = timeout->tv_nsec = 0; break; } /* Timeout, return less than vlen datagrams */ if (timeout->tv_nsec == 0 && timeout->tv_sec == 0) break; } /* Out of band data, return right away */ if (msg_sys.msg_flags & MSG_OOB) break; cond_resched(); } if (err == 0) goto out_put; if (datagrams == 0) { datagrams = err; goto out_put; } /* * We may return less entries than requested (vlen) if the * sock is non block and there aren't enough datagrams... */ if (err != -EAGAIN) { /* * ... or if recvmsg returns an error after we * received some datagrams, where we record the * error to return on the next call or if the * app asks about it using getsockopt(SO_ERROR). */ sock->sk->sk_err = -err; } out_put: fput_light(sock->file, fput_needed); return datagrams; } SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags, struct timespec __user *, timeout) { int datagrams; struct timespec timeout_sys; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (!timeout) return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL); if (copy_from_user(&timeout_sys, timeout, sizeof(timeout_sys))) return -EFAULT; datagrams = __sys_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys); if (datagrams > 0 && copy_to_user(timeout, &timeout_sys, sizeof(timeout_sys))) datagrams = -EFAULT; return datagrams; } #ifdef __ARCH_WANT_SYS_SOCKETCALL /* Argument list sizes for sys_socketcall */ #define AL(x) ((x) * sizeof(unsigned long)) static const unsigned char nargs[21] = { AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4) }; #undef AL /* * System call vectors. * * Argument checking cleaned up. Saved 20% in size. * This function doesn't need to set the kernel lock because * it is set by the callees. */ SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) { unsigned long a[AUDITSC_ARGS]; unsigned long a0, a1; int err; unsigned int len; if (call < 1 || call > SYS_SENDMMSG) return -EINVAL; len = nargs[call]; if (len > sizeof(a)) return -EINVAL; /* copy_from_user should be SMP safe. */ if (copy_from_user(a, args, len)) return -EFAULT; err = audit_socketcall(nargs[call] / sizeof(unsigned long), a); if (err) return err; a0 = a[0]; a1 = a[1]; switch (call) { case SYS_SOCKET: err = sys_socket(a0, a1, a[2]); break; case SYS_BIND: err = sys_bind(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_CONNECT: err = sys_connect(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_LISTEN: err = sys_listen(a0, a1); break; case SYS_ACCEPT: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], 0); break; case SYS_GETSOCKNAME: err = sys_getsockname(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_GETPEERNAME: err = sys_getpeername(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_SOCKETPAIR: err = sys_socketpair(a0, a1, a[2], (int __user *)a[3]); break; case SYS_SEND: err = sys_send(a0, (void __user *)a1, a[2], a[3]); break; case SYS_SENDTO: err = sys_sendto(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], a[5]); break; case SYS_RECV: err = sys_recv(a0, (void __user *)a1, a[2], a[3]); break; case SYS_RECVFROM: err = sys_recvfrom(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], (int __user *)a[5]); break; case SYS_SHUTDOWN: err = sys_shutdown(a0, a1); break; case SYS_SETSOCKOPT: err = sys_setsockopt(a0, a1, a[2], (char __user *)a[3], a[4]); break; case SYS_GETSOCKOPT: err = sys_getsockopt(a0, a1, a[2], (char __user *)a[3], (int __user *)a[4]); break; case SYS_SENDMSG: err = sys_sendmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_SENDMMSG: err = sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3]); break; case SYS_RECVMSG: err = sys_recvmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_RECVMMSG: err = sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3], (struct timespec __user *)a[4]); break; case SYS_ACCEPT4: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], a[3]); break; default: err = -EINVAL; break; } return err; } #endif /* __ARCH_WANT_SYS_SOCKETCALL */ /** * sock_register - add a socket protocol handler * @ops: description of protocol * * This function is called by a protocol handler that wants to * advertise its address family, and have it linked into the * socket interface. The value ops->family corresponds to the * socket system call protocol family. */ int sock_register(const struct net_proto_family *ops) { int err; if (ops->family >= NPROTO) { pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO); return -ENOBUFS; } spin_lock(&net_family_lock); if (rcu_dereference_protected(net_families[ops->family], lockdep_is_held(&net_family_lock))) err = -EEXIST; else { rcu_assign_pointer(net_families[ops->family], ops); err = 0; } spin_unlock(&net_family_lock); pr_info("NET: Registered protocol family %d\n", ops->family); return err; } EXPORT_SYMBOL(sock_register); /** * sock_unregister - remove a protocol handler * @family: protocol family to remove * * This function is called by a protocol handler that wants to * remove its address family, and have it unlinked from the * new socket creation. * * If protocol handler is a module, then it can use module reference * counts to protect against new references. If protocol handler is not * a module then it needs to provide its own protection in * the ops->create routine. */ void sock_unregister(int family) { BUG_ON(family < 0 || family >= NPROTO); spin_lock(&net_family_lock); RCU_INIT_POINTER(net_families[family], NULL); spin_unlock(&net_family_lock); synchronize_rcu(); pr_info("NET: Unregistered protocol family %d\n", family); } EXPORT_SYMBOL(sock_unregister); static int __init sock_init(void) { int err; /* * Initialize the network sysctl infrastructure. */ err = net_sysctl_init(); if (err) goto out; /* * Initialize skbuff SLAB cache */ skb_init(); /* * Initialize the protocols module. */ init_inodecache(); err = register_filesystem(&sock_fs_type); if (err) goto out_fs; sock_mnt = kern_mount(&sock_fs_type); if (IS_ERR(sock_mnt)) { err = PTR_ERR(sock_mnt); goto out_mount; } /* The real protocol initialization is performed in later initcalls. */ #ifdef CONFIG_NETFILTER err = netfilter_init(); if (err) goto out; #endif ptp_classifier_init(); out: return err; out_mount: unregister_filesystem(&sock_fs_type); out_fs: goto out; } core_initcall(sock_init); /* early initcall */ #ifdef CONFIG_PROC_FS void socket_seq_show(struct seq_file *seq) { int cpu; int counter = 0; for_each_possible_cpu(cpu) counter += per_cpu(sockets_in_use, cpu); /* It can be negative, by the way. 8) */ if (counter < 0) counter = 0; seq_printf(seq, "sockets: used %d\n", counter); } #endif /* CONFIG_PROC_FS */ #ifdef CONFIG_COMPAT static int do_siocgstamp(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timeval ktv; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv); set_fs(old_fs); if (!err) err = compat_put_timeval(&ktv, up); return err; } static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(&kts, up); return err; } static int dev_ifname32(struct net *net, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(struct ifreq)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; err = dev_ioctl(net, SIOCGIFNAME, uifr); if (err) return err; if (copy_in_user(uifr32, uifr, sizeof(struct compat_ifreq))) return -EFAULT; return 0; } static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; memset(&ifc, 0, sizeof(ifc)); if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; } static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) { struct compat_ethtool_rxnfc __user *compat_rxnfc; bool convert_in = false, convert_out = false; size_t buf_size = ALIGN(sizeof(struct ifreq), 8); struct ethtool_rxnfc __user *rxnfc; struct ifreq __user *ifr; u32 rule_cnt = 0, actual_rule_cnt; u32 ethcmd; u32 data; int ret; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; compat_rxnfc = compat_ptr(data); if (get_user(ethcmd, &compat_rxnfc->cmd)) return -EFAULT; /* Most ethtool structures are defined without padding. * Unfortunately struct ethtool_rxnfc is an exception. */ switch (ethcmd) { default: break; case ETHTOOL_GRXCLSRLALL: /* Buffer size is variable */ if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) return -EFAULT; if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) return -ENOMEM; buf_size += rule_cnt * sizeof(u32); /* fall through */ case ETHTOOL_GRXRINGS: case ETHTOOL_GRXCLSRLCNT: case ETHTOOL_GRXCLSRULE: case ETHTOOL_SRXCLSRLINS: convert_out = true; /* fall through */ case ETHTOOL_SRXCLSRLDEL: buf_size += sizeof(struct ethtool_rxnfc); convert_in = true; break; } ifr = compat_alloc_user_space(buf_size); rxnfc = (void __user *)ifr + ALIGN(sizeof(struct ifreq), 8); if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (put_user(convert_in ? rxnfc : compat_ptr(data), &ifr->ifr_ifru.ifru_data)) return -EFAULT; if (convert_in) { /* We expect there to be holes between fs.m_ext and * fs.ring_cookie and at the end of fs, but nowhere else. */ BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + sizeof(compat_rxnfc->fs.m_ext) != offsetof(struct ethtool_rxnfc, fs.m_ext) + sizeof(rxnfc->fs.m_ext)); BUILD_BUG_ON( offsetof(struct compat_ethtool_rxnfc, fs.location) - offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != offsetof(struct ethtool_rxnfc, fs.location) - offsetof(struct ethtool_rxnfc, fs.ring_cookie)); if (copy_in_user(rxnfc, compat_rxnfc, (void __user *)(&rxnfc->fs.m_ext + 1) - (void __user *)rxnfc) || copy_in_user(&rxnfc->fs.ring_cookie, &compat_rxnfc->fs.ring_cookie, (void __user *)(&rxnfc->fs.location + 1) - (void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; } ret = dev_ioctl(net, SIOCETHTOOL, ifr); if (ret) return ret; if (convert_out) { if (copy_in_user(compat_rxnfc, rxnfc, (const void __user *)(&rxnfc->fs.m_ext + 1) - (const void __user *)rxnfc) || copy_in_user(&compat_rxnfc->fs.ring_cookie, &rxnfc->fs.ring_cookie, (const void __user *)(&rxnfc->fs.location + 1) - (const void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; if (ethcmd == ETHTOOL_GRXCLSRLALL) { /* As an optimisation, we only copy the actual * number of rules that the underlying * function returned. Since Mallory might * change the rule count in user memory, we * check that it is less than the rule count * originally given (as the user buffer size), * which has been range-checked. */ if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) return -EFAULT; if (actual_rule_cnt < rule_cnt) rule_cnt = actual_rule_cnt; if (copy_in_user(&compat_rxnfc->rule_locs[0], &rxnfc->rule_locs[0], rule_cnt * sizeof(u32))) return -EFAULT; } } return 0; } static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_settings.ifs_ifsu.raw_hdlc)) return -EFAULT; return dev_ioctl(net, SIOCWANDEV, uifr); } static int bond_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *ifr32) { struct ifreq kifr; mm_segment_t old_fs; int err; switch (cmd) { case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (struct ifreq __user __force *) &kifr); set_fs(old_fs); return err; default: return -ENOIOCTLCMD; } } /* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */ static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *u_ifreq32) { struct ifreq __user *u_ifreq64; char tmp_buf[IFNAMSIZ]; void __user *data64; u32 data32; if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]), IFNAMSIZ)) return -EFAULT; if (get_user(data32, &u_ifreq32->ifr_ifru.ifru_data)) return -EFAULT; data64 = compat_ptr(data32); u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64)); if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0], IFNAMSIZ)) return -EFAULT; if (put_user(data64, &u_ifreq64->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, u_ifreq64); } static int dev_ifsioc(struct net *net, struct socket *sock, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(*uifr32))) return -EFAULT; err = sock_do_ioctl(net, sock, cmd, (unsigned long)uifr); if (!err) { switch (cmd) { case SIOCGIFFLAGS: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFMEM: case SIOCGIFHWADDR: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFDSTADDR: case SIOCGIFNETMASK: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCGMIIPHY: case SIOCGMIIREG: if (copy_in_user(uifr32, uifr, sizeof(*uifr32))) err = -EFAULT; break; } } return err; } static int compat_sioc_ifmap(struct net *net, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq ifr; struct compat_ifmap __user *uifmap32; mm_segment_t old_fs; int err; uifmap32 = &uifr32->ifr_ifru.ifru_map; err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name)); err |= get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= get_user(ifr.ifr_map.irq, &uifmap32->irq); err |= get_user(ifr.ifr_map.dma, &uifmap32->dma); err |= get_user(ifr.ifr_map.port, &uifmap32->port); if (err) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (void __user __force *)&ifr); set_fs(old_fs); if (cmd == SIOCGIFMAP && !err) { err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name)); err |= put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= put_user(ifr.ifr_map.irq, &uifmap32->irq); err |= put_user(ifr.ifr_map.dma, &uifmap32->dma); err |= put_user(ifr.ifr_map.port, &uifmap32->port); if (err) err = -EFAULT; } return err; } struct rtentry32 { u32 rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; u32 rt_pad3; unsigned char rt_tos; unsigned char rt_class; short rt_pad4; short rt_metric; /* +1 for binary compatibility! */ /* char * */ u32 rt_dev; /* forcing the device at add */ u32 rt_mtu; /* per route MTU/Window */ u32 rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; struct in6_rtmsg32 { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; u32 rtmsg_type; u16 rtmsg_dst_len; u16 rtmsg_src_len; u32 rtmsg_metric; u32 rtmsg_info; u32 rtmsg_flags; s32 rtmsg_ifindex; }; static int routing_ioctl(struct net *net, struct socket *sock, unsigned int cmd, void __user *argp) { int ret; void *r = NULL; struct in6_rtmsg r6; struct rtentry r4; char devname[16]; u32 rtdev; mm_segment_t old_fs = get_fs(); if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */ struct in6_rtmsg32 __user *ur6 = argp; ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst), 3 * sizeof(struct in6_addr)); ret |= get_user(r6.rtmsg_type, &(ur6->rtmsg_type)); ret |= get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len)); ret |= get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len)); ret |= get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric)); ret |= get_user(r6.rtmsg_info, &(ur6->rtmsg_info)); ret |= get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags)); ret |= get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex)); r = (void *) &r6; } else { /* ipv4 */ struct rtentry32 __user *ur4 = argp; ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst), 3 * sizeof(struct sockaddr)); ret |= get_user(r4.rt_flags, &(ur4->rt_flags)); ret |= get_user(r4.rt_metric, &(ur4->rt_metric)); ret |= get_user(r4.rt_mtu, &(ur4->rt_mtu)); ret |= get_user(r4.rt_window, &(ur4->rt_window)); ret |= get_user(r4.rt_irtt, &(ur4->rt_irtt)); ret |= get_user(rtdev, &(ur4->rt_dev)); if (rtdev) { ret |= copy_from_user(devname, compat_ptr(rtdev), 15); r4.rt_dev = (char __user __force *)devname; devname[15] = 0; } else r4.rt_dev = NULL; r = (void *) &r4; } if (ret) { ret = -EFAULT; goto out; } set_fs(KERNEL_DS); ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r); set_fs(old_fs); out: return ret; } /* Since old style bridge ioctl's endup using SIOCDEVPRIVATE * for some operations; this forces use of the newer bridge-utils that * use compatible ioctls */ static int old_bridge_ioctl(compat_ulong_t __user *argp) { compat_ulong_t tmp; if (get_user(tmp, argp)) return -EFAULT; if (tmp == BRCTL_GET_VERSION) return BRCTL_VERSION + 1; return -EINVAL; } static int compat_sock_ioctl_trans(struct file *file, struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); struct sock *sk = sock->sk; struct net *net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) return compat_ifr_data_ioctl(net, cmd, argp); switch (cmd) { case SIOCSIFBR: case SIOCGIFBR: return old_bridge_ioctl(argp); case SIOCGIFNAME: return dev_ifname32(net, argp); case SIOCGIFCONF: return dev_ifconf(net, argp); case SIOCETHTOOL: return ethtool_ioctl(net, argp); case SIOCWANDEV: return compat_siocwandev(net, argp); case SIOCGIFMAP: case SIOCSIFMAP: return compat_sioc_ifmap(net, cmd, argp); case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: return bond_ioctl(net, cmd, argp); case SIOCADDRT: case SIOCDELRT: return routing_ioctl(net, sock, cmd, argp); case SIOCGSTAMP: return do_siocgstamp(net, sock, cmd, argp); case SIOCGSTAMPNS: return do_siocgstampns(net, sock, cmd, argp); case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: case SIOCSHWTSTAMP: case SIOCGHWTSTAMP: return compat_ifr_data_ioctl(net, cmd, argp); case FIOSETOWN: case SIOCSPGRP: case FIOGETOWN: case SIOCGPGRP: case SIOCBRADDBR: case SIOCBRDELBR: case SIOCGIFVLAN: case SIOCSIFVLAN: case SIOCADDDLCI: case SIOCDELDLCI: case SIOCGSKNS: return sock_ioctl(file, cmd, arg); case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFMETRIC: case SIOCSIFMETRIC: case SIOCGIFMTU: case SIOCSIFMTU: case SIOCGIFMEM: case SIOCSIFMEM: case SIOCGIFHWADDR: case SIOCSIFHWADDR: case SIOCADDMULTI: case SIOCDELMULTI: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCSIFHWBROADCAST: case SIOCDIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCSIFTXQLEN: case SIOCBRADDIF: case SIOCBRDELIF: case SIOCSIFNAME: case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return dev_ifsioc(net, sock, cmd, argp); case SIOCSARP: case SIOCGARP: case SIOCDARP: case SIOCATMARK: return sock_do_ioctl(net, sock, cmd, arg); } return -ENOIOCTLCMD; } static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct socket *sock = file->private_data; int ret = -ENOIOCTLCMD; struct sock *sk; struct net *net; sk = sock->sk; net = sock_net(sk); if (sock->ops->compat_ioctl) ret = sock->ops->compat_ioctl(sock, cmd, arg); if (ret == -ENOIOCTLCMD && (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)) ret = compat_wext_handle_ioctl(net, cmd, arg); if (ret == -ENOIOCTLCMD) ret = compat_sock_ioctl_trans(file, sock, cmd, arg); return ret; } #endif int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen) { return sock->ops->bind(sock, addr, addrlen); } EXPORT_SYMBOL(kernel_bind); int kernel_listen(struct socket *sock, int backlog) { return sock->ops->listen(sock, backlog); } EXPORT_SYMBOL(kernel_listen); int kernel_accept(struct socket *sock, struct socket **newsock, int flags) { struct sock *sk = sock->sk; int err; err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol, newsock); if (err < 0) goto done; err = sock->ops->accept(sock, *newsock, flags, true); if (err < 0) { sock_release(*newsock); *newsock = NULL; goto done; } (*newsock)->ops = sock->ops; __module_get((*newsock)->ops->owner); done: return err; } EXPORT_SYMBOL(kernel_accept); int kernel_connect(struct socket *sock, struct sockaddr *addr, int addrlen, int flags) { return sock->ops->connect(sock, addr, addrlen, flags); } EXPORT_SYMBOL(kernel_connect); int kernel_getsockname(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 0); } EXPORT_SYMBOL(kernel_getsockname); int kernel_getpeername(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 1); } EXPORT_SYMBOL(kernel_getpeername); int kernel_getsockopt(struct socket *sock, int level, int optname, char *optval, int *optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int __user *uoptlen; int err; uoptval = (char __user __force *) optval; uoptlen = (int __user __force *) optlen; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, uoptval, uoptlen); else err = sock->ops->getsockopt(sock, level, optname, uoptval, uoptlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_getsockopt); int kernel_setsockopt(struct socket *sock, int level, int optname, char *optval, unsigned int optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int err; uoptval = (char __user __force *) optval; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, uoptval, optlen); else err = sock->ops->setsockopt(sock, level, optname, uoptval, optlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_setsockopt); int kernel_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { if (sock->ops->sendpage) return sock->ops->sendpage(sock, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } EXPORT_SYMBOL(kernel_sendpage); int kernel_sock_ioctl(struct socket *sock, int cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); int err; set_fs(KERNEL_DS); err = sock->ops->ioctl(sock, cmd, arg); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_sock_ioctl); int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how) { return sock->ops->shutdown(sock, how); } EXPORT_SYMBOL(kernel_sock_shutdown);
./CrossVul/dataset_final_sorted/CWE-125/c/good_3254_2
crossvul-cpp_data_good_2719_0
/* * Copyright (C) 1999 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 /* draft-ietf-idr-shutdown-07 */ #define BGP_NOTIFY_MINOR_CEASE_SHUT 2 #define BGP_NOTIFY_MINOR_CEASE_RESET 4 #define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"}, { 3, "Peer Unconfigured"}, { BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 0, "Unspecified Error"}, { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (0 == plen) { snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; plen-=32; /* adjust prefix length */ if (64 < plen) return -1; memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[1], (plen + 7) / 8); memcpy(&route_target, &pptr[1], (plen + 7) / 8); if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, { 0, NULL} }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN + 4; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; ND_TCHECK2(tptr[0], 5); tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; tlen = len; while (tlen >= 3) { ND_TCHECK2(tptr[0], 3); type = *tptr; length = EXTRACT_16BITS(tptr+1); tptr += 3; tlen -= 3; ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); if (length < 3) goto trunc; length -= 3; /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length); switch (type) { case BGP_AIGP_TLV: if (length < 8) goto trunc; ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr,"\n\t ", length); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; uint8_t shutdown_comm_length; uint8_t remainder_offset; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } /* * draft-ietf-idr-shutdown describes a method to send a communication * intended for human consumption regarding the Administrative Shutdown */ if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT || bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) && length >= BGP_NOTIFICATION_SIZE + 1) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 1); shutdown_comm_length = *(tptr); remainder_offset = 0; /* garbage, hexdump it all */ if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN || shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) { ND_PRINT((ndo, ", invalid Shutdown Communication length")); } else if (shutdown_comm_length == 0) { ND_PRINT((ndo, ", empty Shutdown Communication")); remainder_offset += 1; } /* a proper shutdown communication */ else { ND_TCHECK2(*(tptr+1), shutdown_comm_length); ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length)); (void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL); ND_PRINT((ndo, "\"")); remainder_offset += shutdown_comm_length + 1; } /* if there is trailing data, hexdump it */ if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) { ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE))); hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE)); } } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2719_0
crossvul-cpp_data_good_2665_0
/* * Copyright (c) 1989, 1990, 1991, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IPv6 Routing Information Protocol (RIPng) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" /* * Copyright (C) 1995, 1996, 1997 and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define RIP6_VERSION 1 #define RIP6_REQUEST 1 #define RIP6_RESPONSE 2 struct netinfo6 { struct in6_addr rip6_dest; uint16_t rip6_tag; uint8_t rip6_plen; uint8_t rip6_metric; }; struct rip6 { uint8_t rip6_cmd; uint8_t rip6_vers; uint8_t rip6_res1[2]; union { struct netinfo6 ru6_nets[1]; char ru6_tracefile[1]; } rip6un; #define rip6_nets rip6un.ru6_nets #define rip6_tracefile rip6un.ru6_tracefile }; #define HOPCNT_INFINITY6 16 #if !defined(IN6_IS_ADDR_UNSPECIFIED) && !defined(_MSC_VER) /* MSVC inline */ static int IN6_IS_ADDR_UNSPECIFIED(const struct in6_addr *addr) { static const struct in6_addr in6addr_any; /* :: */ return (memcmp(addr, &in6addr_any, sizeof(*addr)) == 0); } #endif static int rip6_entry_print(netdissect_options *ndo, register const struct netinfo6 *ni, int metric) { int l; l = ND_PRINT((ndo, "%s/%d", ip6addr_string(ndo, &ni->rip6_dest), ni->rip6_plen)); if (ni->rip6_tag) l += ND_PRINT((ndo, " [%d]", EXTRACT_16BITS(&ni->rip6_tag))); if (metric) l += ND_PRINT((ndo, " (%d)", ni->rip6_metric)); return l; } void ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length) { register const struct rip6 *rp = (const struct rip6 *)dat; register const struct netinfo6 *ni; unsigned int length_left; u_int j; ND_TCHECK(rp->rip6_cmd); switch (rp->rip6_cmd) { case RIP6_REQUEST: length_left = length; if (length_left < (sizeof(struct rip6) - sizeof(struct netinfo6))) goto trunc; length_left -= (sizeof(struct rip6) - sizeof(struct netinfo6)); j = length_left / sizeof(*ni); if (j == 1) { ND_TCHECK(rp->rip6_nets); if (rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6 && IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) { ND_PRINT((ndo, " ripng-req dump")); break; } } if (j * sizeof(*ni) != length_left) ND_PRINT((ndo, " ripng-req %u[%u]:", j, length)); else ND_PRINT((ndo, " ripng-req %u:", j)); for (ni = rp->rip6_nets; length_left >= sizeof(*ni); length_left -= sizeof(*ni), ++ni) { ND_TCHECK(*ni); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, 0); } if (length_left != 0) goto trunc; break; case RIP6_RESPONSE: length_left = length; if (length_left < (sizeof(struct rip6) - sizeof(struct netinfo6))) goto trunc; length_left -= (sizeof(struct rip6) - sizeof(struct netinfo6)); j = length_left / sizeof(*ni); if (j * sizeof(*ni) != length_left) ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-resp %d:", j)); for (ni = rp->rip6_nets; length_left >= sizeof(*ni); length_left -= sizeof(*ni), ++ni) { ND_TCHECK(*ni); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, ni->rip6_metric); } if (length_left != 0) goto trunc; break; default: ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length)); break; } ND_TCHECK(rp->rip6_vers); if (rp->rip6_vers != RIP6_VERSION) ND_PRINT((ndo, " [vers %d]", rp->rip6_vers)); return; trunc: ND_PRINT((ndo, "[|ripng]")); return; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2665_0
crossvul-cpp_data_good_501_0
/* radare - LGPL - Copyright 2010-2018 - pancake */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <r_util.h> #include "armass16_const.h" // TODO: only lo registers accessible in thumb arm typedef struct { ut64 off; ut32 o; char op[128]; char opstr[128]; char *a[16]; /* only 15 arguments can be used! */ } ArmOpcode; typedef struct { const char *name; int code; int type; } ArmOp; enum { TYPE_MOV = 1, TYPE_TST = 2, TYPE_SWI = 3, TYPE_HLT = 4, TYPE_BRA = 5, TYPE_BRR = 6, TYPE_ARI = 7, TYPE_IMM = 8, TYPE_MEM = 9, TYPE_BKP = 10, TYPE_SWP = 11, TYPE_MOVW = 12, TYPE_MOVT = 13, TYPE_UDF = 14, TYPE_SHFT = 15, TYPE_COPROC = 16, TYPE_ENDIAN = 17, TYPE_MUL = 18, TYPE_CLZ = 19, TYPE_REV = 20, }; static int strcmpnull(const char *a, const char *b) { if (!a || !b) { return -1; } return strcmp (a, b); } // static const char *const arm_shift[] = {"lsl", "lsr", "asr", "ror"}; static ArmOp ops[] = { { "adc", 0xa000, TYPE_ARI }, { "adcs", 0xb000, TYPE_ARI }, { "adds", 0x9000, TYPE_ARI }, { "add", 0x8000, TYPE_ARI }, { "bkpt", 0x2001, TYPE_BKP }, { "subs", 0x5000, TYPE_ARI }, { "sub", 0x4000, TYPE_ARI }, { "sbcs", 0xd000, TYPE_ARI }, { "sbc", 0xc000, TYPE_ARI }, { "rsb", 0x6000, TYPE_ARI }, { "rsbs", 0x7000, TYPE_ARI }, { "rsc", 0xe000, TYPE_ARI }, { "rscs", 0xf000, TYPE_ARI }, { "bic", 0x0000c0e1, TYPE_ARI }, { "udf", 0xf000f000, TYPE_UDF }, { "push", 0x2d09, TYPE_IMM }, { "pop", 0xbd08, TYPE_IMM }, { "cps", 0xb1, TYPE_IMM }, { "nop", 0xa0e1, -1 }, { "ldrex", 0x9f0f9000, TYPE_MEM }, { "ldr", 0x9000, TYPE_MEM }, { "strexh", 0x900fe000, TYPE_MEM }, { "strexb", 0x900fc000, TYPE_MEM }, { "strex", 0x900f8000, TYPE_MEM }, { "strbt", 0x0000e0e4, TYPE_MEM }, { "strb", 0x0000c0e5, TYPE_MEM }, { "strd", 0xf000c0e1, TYPE_MEM }, { "strh", 0xb00080e1, TYPE_MEM }, { "str", 0x8000, TYPE_MEM }, { "blx", 0x30ff2fe1, TYPE_BRR }, { "bx", 0x10ff2fe1, TYPE_BRR }, { "bl", 0xb, TYPE_BRA }, // bx/blx - to register, b, bne,.. justjust offset // 2220: e12fff1e bx lr // 2224: e12fff12 bx r2 // 2228: e12fff13 bx r3 //{ "bx", 0xb, TYPE_BRA }, { "b", 0xa, TYPE_BRA }, //{ "mov", 0x3, TYPE_MOV }, //{ "mov", 0x0a3, TYPE_MOV }, { "movw", 0x3, TYPE_MOVW }, { "movt", 0x4003, TYPE_MOVT }, { "mov", 0xa001, TYPE_MOV }, { "mvn", 0xe000, TYPE_MOV }, { "svc", 0xf, TYPE_SWI }, // ??? { "hlt", 0x70000001, TYPE_HLT }, // ???u { "mul", 0x900000e0, TYPE_MUL}, { "smull", 0x9000c0e0, TYPE_MUL}, { "umull", 0x900080e0, TYPE_MUL}, { "smlal", 0x9000e0e0, TYPE_MUL}, { "smlabb", 0x800000e1, TYPE_MUL}, { "smlabt", 0xc00000e1, TYPE_MUL}, { "smlatb", 0xa00000e1, TYPE_MUL}, { "smlatt", 0xe00000e1, TYPE_MUL}, { "smlawb", 0x800020e1, TYPE_MUL}, { "smlawt", 0xc00020e1, TYPE_MUL}, { "ands", 0x1000, TYPE_ARI }, { "and", 0x0000, TYPE_ARI }, { "eors", 0x3000, TYPE_ARI }, { "eor", 0x2000, TYPE_ARI }, { "orrs", 0x9001, TYPE_ARI }, { "orr", 0x8001, TYPE_ARI }, { "cmp", 0x5001, TYPE_TST }, { "swp", 0xe1, TYPE_SWP }, { "cmn", 0x0, TYPE_TST }, { "teq", 0x0, TYPE_TST }, { "tst", 0xe1, TYPE_TST }, {"lsr", 0x3000a0e1, TYPE_SHFT}, {"asr", 0x5000a0e1, TYPE_SHFT}, {"lsl", 0x1000a0e1, TYPE_SHFT}, {"ror", 0x7000a0e1, TYPE_SHFT}, {"rev16", 0xb00fbf06, TYPE_REV}, {"revsh", 0xb00fff06, TYPE_REV}, {"rev", 0x300fbf06, TYPE_REV}, {"rbit", 0x300fff06, TYPE_REV}, {"mrc", 0x100010ee, TYPE_COPROC}, {"setend", 0x000001f1, TYPE_ENDIAN}, { "clz", 0x000f6f01, TYPE_CLZ}, { NULL } }; static const ut64 M_BIT = 0x1; static const ut64 S_BIT = 0x2; static const ut64 C_BITS = 0x3c; static const ut64 DOTN_BIT = 0x40; static const ut64 DOTW_BIT = 0x80; static const ut64 L_BIT = 0x100; static const ut64 X_BIT = 0x200; static const ut64 TWO_BIT = 0x400; static const ut64 IE_BIT = 0x800; static const ut64 ID_BIT = 0x1000; static const ut64 EA_BIT = 0x2000; static const ut64 FD_BIT = 0x4000; static const ut64 T_BIT = 0x8000; static const ut64 B_BIT = 0x10000; static const ut64 H_BIT = 0x20000; static const ut64 D_BIT = 0x40000; static const ut64 W_BIT = 0x80000; static const ut64 EIGHT_BIT = 0x100000; static const ut64 SIXTEEN_BIT = 0x200000; static const ut64 BB_BIT = 0x400000; static const ut64 BT_BIT = 0x800000; static const ut64 TB_BIT = 0x1000000; static const ut64 TT_BIT = 0x2000000; static const ut64 R_BIT = 0x4000000; static const ut64 IA_BIT = 0x8000000; static const ut64 DB_BIT = 0x10000000; static const ut64 SH_BIT = 0x20000000; static const ut64 WB_BIT = 0x40000000; static const ut64 WT_BIT = 0x80000000; static const ut64 C_MATCH_BIT = 0x100000000; static char *parse_hints(char *input) { if (!strcmpnull (input, "unst")) { return "6"; } if (!strcmpnull (input, "un")) { return "7"; } if (!strcmpnull (input, "st")) { return "14"; } if (!strcmpnull (input, "sy")) { return "15"; } return "-1"; } static st8 iflag(char *input) { st8 res = 0; ut8 i; r_str_case (input, false); for (i = 0; i < strlen(input); i++) { switch (input[i]) { case 'a': res |= 0x4; break; case 'i': res |= 0x2; break; case 'f': res |= 0x1; break; default: return -1; } } return res; } static ut64 cqcheck(char **input) { ut64 res = 0; int i; ut8 offset = 0; const char *conds[] = { "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", "nv", 0 }; for (i = 0; conds[i]; i++) { if (r_str_startswith (*input, conds[i])) { res |= C_MATCH_BIT; res |= i << 2; *input += 2; offset += 2; break; } } if (r_str_startswith (*input, ".n")) { res |= DOTN_BIT; *input += 2; offset += 2; } else if (r_str_startswith (*input, ".w")) { res |= DOTW_BIT; *input += 2; offset += 2; } if (**input == '\0') { return res; } *input -= offset; return 0; } static ut64 opmask(char *input, char *opcode, ut64 allowed_mask) { ut64 res = 0; r_str_case (input, false); if (strlen (opcode) > strlen (input)) { return 0; } if (r_str_startswith (input, opcode)) { input += strlen (opcode); res |= M_BIT; res |= cqcheck (&input); if ((*input == 's') && (S_BIT & allowed_mask)) { res |= S_BIT; input++; } res |= cqcheck (&input); if ((r_str_startswith (input, "wb")) && (WB_BIT & allowed_mask)) { res |= WB_BIT; input += 2; } if ((r_str_startswith (input, "wt")) && (WT_BIT & allowed_mask)) { res |= WT_BIT; input += 2; } res |= cqcheck (&input); if ((r_str_startswith (input, "db")) && (DB_BIT & allowed_mask)) { res |= DB_BIT; input += 2; } if ((r_str_startswith (input, "ea")) && (EA_BIT & allowed_mask)) { res |= EA_BIT; input += 2; } if ((r_str_startswith (input, "ia")) && (IA_BIT & allowed_mask)) { res |= IA_BIT; input += 2; } if ((r_str_startswith (input, "fd")) && (FD_BIT & allowed_mask)) { res |= FD_BIT; input += 2; } res |= cqcheck (&input); if ((*input == 'l') && (L_BIT & allowed_mask)) { res |= L_BIT; input++; } res |= cqcheck (&input); if ((r_str_startswith (input, "bb")) && (BB_BIT & allowed_mask)) { res |= BB_BIT; input += 2; } if ((r_str_startswith (input, "tt")) && (TT_BIT & allowed_mask)) { res |= TT_BIT; input += 2; } if ((r_str_startswith (input, "bt")) && (BT_BIT & allowed_mask)) { res |= BT_BIT; input += 2; } if ((r_str_startswith (input, "tb")) && (TB_BIT & allowed_mask)) { res |= TB_BIT; input += 2; } res |= cqcheck (&input); if ((*input == 'w') && (W_BIT & allowed_mask)) { res |= W_BIT; input++; } if ((*input == 'b') && (B_BIT & allowed_mask)) { res |= B_BIT; input++; } else if ((*input == 'h') && (H_BIT & allowed_mask)) { res |= H_BIT; input++; } else if ((*input == 'd') && (D_BIT & allowed_mask)) { res |= D_BIT; input++; } if ((*input == 't') && (T_BIT & allowed_mask)) { res |= T_BIT; input++; } if ((*input == 's') && (S_BIT & allowed_mask)) { res |= S_BIT; input++; } res |= cqcheck (&input); if ((*input == 'r') && (R_BIT & allowed_mask)) { res |= R_BIT; input++; } res |= cqcheck (&input); if ((*input == '2') && (TWO_BIT & allowed_mask)) { res |= TWO_BIT; input++; } if ((*input == '8') && (EIGHT_BIT & allowed_mask)) { res |= EIGHT_BIT; input++; } if ((r_str_startswith (input, "16")) && (SIXTEEN_BIT & allowed_mask)) { res |= SIXTEEN_BIT; input += 2; } res |= cqcheck (&input); if ((*input == 'l') && (L_BIT & allowed_mask)) { res |= L_BIT; input++; } if ((*input == 'x') && (X_BIT & allowed_mask)) { res |= X_BIT; input++; } res |= cqcheck (&input); if ((r_str_startswith (input, "id")) && (ID_BIT & allowed_mask)) { res |= ID_BIT; input += 2; } if ((r_str_startswith (input, "ie")) && (IE_BIT & allowed_mask)) { res |= IE_BIT; input += 2; } res |= cqcheck (&input); if ((r_str_startswith (input, "sh")) && (SH_BIT & allowed_mask)) { res |= SH_BIT; input += 2; } res |= cqcheck (&input); if (!(res & C_MATCH_BIT)) { res |= 15 << 2; // nv is the default condition } if (*input == 0) { return res; } } return 0; } static ut32 itmask(char *input) { ut32 res = 0; ut32 i, length; r_str_case (input, false); if (2 > strlen (input)) { return 0; } if (r_str_startswith (input, "it")) { input += 2; res |= 1; // matched if (strlen(input) > 3) { return 0; } res |= (strlen (input) & 0x3) << 4; length = strlen (input); for (i = 0; i < length; i++, input++ ) { if (*input == 'e') { res |= 1 << (3 - i); continue; } if (*input == 't') { continue; } return 0; } return res; } return 0; } static bool err; //decode str as number static ut64 getnum(const char *str) { char *endptr; err = false; ut64 val; if (!str) { err = true; return 0; } while (*str == '$' || *str == '#') { str++; } val = strtol (str, &endptr, 0); if (str != endptr && *endptr == '\0') { return val; } err = true; return 0; } static ut64 getnumbang(const char *str) { ut64 res; if (!str || !*str || !r_str_endswith (str, "!")) { err = true; return 0; } char *temp = r_str_ndup (str, strlen (str) - 1); if (!temp) { return -1; } err = false; res = getnum (temp); free (temp); return res; // err propagates } static ut32 getimmed8(const char *str) { ut32 num = getnum (str); if (err) { return 0; } ut32 rotate; if (num <= 0xff) { return num; } else { for (rotate = 1; rotate < 16; rotate++) { // rol 2 num = ((num << 2) | (num >> 30)); if (num == (num & 0xff)) { return (num | (rotate << 8)); } } err = 1; return 0; } } static st32 firstsigdigit (ut32 num) { st32 f = -1; st32 b = -1; ut32 forwardmask = 0x80000000; ut32 backwardmask = 0x1; ut32 i; for (i = 0; i < 32; i++ ) { if ( (forwardmask & num) && (f == -1)) { f = i; } if ( (backwardmask & num) && (b == -1)) { b = 32-i; } forwardmask >>= 1; backwardmask <<= 1; } if ((b-f) < 9) { return f; } return -1; } static ut32 getthbimmed(st32 number) { ut32 res = 0; if (number < 0) { res |= 1 << 18; } number >>= 1; res |= (( number & 0xff) << 8); number >>= 8; res |= ( number & 0x07); number >>= 3; res |= (( number & 0xff) << 24); number >>= 8; res |= (( number & 0x3) << 16); number >>= 2; if (number < 0) { res |= (( number & 0x1) << 3); number >>= 1; res |= (( number & 0x1) << 5); } else { res |= ((!( number & 0x1)) << 3); number >>= 1; res |= ((!( number & 0x1)) << 5); } return res; } static ut32 getthzeroimmed12(ut32 number) { ut32 res = 0; res |= (number & 0x800) << 7; res |= (number & 0x700) >> 4; res |= (number & 0x0ff) << 8; return res; } static ut32 getthzeroimmed16(ut32 number) { ut32 res = 0; res |= (number & 0xf000) << 12; res |= (number & 0x0800) << 7; res |= (number & 0x0700) >> 4; res |= (number & 0x00ff) << 8; return res; } static ut32 getthimmed12(const char *str) { ut64 num = getnum (str); if (err) { return 0; } st32 FSD = 0; ut64 result = 0; if (num <= 0xff) { return num << 8; } else if ( ((num & 0xff00ff00) == 0) && ((num & 0x00ff0000) == ((num & 0x000000ff) << 16)) ) { result |= (num & 0x000000ff) << 8; result |= 0x00000010; return result; } else if ( ((num & 0x00ff00ff) == 0) && ((num & 0xff000000) == ((num & 0x0000ff00) << 16)) ) { result |= num & 0x0000ff00; result |= 0x00000020; return result; } else if ( ((num & 0xff000000) == ((num & 0x00ff0000) << 8)) && ((num & 0xff000000) == ((num & 0x0000ff00) << 16)) && ((num &0xff000000) == ((num & 0x000000ff) << 24)) ) { result |= num & 0x0000ff00; result |= 0x00000030; return result; } else { FSD = firstsigdigit(num); if (FSD != -1) { result |= ((num >> (24-FSD)) & 0x0000007f) << 8; result |= ((8+FSD) & 0x1) << 15; result |= ((8+FSD) & 0xe) << 3; result |= ((8+FSD) & 0x10) << 14; return result; } else { err = true; return 0; } } } static char *getrange(char *s) { char *p = NULL; while (s && *s) { if (*s == ',') { p = s+1; *p=0; } if (*s == '[' || *s == ']') { memmove (s, s + 1, strlen (s + 1) + 1); } if (*s == '}') { *s = 0; } s++; } while (p && *p == ' ') { p++; } return p; } //ret register #; -1 if failed static int getreg(const char *str) { int i; char *ep; const char *aliases[] = { "sl", "fp", "ip", "sp", "lr", "pc", NULL }; if (!str || !*str) { return -1; } if (*str == 'r') { int reg = strtol (str + 1, &ep, 10); if ((ep[0] != '\0') || (str[1] == '\0')) { return -1; } if (reg < 16 && reg >= 0) { return reg; } } for (i=0; aliases[i]; i++) { if (!strcmpnull (str, aliases[i])) { return 10 + i; } } return -1; } static st32 getlistmask(char *input) { st32 tempres, res = 0; int i, j, start, end; char *temp = NULL; char *otemp = NULL; char *temp2 = malloc (strlen (input) + 1); if (!temp2) { res = -1; goto end; } temp = (char *)malloc (strlen (input) + 1); if (!temp) { res = -1; goto end; } otemp = temp; while (*input != '\0') { for (; *input == ' '; input++) { ; } for (i = 0; input[i] != ',' && input[i] != '\0'; i++) { ; } strncpy (temp, input, i); temp[i] = 0; input += i; if (*input != '\0') { input++; } for (i = 0; temp[i] != '-' && temp[i] != '\0'; i++) { ; } if (i == strlen (temp)) { tempres = getreg (temp); if (tempres == -1 || tempres > 15) { res = -1; goto end; } res |= 1 << tempres; } else { strncpy (temp2, temp, i); temp2[i] = 0; temp += i + 1; start = getreg (temp2); if (start == -1 || start > 15) { res = -1; goto end; } end = getreg (temp); if (end == -1 || end > 15) { res = -1; goto end; } for (j = start; j <= end; j++ ) { res |= 1 << j; } } } end: free (otemp); free (temp2); return res; } static st32 getregmemstart(const char *input) { if ((strlen (input) < 1) || (!(*input == '['))) { return -1; } input++; return getreg (input); } static st32 getregmemstartend(const char *input) { st32 res; if (!input || (strlen (input) < 2) || (*input != '[') || !r_str_endswith (input, "]")) { return -1; } input++; char *temp = r_str_ndup (input, strlen (input) - 1); if (!temp) { return -1; } res = getreg (temp); free (temp); return res; } static st32 getregmemend(const char *input) { st32 res; if (!input || !*input || !r_str_endswith (input, "]")) { return -1; } char *temp = r_str_ndup (input, strlen (input) - 1); if (!temp) { return -1; } res = getreg (temp); free (temp); return res; } static st32 getreglist(const char *input) { st32 res; if (!input || (strlen (input) < 2) || (*input != '{') || !r_str_endswith (input, "}")) { return -1; } if (*input) { input++; } char *temp = r_str_ndup (input, strlen (input) - 1); if (!temp) { return -1; } res = getlistmask (temp); free (temp); return res; } static st32 getnummemend (const char *input) { st32 res; err = false; if (!input || !*input || !r_str_endswith (input, "]")) { err = true; return -1; } char *temp = r_str_ndup (input, strlen (input) - 1); if (!temp) { err = true; return -1; } res = getnum (temp); free (temp); return res; } static st32 getnummemendbang (const char *input) { st32 res; err = false; if (!input || (strlen (input) < 2) || (input[strlen(input) - 2] != ']' || !r_str_endswith (input, "!"))) { err = true; return 0; } char *temp = r_str_ndup (input, strlen (input) - 2); if (!temp) { err = true; return 0; } res = getnum (temp); free (temp); return res; } static st32 getregmembang(const char *input) { st32 res; if (!input || !*input || !r_str_endswith (input, "!")) { return -1; } char *temp = r_str_ndup (input, strlen (input) - 1); if (!temp) { return -1; } res = getreg (temp); free (temp); return res; } static int getcoproc(const char *str) { char *ep; if (!str || !*str) { return -1; } if (*str == 'p') { int coproc = strtol (str + 1, &ep, 10); if ((ep[0] != '\0') || (str[1] == '\0')) { return -1; } if (coproc < 16 && coproc >= 0) { return coproc; } } return -1; } static int getcoprocreg(const char *str) { char *ep; if (!str || !*str) { return -1; } if (r_str_startswith (str, "c")) { int reg = strtol (str + 1, &ep, 10); if ((ep[0] != '\0') || (str[1] == '\0')) { return -1; } if (reg < 16 && reg >= 0) { return reg; } } return -1; } static ut8 interpret_msrbank (char *str, ut8 *spsr) { const char fields[] = {'c', 'x', 's', 'f', 0}; int res = 0; int i, j; if (r_str_startswith (str, "spsr_")) { *spsr = 1; } else { *spsr = 0; } if (r_str_startswith (str, "apsr_")) { if (!(strcmp (str+5, "g"))) { return 0x4; } if (!(strcmp (str+5, "nzcvq"))) { return 0x8; } if (!(strcmp (str+5, "nzcvqg"))) { return 0xc; } } if (r_str_startswith (str, "cpsr_") || r_str_startswith (str, "spsr_")) { for (i = 0; str[5+i]; i++) { for (j = 0; fields[j]; j++) { if (str[5+i] == fields[j]) { break; } } if (!(fields[j])) { return 0; } res |= 1 << j; } return res; } return 0; } static ut32 thumb_getshift(const char *str) { // only immediate shifts are ever used by thumb-2. Bit positions are different from ARM. const char *shifts[] = { "LSL", "LSR", "ASR", "ROR", 0, "RRX" }; char *type = strdup (str); char *arg; char *space; ut32 res = 0; ut32 shift = false; err = false; ut32 argn; ut32 i; r_str_case (type,true); if (!strcmp (type, shifts[5])) { // handle RRX alias case res |= 3 << 12; free (type); return res; } space = strchr (type, ' '); if (!space) { free (type); err = true; return 0; } *space = 0; arg = strdup (++space); for (i = 0; shifts[i]; i++) { if (!strcmp (type, shifts[i])) { shift = true; break; } } if (!shift) { err = true; free (type); free (arg); return 0; } res |= i << 12; argn = getnum (arg); if (err || argn > 32) { err = true; free (type); free (arg); return 0; } res |= ( (argn & 0x1c) << 2); res |= ( (argn & 0x3) << 14); free (type); free (arg); return res; } static st32 getshiftmemend(const char *input) { st32 res; if (!input || !*input || !r_str_endswith (input, "]")) { return -1; } char *temp = r_str_ndup (input, strlen (input) - 1); if (!temp) { return -1; } res = thumb_getshift (temp); free (temp); return res; } void collect_list(char *input[]) { if (input[0] == NULL) { return; } char *temp = malloc (500); if (!temp) { return; } temp[0] = 0; int i; int conc = 0; int start, end = 0; int arrsz; for (arrsz = 1; input[arrsz] != NULL; arrsz++) { ; } for (i = 0; input[i]; i++) { if (conc) { strcat (temp, ", "); strcat (temp, input[i]); } if (input[i][0] == '{') { conc = 1; strcat (temp, input[i]); start = i; } if ((conc) & (input[i][strlen (input[i]) - 1] == '}')) { conc = 0; end = i; } } if (end == 0) { free (temp); return; } input[start] = temp; for (i = start + 1; i < arrsz; i++) { input[i] = input[(end-start) + i]; } input[i] = NULL; } static ut64 thumb_selector(char *args[]) { collect_list(args); ut64 res = 0; ut8 i; for (i = 0; i < 15; i++) { if (args[i] == NULL) { break; } if (getreg (args[i]) != -1) { res |= 1 << (i*4); continue; } err = false; getnum (args[i]); if (!err) { res |= 2 << (i*4); continue; } err = false; thumb_getshift (args[i]); if (!err) { res |= 3 << (i*4); continue; } if (getcoproc (args[i]) != -1) { res |= 4 << (i*4); continue; } if (getcoprocreg (args[i]) != -1) { res |= 5 << (i*4); continue; } if (getregmemstart (args[i]) != -1) { res |= 6 << (i*4); continue; } if (getregmemstartend (args[i]) != -1) { res |= 7 << (i*4); continue; } err = false; getnummemend(args[i]); if (!err) { res |= 8 << (i*4); continue; } err = false; getnummemendbang(args[i]); if (!err) { res |= 9 << (i*4); continue; } if (getregmembang (args[i]) != -1) { res |= 0xa << (i*4); continue; } if (getreglist (args[i]) != -1) { res |= 0xb << (i*4); continue; } if (getregmemend (args[i]) != -1) { res |= 0xc << (i*4); continue; } if (getshiftmemend (args[i]) != -1) { res |= 0xd << (i*4); continue; } err = false; getnumbang(args[i]); if (!err) { res |= 0xe << (i*4); continue; } res |= 0xf << (i*4); } err = false; return res; } static ut32 getshift(const char *str) { char type[128]; char arg[128]; char *space; ut32 i=0, shift=0; const char *shifts[] = { "LSL", "LSR", "ASR", "ROR", 0, "RRX" // alias for ROR #0 }; strncpy (type, str, sizeof (type) - 1); // XXX strcaecmp is probably unportable if (!r_str_casecmp (type, shifts[5])) { // handle RRX alias case shift = 6; } else { // all other shift types space = strchr (type, ' '); if (!space) { return 0; } *space = 0; strncpy (arg, ++space, sizeof(arg) - 1); for (i = 0; shifts[i]; i++) { if (!r_str_casecmp (type, shifts[i])) { shift = 1; break; } } if (!shift) { return 0; } shift = i * 2; if ((i = getreg (arg)) != -1) { i <<= 8; // set reg // i|=1; // use reg i |= (1 << 4); // bitshift i |= shift << 4; // set shift mode if (shift == 6) { i |= (1 << 20); } } else { char *bracket = strchr (arg, ']'); if (bracket) { *bracket = '\0'; } // ensure only the bottom 5 bits are used i &= 0x1f; if (!i) { i = 32; } i = (i * 8); i |= shift; // lsl, ror, ... i = i << 4; } } return i; } static void arm_opcode_parse(ArmOpcode *ao, const char *str) { int i; memset (ao, 0, sizeof (ArmOpcode)); if (strlen (str) + 1 >= sizeof (ao->op)) { return; } strncpy (ao->op, str, sizeof (ao->op)-1); strcpy (ao->opstr, ao->op); ao->a[0] = strchr (ao->op, ' '); for (i=0; i<15; i++) { if (ao->a[i]) { *ao->a[i] = 0; ao->a[i+1] = strchr (++ao->a[i], ','); } else { break; } } if (ao->a[i]) { *ao->a[i] = 0; ao->a[i]++; } for (i=0; i<16; i++) { while (ao->a[i] && *ao->a[i] == ' ') { ao->a[i]++; } } } static inline int arm_opcode_cond(ArmOpcode *ao, int delta) { const char *conds[] = { "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", "nv", 0 }; int i, cond = 14; // 'always' is default char *c = ao->op+delta; for (i=0; conds[i]; i++) { if (!strcmpnull (c, conds[i])) { cond = i; break; } } ao->o |= cond << 4; return cond; } static st32 thumb_getoffset(char *label, ut64 cur) { st32 res = r_num_math (NULL, label); res -= 4; res -= cur; // possible integer underflow //printf("thumb_getoffset: %s, %lld, %lld\n", label, res, cur); return res; } static st8 std_16bit_2reg(ArmOpcode *ao, ut64 m) { ut8 rd = getreg (ao->a[0]); ut8 rn = getreg (ao->a[1]); if ( (rd < 8) && (rn < 8) && !(m & DOTW_BIT)) { ao->o |= rd << 8; ao->o |= rn << 11; return 2; } return 0; } static st8 mem_16bit_2reg(ArmOpcode *ao, ut64 m) { ut8 rd = getreg (ao->a[0]); ut8 rn = getregmemstart (ao->a[1]); if ( (rd < 8) && (rn < 8) && !(m & DOTW_BIT)) { ao->o |= rd << 8; ao->o |= rn << 11; return 2; } return 0; } static st8 std_32bit_2reg(ArmOpcode *ao, ut64 m, bool shift) { ut8 rd = getreg (ao->a[0]); ut8 rn = getreg (ao->a[1]); if ((rd > 15) || (rn > 15) || (m & DOTN_BIT)) { return -1; } if (m & S_BIT) { ao->o |= 1 << 28; } if (shift) { err = false; ut32 shiftnum = thumb_getshift (ao->a[2]); if (err) { return -1; } ao->o |= shiftnum; ao->o |= rd << 24; ao->o |= rn << 8; } else { ao->o |= rd; ao->o |= rn << 24; } return 4; } static st8 mem_32bit_2reg(ArmOpcode *ao, ut64 m) { ut8 rd = getreg (ao->a[0]); ut8 rn = getregmemstart (ao->a[1]); if ((rd > 15) || (rn > 15) || (m & DOTN_BIT)) { return -1; } ao->o |= rd << 4; ao->o |= rn << 24; return 4; } static st8 std_32bit_3reg(ArmOpcode *ao, ut64 m, bool shift) { ut8 rd = getreg (ao->a[0]); ut8 rn = getreg (ao->a[1]); ut8 rm = getreg (ao->a[2]); if ((rd > 15) || (rn > 15) || (rm > 15) || (m & DOTN_BIT)) { return -1; } ao->o |= rd; ao->o |= rn << 24; ao->o |= rm << 8; if (shift) { err = false; ut32 shiftnum = thumb_getshift (ao->a[3]); if (err) { return -1; } ao->o |= shiftnum; } if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } static void std_opt_2(ArmOpcode *ao) { ao->a[2] = ao->a[1]; ao->a[1] = ao->a[0]; } static void std_opt_3(ArmOpcode *ao) { ao->a[3] = ao->a[2]; ao->a[2] = ao->a[1]; ao->a[1] = ao->a[0]; } // TODO: group similar instructions like for non-thumb static int thumb_assemble(ArmOpcode *ao, ut64 off, const char *str) { ut64 m; ao->o = UT32_MAX; if (!strcmpnull (ao->op, "udf")) { ao->o = 0xde; ao->o |= getnum (ao->a[0]) << 8; return 2; } else if ((m = opmask (ao->op, "add", S_BIT | W_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 num = getnum (ao->a[2]); if ((reg1 > 15) || (reg2 > 15)) { return -1; } if (reg2 == 13) { if ((reg1 < 8) && (num < 1024) && (num % 4 == 0) && (!(m & DOTW_BIT)) && (!(m & W_BIT))) { ao->o = 0x00a8; ao->o |= reg1; ao->o |= (num >> 2) << 8; return 2; } if ((reg1 == 13) && (num < 512) && (num % 4 == 0) && (!(m & DOTW_BIT)) && (!(m & W_BIT))) { ao->o = 0x00b0; ao->o |= (num >> 2) << 8; return 2; } err = false; ut32 thnum = getthimmed12 (ao->a[2]); if (!err && (!(m & W_BIT))) { ao->o = 0x0df10000; ao->o |= reg1; ao->o |= thnum; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } if (num > 4095) { return -1; } ao->o = 0x0df20000; ao->o |= reg1; ao->o |= getthzeroimmed12 (num); return 4; } if (num < 8) { ao->o = 0x001c; ao->o |= (num & 0x3) << 14; ao->o |= (num >> 2); if (std_16bit_2reg (ao, m)) { return 2; } } if ((reg1 < 8) && (reg1 == reg2) && (num < 256)) { ao->o = 0x0030; ao->o |= reg1; ao->o |= num << 8; return 2; } err = false; ut32 thnum = getthimmed12 (ao->a[2]); if (!err && (!(m & W_BIT))) { ao->o = 0x00f10000; ao->o |= thnum; return std_32bit_2reg (ao, m, false); } if (num > 4095) { return -1; } ao->o = 0x00f20000; ao->o |= getthzeroimmed12 (num); return std_32bit_2reg (ao, m, false); } break; case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut32 shift = thumb_getshift (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15)) { return -1; } if (reg2 == 13) { if ((reg1 == reg3) && (!(m & DOTW_BIT)) && (shift == 0)) { ao->o = 0x6844; ao->o |= (reg1 & 0x7) << 8; ao->o |= (reg1 >> 3) << 15; return 2; } if ((reg1 == 13) && (!(m & DOTW_BIT)) && (shift == 0)) { ao->o = 0x8544; ao->o |= reg3 << 11; return 2; } ao->o = 0x0deb0000; ao->o |= reg1; ao->o |= reg3 << 8; ao->o |= shift; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } if ((reg3 < 8) && (!(m & DOTW_BIT)) && (shift == 0)) { ao->o = 0x0018; ao->o |= (reg3 >> 2); ao->o |= (reg3 & 0x3) << 14; if (std_16bit_2reg (ao, m)) { return 2; } } if ((reg1 == reg2) && (!(m & DOTW_BIT)) && (shift == 0)) { ao->o = 0x0044; ao->o |= (reg1 & 0x7) << 8; ao->o |= (reg1 >> 3) << 15; ao->o |= reg3 << 11; return 2; } ao->o = 0x00eb0000; return std_32bit_3reg (ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "adc", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { ao->o = 0x40f10000; ao->o |= getthimmed12 (ao->a[2]); return std_32bit_2reg (ao, m, false); } break; case THUMB_REG_REG: { ao->o = 0x4041; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x40eb0000; return std_32bit_3reg (ao, m, false); } break; case THUMB_REG_REG_SHIFT: { std_opt_3 (ao); } // intentional fallthrough // a bit naughty, perhaps? case THUMB_REG_REG_REG_SHIFT: { ao->o = 0x40eb0000; return std_32bit_3reg(ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "adr", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg = getreg (ao->a[0]); st32 label = getnum (ao->a[1]); if ( !(m & DOTW_BIT) && (reg < 8) && (label < 1024) && (label >= 0) && (label % 4 == 0)) { ao->o = 0x00a0; ao->o |= reg; ao->o |= (label / 4) << 8; return 2; } else if ((label < 0) && (label > -4096)) { if (m & DOTN_BIT) { // this is explicitly an error return -1; } ao->o = 0xaff20000; ao->o |= reg; ao->o |= getthzeroimmed12 (-label); return 4; } else if ((label > 0) && (label < 4096)) { if (m & DOTN_BIT) { // this is explicitly an error return -1; } ao->o = 0x0ff20000; ao->o |= reg; ao->o |= getthzeroimmed12 (label); return 4; } return -1; } break; default: return -1; } } else if ((m = opmask (ao->op, "and", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { ao->o = 0x0040; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x00ea0000; return std_32bit_3reg (ao, m, false); } break; case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { ut32 imm = getthimmed12 (ao->a[2]); ao->o = 0x00f00000; ao->o |= imm; return std_32bit_2reg (ao, m, false); } break; case THUMB_REG_REG_SHIFT: { std_opt_3 (ao); } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ao->o = 0x00ea0000; return std_32bit_3reg (ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "asr", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 imm = getnum (ao->a[2]); if (((int)imm < 1) && ((int)imm > 32)) { return -1; } ao->o = 0x0010; ao->o |= (imm & 0x3) << 14; ao->o |= (imm & 0x1c) >> 2; if (std_16bit_2reg (ao, m)) { return 2; } ao->o = 0x4fea2000; ao->o |= reg1; ao->o |= reg2 << 8; ao->o |= (imm & 0x3) << 14; ao->o |= (imm & 0x1c) << 2; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; case THUMB_REG_REG: { ao->o = 0x0041; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x40fa00f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if (( m = opmask (ao->op, "b", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_CONST: { st32 offset = thumb_getoffset (ao->a[0], off); if (offset % 2 != 0) { return -1; } if ((m & C_BITS) == C_BITS) { if ((offset >= -2048) && (offset <= 2046) && (!(m & DOTW_BIT))) { ao->o = 0x00e0; ao->o |= ((offset/2 & 0xff) << 8); ao->o |= ((offset/2 & 0x700) >> 8); return 2; } if ((offset < -16777216) || (offset > 16777214) || (offset % 2 != 0)) { return -1; } ao->o = 0x00f00090; ao->o |= getthbimmed(offset); return 4; } else { if ((offset >= -256) && (offset <= 254) && (!(m & DOTW_BIT))) { ao->o = 0x00d0; ao->o |= (ut16) ((offset/2) << 8); ao->o |= ((m & C_BITS) >> 2); return 2; } if ((offset < -1048576) || (offset > 1048574) || (offset % 2 != 0)) { return -1; } ao->o = 0x00f00080; ao->o |= (ut32)(offset & 0x80000) >> 16; ao->o |= (ut32)(offset & 0x40000) >> 13; ao->o |= (ut32)(offset & 0x3f000) << 12; ao->o |= (ut32)(offset & 0xe00) >> 9; ao->o |= (ut32)(offset & 0x1fe) << 7; if (offset < 0) { ao->o |= 1 << 18; } ao->o |= (((m & C_BITS) & 0xc) << 28); ao->o |= (((m & C_BITS) & 0x30) << 12); return 4; } } break; default: return -1; } } else if (( m = opmask (ao->op, "bl", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_CONST: { st32 offset = thumb_getoffset (ao->a[0], off); ao->o = 0x00f000d0; if ((offset > 16777214) || (offset < -16777216) || (offset % 2 != 0)) { return -1; } ao->o |= getthbimmed(offset); return 4; } break; default: return -1; } } else if (( m = opmask (ao->op, "bx", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG: { ut32 reg1 = getreg (ao->a[0]); ao->o = 0x0047; ao->o |= reg1 << 11; return 2; } break; default: return -1; } } else if (( m = opmask (ao->op, "blx", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG: { ut32 reg1 = getreg (ao->a[0]); ao->o = 0x8047; ao->o |= reg1 << 11; return 2; } break; case THUMB_CONST: { st32 offset = thumb_getoffset (ao->a[0], off); ao->o = 0x00f000c0; if ((offset > 16777214) || (offset < -16777216) || (offset % 2 != 0)) { return -1; } offset += off & 0x2; // (Align(PC,4) ao->o |= getthbimmed (offset); return 4; } break; default: return -1; } } else if (( m = opmask (ao->op, "bfc", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST_CONST: { if (m & DOTN_BIT) { // this is explicitly an error return -1; } ut8 reg1 = getreg (ao->a[0]); ut32 lsb = getnum (ao->a[1]); ut32 width = getnum (ao->a[2]); ut32 msb = lsb + width - 1; if ((lsb > 31) || (msb > 31)) { return -1; } ao->o = 0x6ff30000; ao->o |= reg1; ao->o |= ((lsb & 0x1c) << 2); ao->o |= ((lsb & 0x3) << 14); ao->o |= (msb << 8); return 4; } break; default: return -1; } } else if (( m = opmask (ao->op, "bfi", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_CONST_CONST: { ut32 lsb = getnum (ao->a[2]); ut32 width = getnum (ao->a[3]); ut32 msb = lsb + width - 1; if ((lsb > 31) || (msb > 31)) { return -1; } ao->o = 0x60f30000; ao->o |= ((lsb & 0x1c) << 2); ao->o |= ((lsb & 0x3) << 14); ao->o |= (msb << 8); return std_32bit_2reg (ao, m, false); } break; default: return -1; } } else if (( m = opmask (ao->op, "bic", S_BIT) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { ao->o = 0x8043; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x20ea0000; return std_32bit_3reg (ao, m, false); } break; case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { ao->o = 0x20f00000; ao->o |= getthimmed12 (ao->a[2]); return std_32bit_2reg (ao, m, false); } break; case THUMB_REG_REG_SHIFT: { std_opt_3 (ao); } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ao->o = 0x20ea0000; return std_32bit_3reg (ao, m, true); } break; default: return -1; } } else if (( m = opmask (ao->op, "bkpt", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_CONST: { ut32 num = getnum (ao->a[0]); if (num > 255) { return -1; } ao->o = 0x00be; ao->o |= num << 8; return 2; } break; default: return -1; } } else if (( m = opmask (ao->op, "cbnz", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); st32 offset = thumb_getoffset (ao->a[1], off); if ((reg1 > 7) || (offset > 127) || (offset % 2 != 0)) { return -1; } ao->o = 0x00b9; ao->o |= reg1 << 8; ao->o |= (offset & 0x3e) << 10; ao->o |= (offset & 0x40) >> 5; return 2; } break; default: return -1; } } else if (( m = opmask (ao->op, "cbz", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); st32 offset = thumb_getoffset (ao->a[1], off); if ((reg1 > 7) || (offset > 127) || (offset % 2 != 0)) { return -1; } ao->o = 0x00b1; ao->o |= reg1 << 8; ao->o |= (offset & 0x3e) << 10; ao->o |= (offset & 0x40) >> 5; return 2; } break; default: return -1; } } else if (( m = opmask (ao->op, "cdp", TWO_BIT) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_COPROC_CONST_COREG_COREG_COREG: { ao->a[5] = "0"; } //intentional fallthrough case THUMB_COPROC_CONST_COREG_COREG_COREG_CONST: { ut32 coproc = getcoproc (ao->a[0]); ut32 opc1 = getnum (ao->a[1]); ut8 reg1 = getcoprocreg (ao->a[2]); ut8 reg2 = getcoprocreg (ao->a[3]); ut8 reg3 = getcoprocreg (ao->a[4]); ut32 opc2 = getnum (ao->a[5]); if ((coproc > 15) || (opc1 > 15) || (opc2 > 7)) { return -1; } ao->o = 0x00ee0000; if (m & TWO_BIT) { ao->o |= 1 << 20; } ao->o |= coproc; ao->o |= opc1 << 28; ao->o |= reg1 << 4; ao->o |= reg2 << 24; ao->o |= reg3 << 8; ao->o |= opc2 << 13; return 4; } break; default: return -1; } } else if (( m = opmask (ao->op, "clrex", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { ao->o = 0xbff32f8f; return 4; } break; default: return -1; } } else if (( m = opmask (ao->op, "clz", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { ao->o = 0xb0fa80f0; ao->a[2] = ao->a[1]; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if (( m = opmask (ao->op, "cmn", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut32 num = getthimmed12 (ao->a[1]); ao->o = 0x10f1000f; ao->o |= reg1 << 24; ao->o |= num; return 4; } break; case THUMB_REG_REG: { ao->o = 0xc042; if (std_16bit_2reg (ao, m)) { return 2; } ao->a[2] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { ao->o = 0x10eb000f; return std_32bit_2reg (ao, m, true); } break; default: return -1; } } else if (( m = opmask (ao->op, "cmp", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut32 num = getnum (ao->a[1]); if ((num < 256) && (!(m & DOTW_BIT))) { ao->o = 0x0028; ao->o |= reg1; ao->o |= num << 8; return 2; } num = getthimmed12 (ao->a[1]); ao->o = 0xb0f1000f; ao->o |= reg1 << 24; ao->o |= num; return 4; } break; case THUMB_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ao->o = 0x8042; if (std_16bit_2reg (ao, m)) { return 2; } if (!(m & DOTW_BIT)) { ao->o = 0x0045; ao->o |= ((reg1 & 0x7) << 8); ao->o |= ((reg1 & 0x8) << 12); ao->o |= reg2 << 11; return 2; } ao->a[2] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 shift = thumb_getshift (ao->a[2]); ao->o = 0xb0eb000f; ao->o |= reg1 << 24; ao->o |= reg2 << 8; ao->o |= shift; return 4; } break; default: return -1; } } else if (( m = opmask (ao->op, "cps", ID_BIT | IE_BIT) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_OTHER: { st8 aif = iflag(ao->a[0]); if (aif == -1) { return -1; } if (!(m & DOTW_BIT)) { ao->o = 0x60b6; ao->o |= aif << 8; if (m & ID_BIT) { ao->o |= 1 << 12; } return 2; } ao->a[1] = "0"; } // intentional fallthrough case THUMB_OTHER_CONST: { st8 aif = iflag(ao->a[0]); ut8 mode = getnum (ao->a[1]); if ((mode > 31) || (aif == -1)) { return -1; } ao->o = 0xaff30085; ao->o |= mode << 8; ao->o |= aif << 13; if (m & ID_BIT) { ao->o |= 1 << 1; } return 4; } break; case THUMB_CONST: { ut8 mode = getnum (ao->a[0]); if ((m & ID_BIT) || (m & IE_BIT) || (mode > 31)) { return -1; } ao->o = 0xaff30081; ao->o |= mode << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "dbg", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_CONST: { ut32 option = getnum (ao->a[0]); if (option > 15) { return -1; } ao->o = 0xaff3f080; ao->o |= option << 8; return 4; } default: return -1; } } else if ((m = opmask (ao->op, "dmb", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { ao->o = 0xbff35f8f; return 4; } break; case THUMB_OTHER: { r_str_case (ao->a[0], false); if (strcmpnull (ao->a[0], "sy")) { return -1; } ao->a[0] = "15"; } // intentional fallthrough case THUMB_CONST: { ut32 option = getnum (ao->a[0]); if (option != 15) { return -1; } ao->o = 0xbff3508f; ao->o |= option << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "dsb", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { ao->o = 0xbff34f8f; return 4; } // intentional fallthrough case THUMB_OTHER: { r_str_case (ao->a[0], false); if (!strcmpnull ((ao->a[0] = parse_hints(ao->a[0])), "-1")) { return -1; } } // intentional fallthrough case THUMB_CONST: { ut32 option = getnum (ao->a[0]); if ((option != 6) && (option != 7) && (option != 14) && (option != 15)) { return -1; } ao->o = 0xbff3408f; ao->o |= option << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "eor", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: std_opt_2 (ao); // intentional fallthrough case THUMB_REG_REG_CONST: { err = false; ut32 imm = getthimmed12 (ao->a[2]); if (err) { return -1; } ao->o = 0x80f00000; ao->o |= imm; return std_32bit_2reg (ao, m, false); } break; case THUMB_REG_REG: { ao->o = 0x4040; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: ao->a[3] = "lsl 0"; // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ao->o = 0x80ea0000; return std_32bit_3reg (ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "isb", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { ao->o = 0xbff36f8f; return 4; } // intentional fallthrough case THUMB_OTHER: { r_str_case (ao->a[0], false); if (strcmpnull (ao->a[0], "sy")) { return -1; } ao->a[0] = "15"; } // intentional fallthrough case THUMB_CONST: { ut32 option = getnum (ao->a[0]); if (option != 15) { return -1; } ao->o = 0xbff3608f; ao->o |= option << 8; return 4; } break; default: return -1; } } else if ((m = itmask (ao->op))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_OTHER: { ut16 cond = 0; ut16 i; const char *conds[] = { "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", "nv", 0 }; r_str_case (ao->a[0], false); for (i = 0; conds[i]; i++) { if (!(strcmpnull(ao->a[0], conds[i]))) { cond = i; break; } } if (i == 16) { return -1; } ao->o = 0x00bf; ao->o |= cond << 12; ut8 nrcs = (m & 0x30) >> 4; ut8 thiset = 0; for (i = 0; i < nrcs; i++) { thiset = ((m & (1 << (3 - i))) >> (3 - i)); ao->o |= ((cond & 0x1) ^ thiset) << (11 - i); } ao->o |= 1 << (11 - i); return 2; } break; default: return -1; } } else if ((m = opmask (ao->op, "ldc", TWO_BIT | L_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_COPROC_COREG_BRACKREG_CONSTBRACK: { ut8 proc = getcoproc (ao->a[0]); ut8 reg1 = getcoprocreg (ao->a[1]); ut8 reg2 = getregmemstart (ao->a[2]); st32 imm = getnummemend (ao->a[3]); ao->o = 0x10ed0000; if (m & L_BIT) { ao->o |= 1 << 30; } if (m & TWO_BIT) { ao->o |= 1 << 20; } if (imm < 0) { imm = -imm; } else { ao->o |= 1 << 31; } if ((proc > 15) || (reg1 > 15) || (reg2 > 15) || (imm > 1024) || (imm % 4 != 0)) { return -1; } ao->o |= proc; ao->o |= reg1 << 4; ao->o |= (imm >> 2) << 8; ao->o |= reg2 << 24; return 4; } break; case THUMB_COPROC_COREG_BRACKREGBRACK: ao->a[3] = "0"; // intentional fallthrough case THUMB_COPROC_COREG_BRACKREGBRACK_CONST: { ut8 proc = getcoproc (ao->a[0]); ut8 reg1 = getcoprocreg (ao->a[1]); ut8 reg2 = getregmemstartend (ao->a[2]); st32 imm = getnum (ao->a[3]); ao->o = 0x30ec0000; if (m & L_BIT) { ao->o |= 1 << 30; } if (m & TWO_BIT) { ao->o |= 1 << 20; } if (imm < 0) { imm = -imm; } else { ao->o |= 1 << 31; } if ((proc > 15) || (reg1 > 15) || (reg2 > 15) || (imm > 1024) || (imm % 4 != 0)) { return -1; } ao->o |= proc; ao->o |= reg1 << 4; ao->o |= (imm >> 2) << 8; ao->o |= reg2 << 24; return 4; } break; case THUMB_COPROC_COREG_BRACKREG_CONSTBRACKBANG: { ut8 proc = getcoproc (ao->a[0]); ut8 reg1 = getcoprocreg (ao->a[1]); ut8 reg2 = getregmemstart (ao->a[2]); st32 imm = getnummemendbang (ao->a[3]); ao->o = 0x30ed0000; if (m & L_BIT) { ao->o |= 1 << 30; } if (m & TWO_BIT) { ao->o |= 1 << 20; } if (imm < 0) { imm = -imm; } else { ao->o |= 1 << 31; } if ((proc > 15) || (reg1 > 15) || (reg2 > 15) || (imm > 1024) || (imm % 4 != 0)) { return -1; } ao->o |= proc; ao->o |= reg1 << 4; ao->o |= (imm >> 2) << 8; ao->o |= reg2 << 24; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "ldm", DB_BIT | EA_BIT | IA_BIT | FD_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REGBANG_LIST: { ut8 reg1 = getregmembang (ao->a[0]); ut32 list = getreglist (ao->a[1]); if (!((m & DB_BIT) || (m & EA_BIT)) && !(list & 0xff00) && (reg1 < 8) && !(m & DOTW_BIT)) { ao->o = 0x00c8; ao->o |= reg1; if (list & (1 << reg1)) { list ^= 1 << (reg1); } ao->o |= (list & 0xff) << 8; return 2; } if (list & 0x2000) { return -1; } if ((m & DB_BIT) || (m & EA_BIT)) { ao->o = 0x30e90000; } else { // ldmia is the default! ao->o = 0xb0e80000; } ao->o |= reg1 << 24; ao->o |= (list & 0xff) << 8; ao->o |= (list & 0xff00) >> 8; return 4; } break; case THUMB_REG_LIST: { ut8 reg1 = getreg (ao->a[0]); ut32 list = getreglist (ao->a[1]); if (!((m & DB_BIT) || (m & EA_BIT)) && !(list & 0xff00) && (reg1 < 8) && !(m & DOTW_BIT)) { ao->o = 0x00c8; ao->o |= reg1; ao->o |= 1 << (reg1 + 8); ao->o |= (list & 0xff) << 8; return 2; } if (list & 0x2000) { return -1; } if ((m & DB_BIT) || (m & EA_BIT)) { ao->o = 0x10e90000; } else { ao->o = 0x90e80000; } ao->o |= reg1 << 24; ao->o |= (list & 0xff) << 8; ao->o |= (list & 0xff00) >> 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "ldr", B_BIT | H_BIT | D_BIT | T_BIT | S_BIT))) { ut64 argt = thumb_selector (ao->a); ut32 ldrsel = m & (B_BIT | H_BIT | D_BIT); if ((m & S_BIT) && !(m & (B_BIT | H_BIT))) { return -1; } switch (argt) { case THUMB_REG_CONST: ao->a[2] = ao->a[1]; strcat (ao->a[2],"]"); ao->a[1] = "[r15"; // intentional fallthrough case THUMB_REG_BRACKREGBRACK: if (ao->a[2] == NULL) { // double fallthrough ao->a[1][strlen (ao->a[1]) -1] = '\0'; ao->a[2] = "0]"; } // intentional fallthrough case THUMB_REG_BRACKREG_CONSTBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getregmemstart (ao->a[1]); st32 num = getnummemend (ao->a[2]); if (ldrsel == 0) { if (m & T_BIT) { if ((num < 0) || (num > 255)) { return -1; } ao->o = 0x50f8000e; ao->o |= num << 8; return mem_32bit_2reg (ao, m); } if (reg2 == 15) { if ((num > 4095) || (num < -4095)) { return -1; } if ((reg1 < 8) && (num < 1024) && (num % 4 == 0)) { ao->o = 0x0048; ao->o |= reg1; ao->o |= (num >> 2) << 8; return 2; } ao->o = 0x5ff80000; if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= (num & 0xff) << 8; ao->o |= (num & 0x0f00) >> 8; return 4; } if ((reg2 == 13) && (reg1 < 8) && (num >= 0) && (num < 1024) && (num % 4 == 0) && (!(m & DOTW_BIT))) { ao->o = 0x0098; ao->o |= reg1; ao->o |= (num >> 2) << 8; return 2; } if ((num >= 0) && (num < 128) && (num % 4 == 0)) { ao->o = 0x0068; ao->o |= (num >> 4); ao->o |= ((num >> 2) & 0x3) << 14; if (mem_16bit_2reg (ao, m)) { return 2; } } if ((num > 4095) || (num < -1023)) { return -1; } if (num >= 0) { ao->o = 0xd0f80000; ao->o |= (num & 0xff) << 8; ao->o |= (num & 0xf00) >> 8; return mem_32bit_2reg (ao, m); } ao->o = 0x50f8000c; ao->o |= (-num & 0xff) << 8; return mem_32bit_2reg (ao, m); } else if (ldrsel == B_BIT) { if (m & T_BIT) { if ((num < 0) || (num > 255)) { return -1; } ao->o = 0x10f8000e; if (m & S_BIT) { ao->o |= 1 << 16; } ao->o |= num << 8; return mem_32bit_2reg (ao, m); } if (reg2 == 15) { if ((num > 4095) || (num < -4095)) { return -1; } ao->o = 0x1ff80000; if (m & S_BIT) { ao->o |= 1 << 16; } if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= (num & 0xff) << 8; ao->o |= (num & 0x0f00) >> 8; return 4; } if ((num >= 0) && (num < 32) && (!(m & S_BIT))) { ao->o = 0x0078; ao->o |= (num >> 2); ao->o |= (num & 0x3) << 14; if (mem_16bit_2reg (ao, m)) { return 2; } } if ((num > 4095) || (num < -255)) { return -1; } if (num >= 0) { ao->o = 0x90f80000; if (m & S_BIT) { ao->o |= 1 << 16; } ao->o |= (num & 0xff) << 8; ao->o |= (num & 0xf00) >> 8; return mem_32bit_2reg (ao, m); } ao->o = 0x10f8000c; if (m & S_BIT) { ao->o |= 1 << 16; } ao->o |= -num << 8; return mem_32bit_2reg (ao, m); } else if (ldrsel == H_BIT) { if (m & T_BIT) { if ((num < 0) || (num > 255)) { return -1; } ao->o = 0x30f8000e; if (m & S_BIT) { ao->o |= 1 << 16; } ao->o |= num << 8; return mem_32bit_2reg (ao, m); } if (reg2 == 15) { if ((num > 4095) || (num < -4095)) { return -1; } ao->o = 0x3ff80000; if (m & S_BIT) { ao->o |= 1 << 16; } if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= (num & 0xff) << 8; ao->o |= (num & 0x0f00) >> 8; return 4; } if ((num >= 0) && (num < 64) && (num % 2 == 0) && (!(m & S_BIT))) { ao->o = 0x0088; ao->o |= (num >> 3); ao->o |= ((num >> 1) & 0x3) << 14; if (mem_16bit_2reg (ao, m)) { return 2; } } if ((num > 4095) || (num < -255)) { return -1; } if (num >= 0) { ao->o = 0xb0f80000; if (m & S_BIT) { ao->o |= 1 << 16; } ao->o |= (num & 0xff) << 8; ao->o |= (num & 0xf00) >> 8; return mem_32bit_2reg (ao, m); } ao->o = 0x30f8000c; if (m & S_BIT) { ao->o |= 1 << 16; } ao->o |= -num << 8; return mem_32bit_2reg (ao, m); } else { return -1; } } break; case THUMB_REG_BRACKREGBRACK_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getregmemstartend (ao->a[1]); st32 num = getnum (ao->a[2]); if ((num < -255) || (num > 255)) { return -1; } if (ldrsel == 0) { ao->o = 0x50f80009; } else if (ldrsel == B_BIT) { ao->o = 0x10f80009; } else if (ldrsel == H_BIT) { ao->o = 0x30f80009; } else { return -1; } if (m & S_BIT) { ao->o |= 1 << 16; } if (num < 0) { num = -num; } else { ao->o |= 1 << 1; } ao->o |= num << 8; ao->o |= reg1 << 4; ao->o |= reg2 << 24; return 4; } break; case THUMB_REG_BRACKREG_CONSTBRACKBANG: { st32 num = getnummemendbang (ao->a[2]); if ((num < -255) || (num > 255)) { return -1; } if (ldrsel == 0) { ao->o = 0x50f8000d; } else if (ldrsel == B_BIT) { ao->o = 0x10f8000d; } else if (ldrsel == H_BIT) { ao->o = 0x30f8000d; } else { return -1; } if (m & S_BIT) { ao->o |= 1 << 16; } if (num < 0) { num = -num; } else { ao->o |= 1 << 1; } ao->o |= num << 8; return mem_32bit_2reg (ao, m); } break; case THUMB_REG_BRACKREG_REGBRACK: { ut8 reg3 = getregmemend (ao->a[2]); if (reg3 < 8) { if (ldrsel == 0) { ao->o = 0x0058; } else if (ldrsel == B_BIT) { if (m & S_BIT) { ao->o = 0x0056; } else { ao->o = 0x005c; } } else if (ldrsel == H_BIT) { if (m & S_BIT) { ao->o = 0x005e; } else { ao->o = 0x005a; } } else { return -1; } ao->o |= (reg3 & 0x3) << 14; ao->o |= (reg3 & 0x4) >> 2; if (mem_16bit_2reg (ao, m)) { return 2; } } ao->a[2][strlen (ao->a[2]) -1] = '\0'; ao->a[3] = "lsl 0]"; } // intentional fallthrough case THUMB_REG_BRACKREG_REG_SHIFTBRACK: { ut8 reg3 = getreg (ao->a[2]); ut32 shift = getshiftmemend (ao->a[3]); shift >>= 2; if (shift & 0xffffcfff) { return -1; } if (ldrsel == 0) { ao->o = 0x50f80000; } else if (ldrsel == B_BIT) { ao->o = 0x10f80000; } else if (ldrsel == H_BIT) { ao->o = 0x30f80000; } else { return -1; } if (m & S_BIT) { ao->o |= 1 << 16; } ao->o |= reg3 << 8; ao->o |= shift; return mem_32bit_2reg (ao, m); } break; case THUMB_REG_REG_BRACKREGBRACK: { ao->a[2][strlen (ao->a[2]) -1] = '\0'; ao->a[3] = "0]"; } // intentional fallthrough case THUMB_REG_REG_BRACKREG_CONSTBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstart (ao->a[2]); st32 num = getnummemend (ao->a[3]); if ((num > 1020) || (num < -1020) || (num % 4 != 0) || (ldrsel != D_BIT)) { return -1; } ao->o = 0x50e90000; if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= (num >> 2) << 8; return 4; } break; case THUMB_REG_REG_BRACKREGBRACK_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstartend (ao->a[2]); st32 num = getnum (ao->a[3]); if ((num > 1020) || (num < -1020) || (num % 4 != 0) || (ldrsel != D_BIT)) { return -1; } ao->o = 0x70e80000; if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= (num >> 2) << 8; return 4; } break; case THUMB_REG_REG_BRACKREG_CONSTBRACKBANG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstart (ao->a[2]); st32 num = getnummemendbang (ao->a[3]); if ((num > 1020) || (num < -1020) || (num % 4 != 0) || (ldrsel != D_BIT)) { return -1; } ao->o = 0x70e90000; if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= (num >> 2) << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "ldrex", B_BIT | H_BIT | D_BIT))) { ut64 argt = thumb_selector (ao->a); ut32 ldrsel = m & (B_BIT | H_BIT | D_BIT); switch (argt) { case THUMB_REG_BRACKREGBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getregmemstartend (ao->a[1]); if (ldrsel == B_BIT) { ao->o = 0xd0e84f0f; ao->o |= reg1 << 4; ao->o |= reg2 << 24; return 4; } else if (ldrsel == H_BIT) { ao->o = 0xd0e85f0f; ao->o |= reg1 << 4; ao->o |= reg2 << 24; return 4; } else if (ldrsel == 0) { ao->a[1][strlen (ao->a[1]) - 1] = '\0'; ao->a[2] = "0]"; } else { return -1; } } // intentional fallthrough case THUMB_REG_BRACKREG_CONSTBRACK: { st32 num = getnummemend (ao->a[2]); if ((ldrsel != 0) || (num < 0) || (num > 1020) || (num % 4 != 0)) { return -1; } ao->o = 0x50e8000f; ao->o |= (num >> 2) << 8; return mem_32bit_2reg (ao, m); } break; case THUMB_REG_REG_BRACKREGBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstartend (ao->a[2]); if (!(ldrsel & D_BIT)) { return -1; } ao->o = 0xd0e87f00; ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "lsl", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 num = getnum (ao->a[2]); if (num > 32) { return -1; } ao->o = 0x0000; if (std_16bit_2reg (ao, m)) { ao->o |= (num & 0x03) << 14; ao->o |= num >> 2; return 2; } ao->o = 0x4fea0000; ao->o |= reg1; ao->o |= reg2 << 8; ao->o |= (num >> 2) << 4; ao->o |= (num & 0x3) << 14; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; case THUMB_REG_REG: { ao->o = 0x8040; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x00fa00f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "lsr", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 num = getnum (ao->a[2]); if (num > 32) { return -1; } ao->o = 0x0008; if (std_16bit_2reg (ao, m)) { ao->o |= (num & 0x03) << 14; ao->o |= num >> 2; return 2; } ao->o = 0x4fea1000; ao->o |= reg1; ao->o |= reg2 << 8; ao->o |= (num >> 2) << 4; ao->o |= (num & 0x3) << 14; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; case THUMB_REG_REG: { ao->o = 0xc040; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x20fa00f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "mcr", R_BIT | TWO_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_COPROC_CONST_REG_COREG_COREG: { ao->a[5] = "0"; } // intentional fallthrough case THUMB_COPROC_CONST_REG_COREG_COREG_CONST: { ut32 coproc = getcoproc (ao->a[0]); ut32 opc1 = getnum (ao->a[1]); ut32 reg1 = getreg (ao->a[2]); ut32 coreg1 = getcoprocreg (ao->a[3]); ut32 coreg2 = getcoprocreg (ao->a[4]); ut32 opc2 = getnum (ao->a[5]); if ((coproc > 15) || (opc1 > 7) || (reg1 > 15) || (coreg1 > 15) || (coreg2 > 15) || (opc2 > 7) || (m & R_BIT)) { return -1; } ao->o = 0x00ee1000; if (m & TWO_BIT) { ao->o |= 1 << 20; } ao->o |= coproc; ao->o |= opc1 << 29; ao->o |= reg1 << 4; ao->o |= coreg1 << 24; ao->o |= coreg2 << 8; ao->o |= opc2 << 13; return 4; } break; case THUMB_COPROC_CONST_REG_REG_COREG: { ut32 coproc = getcoproc (ao->a[0]); ut32 opc = getnum (ao->a[1]); ut32 reg1 = getreg (ao->a[2]); ut32 reg2 = getreg (ao->a[3]); ut32 coreg = getcoprocreg (ao->a[4]); if ((coproc > 15) || (opc > 15) || (reg1 > 15) || (reg2 > 15) || (coreg > 15) || (!(m & R_BIT))) { return -1; } ao->o = 0x40ec0000; if (m & TWO_BIT) { ao->o |= 1 << 20; } ao->o |= coproc; ao->o |= opc << 12; ao->o |= reg1 << 4; ao->o |= reg2 << 24; ao->o |= coreg << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "mla", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut32 reg4 = getreg (ao->a[3]); if (reg4 > 15) { return -1; } ao->o = 0x00fb0000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "mls", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut32 reg4 = getreg (ao->a[3]); if (reg4 > 15) { return -1; } ao->o = 0x00fb1000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "mov", S_BIT | W_BIT | T_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut32 reg1 = getreg (ao->a[0]); err = false; ut32 num = getnum (ao->a[1]); if (reg1 > 15) { return -1; } if ((m & W_BIT) || (m & T_BIT)) { ut32 wnum = getnum (ao->a[1]); if (wnum > 65535) { return -1; } ao->o = 0x40f20000; if (m & T_BIT) { ao->o |= 1 << 31; } ao->o |= reg1; ao->o |= getthzeroimmed16 (wnum); return 4; } if (err) { return -1; } if ((num < 256) && (reg1 < 8) && (!(m & DOTW_BIT))) { ao->o = 0x0020; ao->o |= reg1; ao->o |= num << 8; return 2; } ao->o = 0x4ff00000; ao->o |= reg1; ao->o |= getthimmed12 (ao->a[1]); if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; case THUMB_REG_REG: { ut32 reg1 = getreg (ao->a[0]); ut32 reg2 = getreg (ao->a[1]); if ((reg1 > 15) || (reg2 > 15)) { return -1; } if ((!(m & S_BIT)) && (!(m & DOTW_BIT))) { ao->o = 0x0046; ao->o |= (reg1 & 0x7) << 8; ao->o |= (reg1 & 0x8) << 12; ao->o |= reg2 << 11; return 2; } if ((reg1 < 8) && (reg2 < 8) && (!(m & DOTW_BIT))) { ao->o = 0; ao->o |= reg1 << 8; ao->o |= reg2 << 11; return 2; } ao->o = 0x4fea0000; ao->o |= reg1; ao->o |= reg2 << 8; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "mrc", TWO_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_COPROC_CONST_REG_COREG_COREG: { ao->a[5] = "0"; } // intentional fallthrough case THUMB_COPROC_CONST_REG_COREG_COREG_CONST: { ut32 coproc = getcoproc (ao->a[0]); ut32 opc1 = getnum (ao->a[1]); ut32 reg1 = getreg (ao->a[2]); ut32 coreg1 = getcoprocreg (ao->a[3]); ut32 coreg2 = getcoprocreg (ao->a[4]); ut32 opc2 = getnum (ao->a[5]); if ((coproc > 15) || (opc1 > 7) || (reg1 > 15) || (coreg1 > 15) || (coreg2 > 15) || (opc2 > 7)) { return -1; } ao->o = 0x10ee1000; if (m & TWO_BIT) { ao->o |= 1 << 20; } ao->o |= coproc; ao->o |= opc1 << 29; ao->o |= reg1 << 4; ao->o |= coreg1 << 24; ao->o |= coreg2 << 8; ao->o |= opc2 << 13; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "mrrc", TWO_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_COPROC_CONST_REG_REG_COREG: { ut32 coproc = getcoproc (ao->a[0]); ut32 opc = getnum (ao->a[1]); ut32 reg1 = getreg (ao->a[2]); ut32 reg2 = getreg (ao->a[3]); ut32 coreg = getcoprocreg (ao->a[4]); if ((coproc > 15) || (opc > 15) || (reg1 > 15) || (reg2 > 15) || (coreg > 15)) { return -1; } ao->o = 0x50ec0000; if (m & TWO_BIT) { ao->o |= 1 << 20; } ao->o |= coproc; ao->o |= opc << 12; ao->o |= reg1 << 4; ao->o |= reg2 << 24; ao->o |= coreg << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "mrs", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_OTHER: { ut32 reg1 = getreg (ao->a[0]); r_str_case (ao->a[1], false); if (reg1 > 15) { return -1; } if ((!strcmp(ao->a[1], "cpsr")) || (!strcmp(ao->a[1], "apsr"))) { ao->o = 0xeff30080; ao->o |= reg1; return 4; } if (!strcmp(ao->a[1], "spsr")) { ao->o = 0xfff30080; ao->o |= reg1; return 4; } return -1; } break; default: return -1; } } else if ((m = opmask (ao->op, "msr", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_OTHER_REG: { r_str_case (ao->a[0], false); ut8 spsr = 0; ut8 bank = interpret_msrbank (ao->a[0], &spsr); ut32 reg1 = getreg (ao->a[1]); if ((bank == 0) || (reg1 > 15)) { return -1; } ao->o = 0x80f30080; ao->o |= reg1 << 24; ao->o |= bank; if (spsr != 0) { ao->o |= 1 << 28; } return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "mul", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg3 = getreg (ao->a[2]); ao->o = 0x4043; if ((reg1 == reg3) && (std_16bit_2reg (ao, m))) { return 2; } ao->o = 0x00fb00f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "mvn", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); err = false; ut32 num = getthimmed12 (ao->a[1]); if ((reg1 > 15) || err) { return -1; } ao->o = 0x6ff00000; ao->o |= reg1; ao->o |= num; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; case THUMB_REG_REG: { ao->a[2] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 shift = thumb_getshift (ao->a[2]); if ((reg1 > 15) || (reg2 > 15)) { return -1; } ao->o = 0xc043; if ((shift == 0) && (std_16bit_2reg (ao, m))) { return 2; } ao->o = 0x6fea0000; ao->o |= reg1; ao->o |= reg2 << 8; ao->o |= shift; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "nop", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { if (m & DOTW_BIT) { ao->o = 0xaff30080; return 4; } ao->o = 0x00bf; return 2; } break; default: return -1; } } else if ((m = opmask (ao->op, "orn", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { err = false; ut32 num = getthimmed12 (ao->a[2]); if (err) { return -1; } ao->o = 0x60f00000; ao->o |= num; return (std_32bit_2reg (ao, m, false)); } break; case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ao->o = 0x60ea0000; return std_32bit_3reg (ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "orr", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { err = false; ut32 num = getthimmed12 (ao->a[2]); if (err) { return -1; } ao->o = 0x40f00000; ao->o |= num; return std_32bit_2reg (ao, m, false); } break; case THUMB_REG_REG: { ao->o = 0x0043; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ao->o = 0x40ea0000; return (std_32bit_3reg (ao, m, true)); } break; default: return -1; } } else if ((m = opmask (ao->op, "pkh", BT_BIT | TB_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & TB_BIT) { ao->a[3] = "asr 0"; } else if (m & BT_BIT) { ao->a[3] = "lsl 0"; } else { return -1; } } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ut32 shift = thumb_getshift (ao->a[3]); if (((m & TB_BIT) && ((shift & 0x00003000) != 0x00002000)) || ((m & BT_BIT) && ((shift & 0x00003000) != 0)) || ((m & (TB_BIT | BT_BIT)) == 0)) { return -1; } ao->o = 0xc0ea0000; return (std_32bit_3reg (ao, m, true)); } break; default: return -1; } } else if ((m = opmask (ao->op, "pld", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_BRACKREG_CONSTBRACK: { ut8 reg1 = getregmemstart (ao->a[0]); st32 num = getnummemend (ao->a[1]); if (reg1 == 15) { if ((num < -4095) || (num > 4095)) { return -1; } ao->o = 0x1ff800f0; if (num > 0) { ao->o |= 1 << 31; } else { num = -num; } ao->o |= (num & 0x0ff) << 8; ao->o |= (num & 0xf00) >> 8; return 4; } if ((reg1 > 15) || (num < -255) || (num > 4095)) { return -1; } if (num > 0) { ao->o = 0x90f800f0; ao->o |= (num & 0x0ff) << 8; ao->o |= (num & 0xf00) >> 8; ao->o |= reg1 << 24; return 4; } num = -num; ao->o = 0x10f800fc; ao->o |= num << 8; ao->o |= reg1 << 24; return 4; } break; case THUMB_BRACKREG_REGBRACK: { ao->a[1][strlen (ao->a[1]) - 1] = '\0'; ao->a[2] = "lsl 0]"; } // intentional fallthrough case THUMB_BRACKREG_REG_SHIFTBRACK: { ut8 reg1 = getregmemstart (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 shift = getshiftmemend (ao->a[2]) >> 2; if ((reg1 > 15) || (reg2 > 15) || ((shift & 0xffffcfff) != 0)) { return -1; } ao->o = 0x10f800f0; ao->o |= reg1 << 24; ao->o |= reg2 << 8; ao->o |= shift; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "pli", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_BRACKREG_CONSTBRACK: { ut8 reg1 = getregmemstart (ao->a[0]); st32 num = getnummemend (ao->a[1]); if (reg1 == 15) { if ((num < -4095) || (num > 4095)) { return -1; } ao->o = 0x1ff900f0; if (num > 0) { ao->o |= 1 << 31; } else { num = -num; } ao->o |= (num & 0x0ff) << 8; ao->o |= (num & 0xf00) >> 8; return 4; } if ((reg1 > 15) || (num < -255) || (num > 4095)) { return -1; } if (num > 0) { ao->o = 0x90f900f0; ao->o |= (num & 0x0ff) << 8; ao->o |= (num & 0xf00) >> 8; ao->o |= reg1 << 24; return 4; } num = -num; ao->o = 0x10f900fc; ao->o |= num << 8; ao->o |= reg1 << 24; return 4; } break; case THUMB_BRACKREG_REGBRACK: { ao->a[1][strlen (ao->a[1]) -1] = '\0'; ao->a[2] = "lsl 0]"; } // intentional fallthrough case THUMB_BRACKREG_REG_SHIFTBRACK: { ut8 reg1 = getregmemstart (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 shift = getshiftmemend (ao->a[2]) >> 2; if ((reg1 > 15) || (reg2 > 15) || ((shift & 0xffffcfff) != 0)) { return -1; } ao->o = 0x10f900f0; ao->o |= reg1 << 24; ao->o |= reg2 << 8; ao->o |= shift; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "pop", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_LIST: { st32 list = getreglist (ao->a[0]); if ((list <= 0) || ((list & (1 << 13)) != 0)) { return -1; } if ((!(m & DOTW_BIT)) && ((list & 0x00007f00) == 0)) { ao->o = 0x00bc; ao->o |= (list & 0x8000) >> 15; ao->o |= (list & 0xff) << 8; return 2; } ao->o = 0xbde80000; ao->o |= (list & 0xff00) >> 8; ao->o |= (list & 0xff) << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "push", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_LIST: { st32 list = getreglist (ao->a[0]); if ((list <= 0) || ((list & 0x0000a000) != 0)) { return -1; } if ((!(m & DOTW_BIT)) && ((list & 0x00001f00) == 0)) { ao->o = 0x00b4; ao->o |= (list & 0x4000) >> 14; ao->o |= (list & 0xff) << 8; return 2; } ao->o = 0x2de90000; ao->o |= (list & 0xff00) >> 8; ao->o |= (list & 0xff) << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "qadd", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & SIXTEEN_BIT) { ao->o = 0x90fa10f0; } else if (m & EIGHT_BIT) { ao->o = 0x80fa10f0; } else { ao->o = 0x80fa80f0; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "qasx", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xa0fa10f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "qdadd", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x80fa90f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "qdsub", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x80fab0f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "qsax", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xe0fa10f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "qsub", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & SIXTEEN_BIT) { ao->o = 0xd0fa10f0; } else if (m & EIGHT_BIT) { ao->o = 0xc0fa10f0; } else { ao->o = 0x80faa0f0; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "rbit", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { ao->a[2] = ao->a[1]; ao->o = 0x90faa0f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "rev", SIXTEEN_BIT | SH_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { if (m & SIXTEEN_BIT) { ao->o = 0x40ba; } else if (m & SH_BIT) { ao->o = 0xc0ba; } else { ao->o = 0x00ba; } if (std_16bit_2reg (ao, m)) { return 2; } if (m & SIXTEEN_BIT) { ao->o = 0x90fa90f0; } else if (m & SH_BIT) { ao->o = 0x90fab0f0; } else { ao->o = 0x90fa80f0; } ao->a[2] = ao->a[1]; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "rfe", IA_BIT | FD_BIT | DB_BIT | EA_BIT))) { ut64 argt = thumb_selector (ao->a); ut32 wb = 0; switch (argt) { case THUMB_REGBANG: { ao->a[0][strlen (ao->a[0]) - 1] = '\0'; wb = 0x20000000; } // intentional fallthrough case THUMB_REG: { ut8 reg1 = getreg (ao->a[0]); if (reg1 > 15) { return -1; } if ((m & DB_BIT) || (m & EA_BIT)) { ao->o = 0x10e800c0; } else { ao->o = 0x90e900c0; } ao->o |= reg1 << 24; ao->o |= wb; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "ror", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 num = getnum (ao->a[2]); if ((reg1 > 15) || (reg2 > 15) || (num > 31) || (num < 1)) { return -1; } ao->o = 0x4fea3000; ao->o |= reg1; ao->o |= reg2 << 8; ao->o |= (num & 0x3) << 14; ao->o |= (num & 0x1c) << 2; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; case THUMB_REG_REG: { ao->o = 0xc041; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x60fa00f0; return (std_32bit_3reg (ao, m, false)); } break; default: return -1; } } else if ((m = opmask (ao->op, "rrx", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); if ((reg1 > 15) || (reg2 > 15)) { return -1; } ao->o = 0x4fea3000; ao->o |= reg1; ao->o |= reg2 << 8; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "rsb", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { err = false; ut32 num = getthimmed12 (ao->a[2]); if (err) { return -1; } ao->o = 0x4042; if ((num == 0) && std_16bit_2reg (ao, m)) { return 2; } ao->o = 0xc0f10000; ao->o |= num; return (std_32bit_2reg (ao, m, false)); } break; case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ao->o = 0xc0eb0000; return (std_32bit_3reg (ao, m, true)); } break; default: return -1; } } else if ((m = opmask (ao->op, "sadd", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & SIXTEEN_BIT) { ao->o = 0x90fa00f0; } else if (m & EIGHT_BIT) { ao->o = 0x80fa00f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "sasx", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xa0fa00f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "sbc", S_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { ao->o = 0x8041; if (std_16bit_2reg (ao, m)) { return 2; } std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ao->o = 0x60eb0000; return std_32bit_3reg (ao, m, true); } break; case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { ao->o = 0x60f10000; err = false; ut32 num = getthimmed12 (ao->a[2]); if (err) { return -1; } ao->o |= num; return std_32bit_2reg (ao, m, false); } break; default: return -1; } } else if (( m = opmask (ao->op, "sbfx", 0) )) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_CONST_CONST: { ut32 lsb = getnum (ao->a[2]); ut32 width = getnum (ao->a[3]); ut32 msb = lsb + width - 1; if ((lsb > 31) || (msb > 31)) { return -1; } ao->o = 0x40f30000; ao->o |= ((lsb & 0x1c) << 2); ao->o |= ((lsb & 0x3) << 14); ao->o |= ((width - 1) << 8); return std_32bit_2reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "sdiv", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x90fbf0f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "sel", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xa0fa80f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "setend", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_OTHER: { r_str_case (ao->a[0], false); ao->o = 0x50b6; if (!(strcmpnull (ao->a[0], "be"))) { ao->o |= 1 << 11; return 2; } else if (!(strcmpnull (ao->a[0], "le"))) { return 2; } else { return -1; } break; } default: return -1; } } else if ((m = opmask (ao->op, "sev", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: if (m & DOTW_BIT) { ao->o = 0xaff30480; return 4; } else { ao->o = 0x40bf; return 2; } break; default: return -1; } } else if ((m = opmask (ao->op, "shadd", EIGHT_BIT | SIXTEEN_BIT ))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & SIXTEEN_BIT) { ao->o = 0x90fa20f0; } else if (m & EIGHT_BIT) { ao->o = 0x80fa20f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "shasx", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xa0fa20f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "shsax", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xe0fa20f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "shsub", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & SIXTEEN_BIT) { ao->o = 0xd0fa20f0; } else if (m & EIGHT_BIT) { ao->o = 0xc0fa20f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "smc", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_CONST: { err = false; ut32 num = getnum (ao->a[0]); if (err || (num > 15)) { return -1; } ao->o = 0xf0f70080; ao->o |= num << 24; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "smla", BB_BIT | BT_BIT | TB_BIT | TT_BIT | WB_BIT | WT_BIT | L_BIT | D_BIT | X_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getreg (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15) || (m & DOTN_BIT)) { return -1; } if (m & L_BIT) { if (m & BB_BIT) { ao->o = 0xc0fb8000; } else if (m & BT_BIT) { ao->o = 0xc0fb9000; } else if (m & TB_BIT) { ao->o = 0xc0fba000; } else if (m & TT_BIT) { ao->o = 0xc0fbb000; } else if (m & D_BIT) { ao->o = 0xc0fbc000; if (m & X_BIT) { ao->o |= 1 << 12; } } else { ao->o = 0xc0fb0000; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= reg4 << 8; return 4; } if (m & BB_BIT) { ao->o = 0x10fb0000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } if (m & BT_BIT) { ao->o = 0x10fb1000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } if (m & TB_BIT) { ao->o = 0x10fb2000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } if (m & TT_BIT) { ao->o = 0x10fb3000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } if (m & D_BIT) { ao->o = 0x20fb0000; if (m & X_BIT) { ao->o |= 1 << 12; } ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } if (m & WB_BIT) { ao->o = 0x30fb0000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } if (m & WT_BIT) { ao->o = 0x30fb1000; ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } return -1; } break; default: return -1; } } else if ((m = opmask (ao->op, "smlsd", X_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg4 = getreg (ao->a[3]); if (reg4 > 15) { return -1; } ao->o = 0x40fb0000; if (m & X_BIT) { ao->o |= 1 << 12; } ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "smlsld", X_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getreg (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15) || (m & DOTN_BIT)) { return -1; } ao->o = 0xd0fbc000; if (m & X_BIT) { ao->o |= 1 << 12; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= reg4 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "smmla", R_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg4 = getreg (ao->a[3]); if (reg4 > 15) { return -1; } ao->o = 0x50fb0000; if (m & R_BIT) { ao->o |= 1 << 12; } ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "smmls", R_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg4 = getreg (ao->a[3]); if (reg4 > 15) { return -1; } ao->o = 0x60fb0000; if (m & R_BIT) { ao->o |= 1 << 12; } ao->o |= reg4 << 4; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "smmul", R_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x50fb00f0; if (m & R_BIT) { ao->o |= 1 << 12; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "smuad", X_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x20fb00f0; if (m & X_BIT) { ao->o |= 1 << 12; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "smul", BB_BIT | BT_BIT | TB_BIT | TT_BIT | WB_BIT | WT_BIT | L_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & BB_BIT) { ao->o = 0x10fb00f0; } else if (m & BT_BIT) { ao->o = 0x10fb10f0; } else if (m & TB_BIT) { ao->o = 0x10fb20f0; } else if (m & TT_BIT) { ao->o = 0x10fb30f0; } else if (m & WB_BIT) { ao->o = 0x30fb00f0; } else if (m & WT_BIT) { ao->o = 0x30fb10f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; case THUMB_REG_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getreg (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15) || (m & DOTN_BIT) || (!(m & L_BIT))) { return -1; } ao->o = 0x80fb0000; ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= reg4 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "smusd", X_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x40fb00f0; if (m & X_BIT) { ao->o |= 1 << 12; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "srs", DB_BIT | FD_BIT | IA_BIT | EA_BIT))) { ut32 w = 0; ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_CONSTBANG: { ao->a[0][strlen (ao->a[0]) - 1] = '\0'; w = 1; } // intentional fallthrough case THUMB_CONST: { ut32 num = getnum (ao->a[0]); if (num > 31) { return -1; } if ((m & DB_BIT) || (m & FD_BIT)) { ao->o = 0x0de800c0; } else { ao->o = 0x8de900c0; } ao->o |= num << 8; ao->o |= w << 29; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "ssat", SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_CONST_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut32 num = getnum (ao->a[1]) - 1; ut8 reg2 = getreg (ao->a[2]); ut32 shift = thumb_getshift (ao->a[3]); if (err || (reg1 > 15) || (reg2 > 15) || (num > 31) || (shift & 0x00001000) || ((m & SIXTEEN_BIT) && shift)) { return -1; } if (shift & 0x00002000) { shift |= 0x20000000; shift &= 0xffffdfff; } if (m & SIXTEEN_BIT) { ao->o = 0x20f30000; } else { ao->o = 0x00f30000; } ao->o |= reg1; ao->o |= reg2 << 24; ao->o |= num << 8; ao->o |= shift; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "ssax", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xe0fa00f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "ssub", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & EIGHT_BIT) { ao->o = 0xc0fa00f0; } else if (m & SIXTEEN_BIT) { ao->o = 0xd0fa00f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "stc", L_BIT | TWO_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_COPROC_COREG_BRACKREGBRACK: { ao->a[2][strlen (ao->a[2]) - 1] = '\0'; ao->a[3] = "0]"; } // intentional fallthrough case THUMB_COPROC_COREG_BRACKREG_CONSTBRACK: { ut8 coproc = getcoproc (ao->a[0]); ut8 coreg = getcoprocreg (ao->a[1]); ut8 reg = getregmemstart (ao->a[2]); st32 num = getnummemend (ao->a[3]); if ((coproc > 15) || (coreg > 15) || (reg > 15) || (num > 4092) || (num < -4092) || (num % 4 != 0)) { return -1; } ao->o = 0x00ed0000; if (m & L_BIT) { ao->o |= 1 << 30; } if (m & TWO_BIT) { ao->o |= 1 << 20; } if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= coproc; ao->o |= coreg << 4; ao->o |= reg << 24; ao->o |= (num >> 2) << 8; return 4; } break; case THUMB_COPROC_COREG_BRACKREGBRACK_CONST: { ut8 coproc = getcoproc (ao->a[0]); ut8 coreg = getcoprocreg (ao->a[1]); ut8 reg = getregmemstartend (ao->a[2]); st32 num = getnum (ao->a[3]); if ((coproc > 15) || (coreg > 15) || (reg > 15) || (num > 4092) || (num < -4092) || (num % 4 != 0)) { return -1; } ao->o = 0x20ec0000; if (m & L_BIT) { ao->o |= 1 << 30; } if (m & TWO_BIT) { ao->o |= 1 << 20; } if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= coproc; ao->o |= coreg << 4; ao->o |= reg << 24; ao->o |= (num >> 2) << 8; return 4; } break; case THUMB_COPROC_COREG_BRACKREG_CONSTBRACKBANG: { ut8 coproc = getcoproc (ao->a[0]); ut8 coreg = getcoprocreg (ao->a[1]); ut8 reg = getregmemstart (ao->a[2]); st32 num = getnummemendbang (ao->a[3]); if ((coproc > 15) || (coreg > 15) || (reg > 15) || (num > 4092) || (num < -4092) || (num % 4 != 0)) { return -1; } ao->o = 0x20ed0000; if (m & L_BIT) { ao->o |= 1 << 30; } if (m & TWO_BIT) { ao->o |= 1 << 20; } if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= coproc; ao->o |= coreg << 4; ao->o |= reg << 24; ao->o |= (num >> 2) << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "stm", FD_BIT | DB_BIT | IA_BIT | EA_BIT))) { ut64 argt = thumb_selector (ao->a); bool wb = false; switch (argt) { case THUMB_REGBANG_LIST: { wb = true; ao->a[0][strlen (ao->a[0]) - 1] = '\0'; } // intentional fallthrough case THUMB_REG_LIST: { ut8 reg = getreg (ao->a[0]); st32 list = getreglist (ao->a[1]); if ((list <= 0) || ((list & 0x0000a000) != 0)) { return -1; } if ((!(m & DOTW_BIT)) && ((list & 0x0000ff00) == 0) && (!(m & (FD_BIT | DB_BIT))) && wb) { ao->o = 0x00c0; ao->o |= (list & 0x000000ff) << 8; ao->o |= reg; return 2; } if ((m & (FD_BIT | DB_BIT | IA_BIT | EA_BIT)) == 0) { return -1; } if (m & (FD_BIT | DB_BIT)) { ao->o = 0x00e90000; } else { ao->o = 0x80e80000; } if (wb) { ao->o |= 1 << 29; } ao->o |= reg << 24; ao->o |= (list & 0x000000ff) << 8; ao->o |= (list & 0x0000ff00) >> 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "str", B_BIT | T_BIT | D_BIT | H_BIT))) { ut64 argt = thumb_selector (ao->a); ut32 strsel = m & (B_BIT | H_BIT | D_BIT); switch (argt) { case THUMB_REG_BRACKREGBRACK: if (ao->a[2] == NULL) { // double fallthrough ao->a[1][strlen (ao->a[1]) -1] = '\0'; ao->a[2] = "0]"; } // intentional fallthrough case THUMB_REG_BRACKREG_CONSTBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getregmemstart (ao->a[1]); st32 num = getnummemend (ao->a[2]); if (m & T_BIT) { if ((num < 0) || (num > 255)) { return -1; } if (strsel == 0) { ao->o = 0x40f8000e; } else if (strsel == H_BIT) { ao->o = 0x20f8000e; } else if (strsel == B_BIT) { ao->o = 0x00f8000e; } else { return -1; } ao->o |= num << 8; return mem_32bit_2reg (ao, m); } if ((strsel == 0) && (reg2 == 13) && (num >= 0) && (num < 1024) && ((num % 4) == 0) && (reg1 < 8) & (!(m & DOTW_BIT))) { ao->o = 0x0090; ao->o |= reg1; ao->o |= (num >> 2) << 8; return 2; } bool t1form = false; if ((strsel == 0) && (num < 128) && (num >= 0) && (num % 4 == 0)) { ao->o = 0x0060; ao->o |= (num >> 4); ao->o |= ((num >> 2) & 0x3) << 14; t1form = true; } if ((strsel == B_BIT) && (num < 32) && (num >= 0)) { ao->o = 0x0070; ao->o |= (num >> 2); ao->o |= (num & 0x3) << 14; t1form = true; } if ((strsel == H_BIT) && (num < 64) && (num >= 0) && (num % 2 == 0)) { ao->o = 0x0080; ao->o |= (num >> 3); ao->o |= ((num >> 1) & 0x3) << 14; t1form = true; } if (t1form) { if (mem_16bit_2reg (ao, m)) { return 2; } } if ((num > 4095) || (num < -255)) { return -1; } if ((num >= 0) && (num < 4096)) { if (strsel == 0) { ao->o = 0xc0f80000; } else if (strsel == B_BIT) { ao->o = 0x80f80000; } else if (strsel == H_BIT) { ao->o = 0xa0f80000; } else { return -1; } ao->o |= (num >> 8); ao->o |= (num & 0x000000ff) << 8; return mem_32bit_2reg (ao, m); } if (strsel == 0) { ao->o = 0x40f8000c; } else if (strsel == B_BIT) { ao->o = 0x00f8000c; } else if (strsel == H_BIT) { ao->o = 0x20f8000c; } else { return -1; } ao->o |= -num << 8; return mem_32bit_2reg (ao, m); } break; case THUMB_REG_BRACKREGBRACK_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getregmemstartend (ao->a[1]); st32 num = getnum (ao->a[2]); if ((num > 255) || (num < -255)) { return -1; } if (strsel == 0) { ao->o = 0x40f80009; } else if (strsel == B_BIT) { ao->o = 0x00f80009; } else if (strsel == H_BIT) { ao->o = 0x20f80009; } else { return -1; } if (num < 0) { num = -num; } else { ao->o |= 1 << 1; } ao->o |= num << 8; ao->o |= reg1 << 4; ao->o |= reg2 << 24; return 4; } break; case THUMB_REG_BRACKREG_CONSTBRACKBANG: { st32 num = getnummemendbang (ao->a[2]); if ((num > 255) || (num < -255)) { return -1; } if (strsel == 0) { ao->o = 0x40f8000d; } else if (strsel == B_BIT) { ao->o = 0x00f8000d; } else if (strsel == H_BIT) { ao->o = 0x20f8000d; } else { return -1; } if (num < 0) { num = -num; } else { ao->o |= 1 << 1; } ao->o |= num << 8; return mem_32bit_2reg (ao, m); } break; case THUMB_REG_BRACKREG_REGBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getregmemstart (ao->a[1]); ut8 reg3 = getregmemend (ao->a[2]); if ((reg1 < 8) && (reg2 < 8) && (reg3 < 8) && (!(m & DOTW_BIT))) { if (strsel == 0) { ao->o = 0x0050; } else if (strsel == B_BIT) { ao->o = 0x0054; } else if (strsel == H_BIT) { ao->o = 0x0052; } else { return -1; } ao->o |= reg1 << 8; ao->o |= reg2 << 11; ao->o |= (reg3 & 0x3) << 14; ao->o |= (reg3 >> 2); return 2; } ao->a[2][strlen (ao->a[2]) - 1] = '\0'; ao->a[3] = "lsl 0]"; } // intentional fallthrough case THUMB_REG_BRACKREG_REG_SHIFTBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getregmemstart (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut32 shift = getshiftmemend (ao->a[3]) >> 2; if (((shift & 0xffffcfff) != 0) || (reg1 > 15) || (reg2 > 15) || (reg3 > 15)) { return -1; } if (strsel == 0) { ao->o = 0x40f80000; } else if (strsel == B_BIT) { ao->o = 0x00f80000; } else if (strsel == H_BIT) { ao->o = 0x20f80000; } else { return -1; } ao->o |= reg1 << 4; ao->o |= reg2 << 24; ao->o |= reg3 << 8; ao->o |= shift; return 4; } break; case THUMB_REG_REG_BRACKREGBRACK: { ao->a[2][strlen (ao->a[2]) - 1] = '\0'; ao->a[3] = "0]"; } // intentional fallthrough case THUMB_REG_REG_BRACKREG_CONSTBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstart (ao->a[2]); st32 num = getnummemend (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (strsel != D_BIT) || (num > 1023) || (num < -1023) || ((num % 4) != 0)) { return -1; } ao->o = 0x40e90000; if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= (num >> 2) << 8; return 4; } break; case THUMB_REG_REG_BRACKREG_CONSTBRACKBANG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstart (ao->a[2]); st32 num = getnummemendbang (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (strsel != D_BIT) || (num > 1023) || (num < -1023) || ((num % 4) != 0)) { return -1; } ao->o = 0x60e90000; if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= (num >> 2) << 8; return 4; } break; case THUMB_REG_REG_BRACKREGBRACK_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstartend (ao->a[2]); st32 num = getnum (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (strsel != D_BIT) || (num > 1023) || (num < -1023) || ((num % 4) != 0)) { return -1; } ao->o = 0x60e80000; if (num < 0) { num = -num; } else { ao->o |= 1 << 31; } ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= (num >> 2) << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "strex", B_BIT | D_BIT | H_BIT))) { ut64 argt = thumb_selector (ao->a); ut32 strsel = m & (B_BIT | H_BIT | D_BIT); switch (argt) { case THUMB_REG_REG_BRACKREGBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstartend (ao->a[2]); if ((strsel == D_BIT) || (reg1 > 15) || (reg2 > 15) || (reg3 > 15)) { return -1; } if (strsel == B_BIT) { ao->o = 0xc0e8400f; ao->o |= reg1 << 8; ao->o |= reg2 << 4; ao->o |= reg3 << 24; return 4; } else if (strsel == H_BIT) { ao->o = 0xc0e8500f; ao->o |= reg1 << 8; ao->o |= reg2 << 4; ao->o |= reg3 << 24; return 4; } ao->a[2][strlen (ao->a[2]) - 1] = '\0'; ao->a[3] = "0]"; } // intentional fallthrough case THUMB_REG_REG_BRACKREG_CONSTBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getregmemstart (ao->a[2]); st32 num = getnummemend (ao->a[3]); if ((strsel != 0) || (reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (num < 0) || (num > 1023) || ((num % 4) !=0)) { return -1; } ao->o = 0x40e80000; ao->o |= reg1; ao->o |= reg2 << 4; ao->o |= reg3 << 24; ao->o |= (num >> 2) << 8; return 4; } break; case THUMB_REG_REG_REG_BRACKREGBRACK: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getregmemstartend (ao->a[3]); if ((strsel != D_BIT) || (reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15)) { return -1; } ao->o = 0xc0e87000; ao->o |= reg1 << 8; ao->o |= reg2 << 4; ao->o |= reg3; ao->o |= reg4 << 24; return 4; } break; } } else if ((m = opmask (ao->op, "sub", S_BIT | W_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 num = getnum (ao->a[2]); if ((reg1 > 15) || (reg2 > 15)) { return -1; } if ((reg1 == 15) && (reg2 == 14) && (num < 256)) { ao->o = 0xdef3008f; ao->o |= num << 8; return 4; } if (reg2 == 13) { if ((reg1 == 13) && (!(m & DOTW_BIT)) && (!(m & W_BIT)) && (num <= 4096) && (num % 4 == 0)) { ao->o = 0x80b0; ao->o |= (num >> 2) << 8; return 2; } err = false; ut32 thnum = getthimmed12 (ao->a[2]); if (!err && (!(m & W_BIT))) { ao->o = 0xadf10000; ao->o |= thnum; ao->o |= reg1; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } if (num > 4096) { return -1; } ao->o = 0xadf20000; ao->o |= getthzeroimmed12 (num); ao->o |= reg1; return 4; } if ((reg1 < 8) && (reg2 < 8) && (!(m & DOTW_BIT)) && (!(m & W_BIT)) && (num < 8)) { ao->o = 0x001e; ao->o |= reg1 << 8; ao->o |= reg2 << 11; ao->o |= (num & 0x3) << 14; ao->o |= (num >> 2); return 2; } if ((reg1 < 8) && (reg1 == reg2) && (!(m & DOTW_BIT)) && (!(m & W_BIT)) && (num < 256)) { ao->o = 0x0038; ao->o |= reg1; ao->o |= num << 8; return 2; } err = false; ut32 thnum = getthimmed12 (ao->a[2]); if (!err && (!(m & W_BIT))) { ao->o = 0xa0f10000; ao->o |= thnum; return std_32bit_2reg (ao, m, false); } if (num > 4096) { return -1; } ao->o = 0xa0f20000; ao->o |= reg1; ao->o |= reg2 << 24; ao->o |= getthzeroimmed12 (num); return 4; } break; case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut32 shift = thumb_getshift (ao->a[3]); if (reg2 == 13) { ao->o = 0xadeb0000; ao->o |= reg1; ao->o |= reg3 << 8; ao->o |= shift; if (m & S_BIT) { ao->o |= 1 << 28; } return 4; } if ((shift == 0) && (reg1 < 8) && (reg2 < 8) && (reg3 < 8) && (!(m & DOTW_BIT))) { ao->o = 0x001a; ao->o |= reg1 << 8; ao->o |= reg2 << 11; ao->o |= (reg3 & 0x3) << 14; ao->o |= (reg3 >> 2); return 2; } ao->o = 0xa0eb0000; return std_32bit_3reg (ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "svc", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_CONST: { ut32 num = getnum (ao->a[0]); if (num > 255) { return -1; } ao->o = 0x00df; ao->o |= num << 8; return 2; } break; default: return -1; } } else if ((m = opmask (ao->op, "sxta", B_BIT | H_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ut32 shift = thumb_getshift (ao->a[3]); if ((shift != 0) && ((shift & 0x0000f010) != 0x00003000)) { return -1; } ut64 sufsel = m & (B_BIT | H_BIT | SIXTEEN_BIT); if (sufsel == B_BIT) { ao->o = 0x40fa80f0; } else if (sufsel == (B_BIT | SIXTEEN_BIT)) { ao->o = 0x20fa80f0; } else if (sufsel == H_BIT) { ao->o = 0x00fa80f0; } else { return -1; } ao->o |= (shift & 0x00000060) << 7; return std_32bit_3reg (ao, m, false); } break; } } else if ((m = opmask (ao->op, "sxt", B_BIT | H_BIT | SIXTEEN_BIT))) { ut64 sufsel = m & (B_BIT | H_BIT | SIXTEEN_BIT); ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { ao->a[2] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 shift = thumb_getshift (ao->a[2]); if ((reg1 > 15) && (reg2 > 15) && (shift != 0) && ((shift & 0x0000f010) != 0x00003000)) { return -1; } if (sufsel == B_BIT) { ao->o = 0x40b2; if ((shift == 0) && std_16bit_2reg (ao, m)) { return 2; } ao->o = 0x4ffa80f0; } else if (sufsel == (B_BIT | SIXTEEN_BIT)) { ao->o = 0x2ffa80f0; } else if (sufsel == H_BIT) { ao->o = 0x00b2; if ((shift == 0) && std_16bit_2reg (ao, m)) { return 2; } ao->o = 0x0ffa80f0; } else { return -1; } ao->o |= (shift & 0x00000060) << 7; ao->o |= reg1; ao->o |= reg2 << 8; return 4; } break; } } else if ((m = opmask (ao->op, "tb", B_BIT | H_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (B_BIT | H_BIT); switch (argt) { case THUMB_BRACKREG_REGBRACK: { ut8 reg1 = getregmemstart (ao->a[0]); ut8 reg2 = getregmemend (ao->a[1]); if ((reg1 > 15) || (reg2 > 15)) { return -1; } if (sufsel == B_BIT) { ao->o = 0xd0e800f0; ao->o |= reg1 << 24; ao->o |= reg2 << 8; return 4; } ao->a[1][strlen (ao->a[1]) - 1] = '\0'; ao->a[2] = "lsl 1]"; } // intentional fallthrough case THUMB_BRACKREG_REG_SHIFTBRACK: { ut8 reg1 = getregmemstart (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 shift = getshiftmemend (ao->a[2]); if ((reg1 > 15) || (reg2 > 15) || (shift != 0x00004000) || (sufsel != H_BIT)) { return -1; } ao->o = 0xd0e810f0; ao->o |= reg1 << 24; ao->o |= reg2 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "teq", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg = getreg (ao->a[0]); err = false; ut32 num = getthimmed12 (ao->a[1]); if (err || (reg > 15)) { return -1; } ao->o = 0x90f0000f; ao->o |= reg << 24; ao->o |= num; return 4; } break; case THUMB_REG_REG: { ao->a[2] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { ao->o = 0x90ea000f; return std_32bit_2reg (ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "tst", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST: { ut8 reg1 = getreg (ao->a[0]); err = false; ut32 num = getthimmed12 (ao->a[1]); if (err || (reg1 > 15)) { return -1; } ao->o = 0x10f0000f; ao->o |= reg1 << 24; ao->o |= num; return 4; } break; case THUMB_REG_REG: { ao->o = 0x0042; if (std_16bit_2reg (ao, m)) { return 2; } ao->a[2] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { ao->o = 0x10ea000f; return std_32bit_2reg (ao, m, true); } break; default: return -1; } } else if ((m = opmask (ao->op, "uadd", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (m & EIGHT_BIT) { ao->o = 0x80fa40f0; } else if (m & SIXTEEN_BIT) { ao->o = 0x90fa40f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uasx", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xa0fa40f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "ubfx", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_CONST_CONST: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 lsb = getnum (ao->a[2]); ut32 widthm1 = getnum (ao->a[3]) - 1; if ((reg1 > 15) || (reg2 > 15) || (lsb > 31) || ((31 - lsb) <= widthm1)) { return -1; } ao->o = 0xc0f30000; ao->o |= reg1; ao->o |= reg2 << 24; ao->o |= (lsb & 0x1c) << 2; ao->o |= (lsb & 0x3) << 14; ao->o |= widthm1 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "udiv", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xb0fbf0f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uhadd", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (EIGHT_BIT | SIXTEEN_BIT); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (sufsel == EIGHT_BIT) { ao->o = 0x80fa60f0; } else if (sufsel == SIXTEEN_BIT) { ao->o = 0x90fa60f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uhasx", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xa0fa60f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uhsax", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xe0fa60f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uhsub", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (EIGHT_BIT | SIXTEEN_BIT); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (sufsel == EIGHT_BIT) { ao->o = 0xc0fa60f0; } else if (sufsel == SIXTEEN_BIT) { ao->o = 0xd0fa60f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "umaal", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getreg (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15)) { return -1; } ao->o = 0xe0fb6000; ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= reg4 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "umlal", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getreg (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15)) { return -1; } ao->o = 0xe0fb0000; ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= reg4 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "umull", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getreg (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15)) { return -1; } ao->o = 0xa0fb0000; ao->o |= reg1 << 4; ao->o |= reg2; ao->o |= reg3 << 24; ao->o |= reg4 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "uqadd", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (EIGHT_BIT | SIXTEEN_BIT); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (sufsel == EIGHT_BIT) { ao->o = 0x80fa50f0; } else if (sufsel == SIXTEEN_BIT) { ao->o = 0x90fa50f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uqasx", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xa0fa50f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uqsax", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xe0fa50f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uqsub", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (EIGHT_BIT | SIXTEEN_BIT); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (sufsel == EIGHT_BIT) { ao->o = 0xc0fa50f0; } else if (sufsel == SIXTEEN_BIT) { ao->o = 0xd0fa50f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "usad8", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0x70fb00f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "usada8", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG_REG_REG: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut8 reg3 = getreg (ao->a[2]); ut8 reg4 = getreg (ao->a[3]); if ((reg1 > 15) || (reg2 > 15) || (reg3 > 15) || (reg4 > 15)) { return -1; } ao->o = 0x70fb0000; ao->o |= reg1; ao->o |= reg2 << 24; ao->o |= reg3 << 8; ao->o |= reg4 << 4; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "usat", SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_CONST_REG: { if (m & SIXTEEN_BIT) { ut8 reg1 = getreg (ao->a[0]); ut32 num = getnum (ao->a[1]); ut8 reg2 = getreg (ao->a[2]); if ((reg1 > 15) || (num > 15) || (reg2 > 15)) { return -1; } ao->o = 0xa0f30000; ao->o |= reg1; ao->o |= reg2 << 24; ao->o |= num << 8; return 4; } ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_CONST_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut32 num = getnum (ao->a[1]); ut8 reg2 = getreg (ao->a[2]); ut32 shift = thumb_getshift (ao->a[3]); if ((reg1 > 15) || (num > 31) || (reg2 > 15) || (m & SIXTEEN_BIT) || ((shift & 0x00001000) != 0)) { return -1; } ao->o = 0x80f30000; ao->o |= reg1; ao->o |= (num & 0xf) << 8; ao->o |= (num >> 4 ) << 12; ao->o |= reg2 << 24; ao->o |= (shift & 0x00002000) << 16; ao->o |= (shift & 0x0000c070); return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "usax", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->o = 0xe0fa40f0; return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "usub", EIGHT_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (EIGHT_BIT | SIXTEEN_BIT); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { if (sufsel == EIGHT_BIT) { ao->o = 0xc0fa40f0; } else if (sufsel == SIXTEEN_BIT) { ao->o = 0xd0fa40f0; } else { return -1; } return std_32bit_3reg (ao, m, false); } break; default: return -1; } } else if ((m = opmask (ao->op, "uxta", B_BIT | H_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (B_BIT | H_BIT | SIXTEEN_BIT); switch (argt) { case THUMB_REG_REG: { std_opt_2 (ao); } // intentional fallthrough case THUMB_REG_REG_REG: { ao->a[3] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { if (ao->a[3] == NULL) { // double fallthrough std_opt_3 (ao); } } // intentional fallthrough case THUMB_REG_REG_REG_SHIFT: { ut32 shift = thumb_getshift (ao->a[3]); if (shift && ((shift & 0x0000f010) != 0x00003000)) { return -1; } if (sufsel == B_BIT) { ao->o = 0x50fa80f0; } else if (sufsel == (B_BIT | SIXTEEN_BIT)) { ao->o = 0x30fa80f0; } else if (sufsel == H_BIT) { ao->o = 0x10fa80f0; } else { return -1; } ao->o |= (shift & 0x00000060) << 7; return (std_32bit_3reg (ao, m, false)); } break; default: return -1; } } else if ((m = opmask (ao->op, "uxt", B_BIT | H_BIT | SIXTEEN_BIT))) { ut64 argt = thumb_selector (ao->a); ut64 sufsel = m & (B_BIT | H_BIT | SIXTEEN_BIT); switch (argt) { case THUMB_REG_REG: { if ((sufsel == B_BIT) || (sufsel == H_BIT)) { if (sufsel == B_BIT) { ao->o = 0xc0b2; } else { ao->o = 0x80b2; } if (std_16bit_2reg (ao, m)) { return 2; } } ao->a[2] = "lsl 0"; } // intentional fallthrough case THUMB_REG_REG_SHIFT: { ut8 reg1 = getreg (ao->a[0]); ut8 reg2 = getreg (ao->a[1]); ut32 shift = thumb_getshift (ao->a[2]); if ((reg1 > 15) || (reg2 > 15) || (shift && ((shift & 0x0000f010) != 0x00003000))) { return -1; } if (sufsel == B_BIT) { ao->o = 0x5ffa80f0; } else if (sufsel == (B_BIT | SIXTEEN_BIT)) { ao->o = 0x3ffa80f0; } else if (sufsel == H_BIT) { ao->o = 0x1ffa80f0; } else { return -1; } ao->o |= (shift & 0x00000060) << 7; ao->o |= reg1; ao->o |= reg2 << 8; return 4; } break; default: return -1; } } else if ((m = opmask (ao->op, "wfe", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { if (m & DOTW_BIT) { ao->o = 0xaff30280; return 4; } else { ao->o = 0x20bf; return 2; } } break; default: return -1; } } else if ((m = opmask (ao->op, "wfi", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { if (m & DOTW_BIT) { ao->o = 0xaff30380; return 4; } else { ao->o = 0x30bf; return 2; } } break; default: return -1; } } else if ((m = opmask (ao->op, "yield", 0))) { ut64 argt = thumb_selector (ao->a); switch (argt) { case THUMB_NONE: { if (m & DOTW_BIT) { ao->o = 0xaff30180; return 4; } else { ao->o = 0x10bf; return 2; } } break; default: return -1; } } return 0; } static int findyz(int x, int *y, int *z) { int i, j; for (i = 0;i < 0xff; i++) { for (j = 0;j < 0xf;j++) { int v = i << j; if (v > x) { continue; } if (v == x) { *y = i; *z = 16 - (j / 2); return 1; } } } return 0; } static int arm_assemble(ArmOpcode *ao, ut64 off, const char *str) { int i, j, ret, reg, a, b; int coproc, opc; bool rex = false; int shift, low, high; for (i = 0; ops[i].name; i++) { if (!strncmp (ao->op, ops[i].name, strlen (ops[i].name))) { ao->o = ops[i].code; arm_opcode_cond (ao, strlen(ops[i].name)); if (ao->a[0] || ops[i].type == TYPE_BKP) { switch (ops[i].type) { case TYPE_MEM: if (!strncmp (ops[i].name, "strex", 5)) { rex = 1; } if (!strcmp (ops[i].name, "str") || !strcmp (ops[i].name, "ldr")) { if (!ao->a[2]) { ao->a[2] = "0"; } } getrange (ao->a[0]); getrange (ao->a[1]); getrange (ao->a[2]); if (ao->a[0] && ao->a[1]) { char rn[8]; strncpy (rn, ao->a[1], 7); int r0 = getreg (ao->a[0]); int r1 = getreg (ao->a[1]); if ((r0 < 0 || r0 > 15) || (r1 > 15 || r1 < 0)) { return 0; } ao->o |= r0 << 20; if (!strcmp (ops[i].name, "strd")) { r1 = getreg (ao->a[2]); if (r1 == -1) { break; } ao->o |= r1 << 8; if (ao->a[3]) { char *bracket = strchr (ao->a[3], ']'); if (bracket) { *bracket = '\0'; } int num = getnum (ao->a[3]); ao->o |= (num & 0x0f) << 24; ao->o |= ((num >> 4) & 0x0f) << 16; } break; } if (!strcmp (ops[i].name, "strh")) { ao->o |= r1 << 8; if (ao->a[2]) { reg = getreg (ao->a[2]); if (reg != -1) { ao->o |= reg << 24; } else { ao->o |= 1 << 14; ao->o |= getnum (ao->a[2]) << 24; } } else { ao->o |= 1 << 14; } break; } if (rex) { ao->o |= r1 << 24; } else { ao->o |= r1 << 8; // delta } } else { return 0; } ret = getreg (ao->a[2]); if (ret != -1) { if (rex) { ao->o |= 1; ao->o |= (ret & 0x0f) << 8; } else { ao->o |= (strstr (str, "],")) ? 6 : 7; ao->o |= (ret & 0x0f) << 24; } if (ao->a[3]) { shift = getshift (ao->a[3]); low = shift & 0xFF; high = shift & 0xFF00; ao->o |= low << 24; ao->o |= high << 8; } } else { int num = getnum (ao->a[2]) & 0xfff; if (err) { break; } if (rex) { ao->o |= 1; } else { ao->o |= (strstr (str, "],")) ? 4 : 5; } ao->o |= 1; ao->o |= (num & 0xff) << 24; ao->o |= ((num >> 8) & 0xf) << 16; } break; case TYPE_IMM: if (*ao->a[0]++ == '{') { for (j = 0; j < 16; j++) { if (ao->a[j] && *ao->a[j]) { getrange (ao->a[j]); // XXX filter regname string reg = getreg (ao->a[j]); if (reg != -1) { if (reg < 8) { ao->o |= 1 << (24 + reg); } else { ao->o |= 1 << (8 + reg); } } } } } else { ao->o |= getnum (ao->a[0]) << 24; // ??? } break; case TYPE_BRA: if ((ret = getreg (ao->a[0])) == -1) { // TODO: control if branch out of range ret = (getnum (ao->a[0]) - (int)ao->off - 8) / 4; if (ret >= 0x00800000 || ret < (int)0xff800000) { eprintf ("Branch into out of range\n"); return 0; } ao->o |= ((ret >> 16) & 0xff) << 8; ao->o |= ((ret >> 8) & 0xff) << 16; ao->o |= ((ret)&0xff) << 24; } else { eprintf ("This branch does not accept reg as arg\n"); return 0; } break; case TYPE_BKP: ao->o |= 0x70 << 24; if (ao->a[0]) { int n = getnum (ao->a[0]); ao->o |= ((n & 0xf) << 24); ao->o |= (((n >> 4) & 0xff) << 16); } break; case TYPE_BRR: if ((ret = getreg (ao->a[0])) == -1) { ut32 dst = getnum (ao->a[0]); dst -= (ao->off + 8); if (dst & 0x2) { ao->o = 0xfb; } else { ao->o = 0xfa; } dst /= 4; ao->o |= ((dst >> 16) & 0xff) << 8; ao->o |= ((dst >> 8) & 0xff) << 16; ao->o |= ((dst)&0xff) << 24; return 4; } else { ao->o |= (getreg (ao->a[0]) << 24); } break; case TYPE_HLT: { ut32 o = 0, n = getnum (ao->a[0]); o |= ((n >> 12) & 0xf) << 8; o |= ((n >> 8) & 0xf) << 20; o |= ((n >> 4) & 0xf) << 16; o |= ((n) & 0xf) << 24; ao->o |=o; } break; case TYPE_SWI: ao->o |= (getnum (ao->a[0]) & 0xff) << 24; ao->o |= ((getnum (ao->a[0]) >> 8) & 0xff) << 16; ao->o |= ((getnum (ao->a[0]) >> 16) & 0xff) << 8; break; case TYPE_UDF: { // e7f000f0 = udf 0 // e7ffffff = udf 0xffff ut32 n = getnum (ao->a[0]); ao->o |= 0xe7; ao->o |= (n & 0xf) << 24; ao->o |= ((n >> 4) & 0xff) << 16; ao->o |= ((n >> 12) & 0xf) << 8; } break; case TYPE_ARI: if (!ao->a[2]) { ao->a[2] = ao->a[1]; ao->a[1] = ao->a[0]; } reg = getreg (ao->a[0]); if (reg == -1) { return 0; } ao->o |= reg << 20; reg = getreg (ao->a[1]); if (reg == -1) { return 0; } ao->o |= reg << 8; reg = getreg (ao->a[2]); ao->o |= (reg != -1)? reg << 24 : 2 | getnum (ao->a[2]) << 24; if (ao->a[3]) { ao->o |= getshift (ao->a[3]); } break; case TYPE_SWP: { int a1 = getreg (ao->a[1]); if (a1) { ao->o = 0xe1; ao->o |= (getreg (ao->a[0]) << 4) << 16; ao->o |= (0x90 + a1) << 24; if (ao->a[2]) { ao->o |= (getreg (ao->a[2] + 1)) << 8; } else { return 0; } } if (0xff == ((ao->o >> 16) & 0xff)) { return 0; } } break; case TYPE_MOV: if (!strcmpnull (ao->op, "movs")) { ao->o = 0xb0e1; } ao->o |= getreg (ao->a[0]) << 20; ret = getreg (ao->a[1]); if (ret != -1) { ao->o |= ret << 24; } else { int immed = getimmed8 (ao->a[1]); if (err) { return 0; } ao->o |= 0xa003 | (immed & 0xff) << 24 | (immed >> 8) << 16; } break; case TYPE_MOVW: reg = getreg (ao->a[0]); if (reg == -1) { return 0; } ao->o |= getreg (ao->a[0]) << 20; ret = getnum (ao->a[1]); ao->o |= 0x3 | ret << 24; ao->o |= (ret & 0xf000) >> 4; ao->o |= (ret & 0xf00) << 8; break; case TYPE_MOVT: ao->o |= getreg (ao->a[0]) << 20; ret = getnum (ao->a[1]); ao->o |= 0x4003 | ret << 24; ao->o |= (ret & 0xf000) >> 4; ao->o |= (ret & 0xf00) << 8; break; case TYPE_MUL: if (!strcmpnull (ao->op, "mul")) { ret = getreg (ao->a[0]); a = getreg (ao->a[1]); b = getreg (ao->a[2]); if (b == -1) { b = a; a = ret; } if (ret == -1 || a == -1) { return 0; } ao->o |= ret << 8; ao->o |= a << 24; ao->o |= b << 16; } else { low = getreg (ao->a[0]); high = getreg (ao->a[1]); a = getreg (ao->a[2]); b = getreg (ao->a[3]); if (low == -1 || high == -1 || a == -1 || b == -1) { return 0; } if (!strcmpnull (ao->op, "smlal")) { ao->o |= low << 20; ao->o |= high << 8; ao->o |= a << 24; ao->o |= b << 16; } else if (!strncmp (ao->op, "smla", 4)) { if (low > 14 || high > 14 || a > 14) { return 0; } ao->o |= low << 8; ao->o |= high << 24; ao->o |= a << 16; ao->o |= b << 20; break; } else { ao->o |= low << 20; ao->o |= high << 8; ao->o |= a << 24; ao->o |= b << 16; } } break; case TYPE_TST: a = getreg (ao->a[0]); b = getreg (ao->a[1]); if (b == -1) { int y, z; b = getnum (ao->a[1]); if (b >= 0 && b <= 0xff) { ao->o = 0x50e3; // TODO: if (b>255) -> automatic multiplier ao->o |= (a << 8); ao->o |= ((b & 0xff) << 24); } else if (findyz (b, &y, &z)) { ao->o = 0x50e3; ao->o |= (y << 24); ao->o |= (z << 16); } else { eprintf ("Parameter %d out0x3000a0e1 of range (0-255)\n", (int)b); return 0; } } else { ao->o |= (a << 8); ao->o |= (b << 24); if (ao->a[2]) { ao->o |= getshift (ao->a[2]); } } if (ao->a[2]) { int n = getnum (ao->a[2]); if (n & 1) { eprintf ("Invalid multiplier\n"); return 0; } ao->o |= (n >> 1) << 16; } break; case TYPE_SHFT: reg = getreg (ao->a[2]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 16; reg = getreg (ao->a[0]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 20; reg = getreg (ao->a[1]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 24; break; case TYPE_REV: reg = getreg (ao->a[0]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 20; reg = getreg (ao->a[1]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 24; break; case TYPE_ENDIAN: if (!strcmp (ao->a[0], "le")) { ao->o |= 0; } else if (!strcmp (ao->a[0], "be")) { ao->o |= 0x20000; } else { return 0; } break; case TYPE_COPROC: //printf ("%s %s %s %s %s\n", ao->a[0], ao->a[1], ao->a[2], ao->a[3], ao->a[4] ); if (ao->a[0]) { coproc = getnum (ao->a[0] + 1); if (coproc == -1 || coproc > 9) { return 0; } ao->o |= coproc << 16; } opc = getnum (ao->a[1]); if (opc == -1 || opc > 7) { return 0; } ao->o |= opc << 13; reg = getreg (ao->a[2]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 20; // coproc register 1 const char *a3 = ao->a[3]; if (a3) { coproc = getnum (a3 + 1); if (coproc == -1 || coproc > 15) { return 0; } ao->o |= coproc << 8; } const char *a4 = ao->a[4]; if (a4) { coproc = getnum (ao->a[4] + 1); if (coproc == -1 || coproc > 15) { return 0; } ao->o |= coproc << 24; } coproc = getnum (ao->a[5]); if (coproc > -1) { if (coproc > 7) { return 0; } // optional opcode ao->o |= coproc << 29; } break; case TYPE_CLZ: ao->o |= 1 << 28; reg = getreg (ao->a[0]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 20; reg = getreg (ao->a[1]); if (reg == -1 || reg > 14) { return 0; } ao->o |= reg << 24; break; } } return 1; } } return 0; } typedef int (*AssembleFunction)(ArmOpcode *, ut64, const char *); static AssembleFunction assemble[2] = { &arm_assemble, &thumb_assemble }; ut32 armass_assemble(const char *str, ut64 off, int thumb) { int i, j; char buf[128]; ArmOpcode aop = {.off = off}; for (i = j = 0; i < sizeof (buf) - 1 && str[j]; i++, j++) { if (str[j] == '#') { i--; continue; } buf[i] = tolower ((const ut8)str[j]); } buf[i] = 0; arm_opcode_parse (&aop, buf); aop.off = off; if (thumb < 0 || thumb > 1) { return -1; } if (!assemble[thumb] (&aop, off, buf)) { //eprintf ("armass: Unknown opcode (%s)\n", buf); return -1; } return aop.o; } #ifdef MAIN void thisplay(const char *str) { char cmd[32]; int op = armass_assemble (str, 0x1000, 1); printf ("[%04x] %s\n", op, str); snprintf (cmd, sizeof(cmd), "rasm2 -d -b 16 -a arm %04x", op); system (cmd); } void display(const char *str) { char cmd[32]; int op = armass_assemble (str, 0x1000, 0); printf ("[%08x] %s\n", op, str); snprintf (cmd, sizeof(cmd), "rasm2 -d -a arm %08x", op); system (cmd); } int main() { thisplay ("ldmia r1!, {r3, r4, r5}"); thisplay ("stmia r1!, {r3, r4, r5}"); thisplay ("bkpt 12"); return 0; thisplay("sub r1, r2, 0"); thisplay("sub r1, r2, 4"); thisplay("sub r1, r2, 5"); thisplay("sub r1, r2, 7"); thisplay("sub r3, 44"); return 0; #if 0 thisplay("mov r0, 11"); thisplay("mov r0, r2"); thisplay("mov r1, r4"); thisplay("cmp r1, r2"); thisplay("cmp r3, 44"); thisplay("nop"); thisplay("svc 15"); thisplay("add r1, r2"); thisplay("add r3, 44"); thisplay("sub r1, r2, 3"); thisplay("sub r3, 44"); thisplay("tst r3,r4"); thisplay("bx r3"); thisplay("b 33"); thisplay("b 0"); thisplay("bne 44"); thisplay("and r2,r3"); #endif // INVALID thisplay("ldr r1, [pc, r2]"); // INVALID thisplay("ldr r1, [sp, r2]"); #if 0 thisplay("ldr r1, [pc, 12]"); thisplay("ldr r1, [sp, 24]"); thisplay("ldr r1, [r2, r3]"); #endif // INVALID thisplay("str r1, [pc, 22]"); // INVALID thisplay("str r1, [pc, r2]"); // INVALID thisplay("str r1, [sp, r2]"); #if 0 0: 8991 ldrh r1, [r2, #12] 2: 7b11 ldrb r1, [r2, #12] 4: 8191 strh r1, [r2, #12] 6: 7311 strb r1, [r2, #12] #endif thisplay("ldrh r1, [r2, 8]"); // aligned to 4 thisplay("ldrh r1, [r3, 8]"); // aligned to 4 thisplay("ldrh r1, [r4, 16]"); // aligned to 4 thisplay("ldrh r1, [r2, 32]"); // aligned to 4 thisplay("ldrb r1, [r2, 20]"); // aligned to 4 thisplay("strh r1, [r2, 20]"); // aligned to 4 thisplay("strb r1, [r2, 20]"); // aligned to 4 thisplay("str r1, [sp, 20]"); // aligned to 4 thisplay("str r1, [r2, 12]"); // OK thisplay("str r1, [r2, r3]"); return 0; #if 0 display("mov r0, 33"); display("mov r1, 33"); display("movne r0, 33"); display("tst r0, r1, lsl #2"); display("svc 0x80"); display("sub r3, r1, r2"); display("add r0, r1, r2"); display("mov fp, 0"); display("pop {pc}"); display("pop {r3}"); display("bx r1"); display("bx r3"); display("bx pc"); display("blx fp"); display("pop {pc}"); display("add lr, pc, lr"); display("adds r3, #8"); display("adds r3, r2, #8"); display("subs r2, #1"); display("cmp r0, r4"); display("cmp r7, pc"); display("cmp r1, r3"); display("mov pc, 44"); display("mov pc, r3"); display("push {pc}"); display("pop {pc}"); display("nop"); display("ldr r1, [r2, 33]"); display("ldr r1, [r2, r3]"); display("ldr r3, [r4, r6]"); display("str r1, [pc, 33]"); display("str r1, [pc], 2"); display("str r1, [pc, 3]"); display("str r1, [pc, r4]"); display("bx r3"); display("bcc 33"); display("blx r3"); display("bne 0x1200"); display("str r0, [r1]"); display("push {fp,lr}"); display("pop {fp,lr}"); display("pop {pc}"); #endif //10ab4: 00047e30 andeq r7, r4, r0, lsr lr //10ab8: 00036e70 andeq r6, r3, r0, ror lr display("andeq r7, r4, r0, lsr lr"); display("andeq r6, r3, r0, ror lr"); // c4: e8bd80f0 pop {r4, r5, r6, r7, pc} display("pop {r4,r5,r6,r7,pc}"); #if 0 display("blx r1"); display("blx 0x8048"); #endif #if 0 display("b 0x123"); display("bl 0x123"); display("blt 0x123"); // XXX: not supported #endif return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_501_0
crossvul-cpp_data_bad_2681_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Network File System (NFS) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "nfs.h" #include "nfsfh.h" #include "ip.h" #include "ip6.h" #include "rpc_auth.h" #include "rpc_msg.h" static const char tstr[] = " [|nfs]"; static void nfs_printfh(netdissect_options *, const uint32_t *, const u_int); static int xid_map_enter(netdissect_options *, const struct sunrpc_msg *, const u_char *); static int xid_map_find(const struct sunrpc_msg *, const u_char *, uint32_t *, uint32_t *); static void interp_reply(netdissect_options *, const struct sunrpc_msg *, uint32_t, uint32_t, int); static const uint32_t *parse_post_op_attr(netdissect_options *, const uint32_t *, int); /* * Mapping of old NFS Version 2 RPC numbers to generic numbers. */ static uint32_t nfsv3_procid[NFS_NPROCS] = { NFSPROC_NULL, NFSPROC_GETATTR, NFSPROC_SETATTR, NFSPROC_NOOP, NFSPROC_LOOKUP, NFSPROC_READLINK, NFSPROC_READ, NFSPROC_NOOP, NFSPROC_WRITE, NFSPROC_CREATE, NFSPROC_REMOVE, NFSPROC_RENAME, NFSPROC_LINK, NFSPROC_SYMLINK, NFSPROC_MKDIR, NFSPROC_RMDIR, NFSPROC_READDIR, NFSPROC_FSSTAT, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP }; static const struct tok nfsproc_str[] = { { NFSPROC_NOOP, "nop" }, { NFSPROC_NULL, "null" }, { NFSPROC_GETATTR, "getattr" }, { NFSPROC_SETATTR, "setattr" }, { NFSPROC_LOOKUP, "lookup" }, { NFSPROC_ACCESS, "access" }, { NFSPROC_READLINK, "readlink" }, { NFSPROC_READ, "read" }, { NFSPROC_WRITE, "write" }, { NFSPROC_CREATE, "create" }, { NFSPROC_MKDIR, "mkdir" }, { NFSPROC_SYMLINK, "symlink" }, { NFSPROC_MKNOD, "mknod" }, { NFSPROC_REMOVE, "remove" }, { NFSPROC_RMDIR, "rmdir" }, { NFSPROC_RENAME, "rename" }, { NFSPROC_LINK, "link" }, { NFSPROC_READDIR, "readdir" }, { NFSPROC_READDIRPLUS, "readdirplus" }, { NFSPROC_FSSTAT, "fsstat" }, { NFSPROC_FSINFO, "fsinfo" }, { NFSPROC_PATHCONF, "pathconf" }, { NFSPROC_COMMIT, "commit" }, { 0, NULL } }; /* * NFS V2 and V3 status values. * * Some of these come from the RFCs for NFS V2 and V3, with the message * strings taken from the FreeBSD C library "errlst.c". * * Others are errors that are not in the RFC but that I suspect some * NFS servers could return; the values are FreeBSD errno values, as * the first NFS server was the SunOS 2.0 one, and until 5.0 SunOS * was primarily BSD-derived. */ static const struct tok status2str[] = { { 1, "Operation not permitted" }, /* EPERM */ { 2, "No such file or directory" }, /* ENOENT */ { 5, "Input/output error" }, /* EIO */ { 6, "Device not configured" }, /* ENXIO */ { 11, "Resource deadlock avoided" }, /* EDEADLK */ { 12, "Cannot allocate memory" }, /* ENOMEM */ { 13, "Permission denied" }, /* EACCES */ { 17, "File exists" }, /* EEXIST */ { 18, "Cross-device link" }, /* EXDEV */ { 19, "Operation not supported by device" }, /* ENODEV */ { 20, "Not a directory" }, /* ENOTDIR */ { 21, "Is a directory" }, /* EISDIR */ { 22, "Invalid argument" }, /* EINVAL */ { 26, "Text file busy" }, /* ETXTBSY */ { 27, "File too large" }, /* EFBIG */ { 28, "No space left on device" }, /* ENOSPC */ { 30, "Read-only file system" }, /* EROFS */ { 31, "Too many links" }, /* EMLINK */ { 45, "Operation not supported" }, /* EOPNOTSUPP */ { 62, "Too many levels of symbolic links" }, /* ELOOP */ { 63, "File name too long" }, /* ENAMETOOLONG */ { 66, "Directory not empty" }, /* ENOTEMPTY */ { 69, "Disc quota exceeded" }, /* EDQUOT */ { 70, "Stale NFS file handle" }, /* ESTALE */ { 71, "Too many levels of remote in path" }, /* EREMOTE */ { 99, "Write cache flushed to disk" }, /* NFSERR_WFLUSH (not used) */ { 10001, "Illegal NFS file handle" }, /* NFS3ERR_BADHANDLE */ { 10002, "Update synchronization mismatch" }, /* NFS3ERR_NOT_SYNC */ { 10003, "READDIR/READDIRPLUS cookie is stale" }, /* NFS3ERR_BAD_COOKIE */ { 10004, "Operation not supported" }, /* NFS3ERR_NOTSUPP */ { 10005, "Buffer or request is too small" }, /* NFS3ERR_TOOSMALL */ { 10006, "Unspecified error on server" }, /* NFS3ERR_SERVERFAULT */ { 10007, "Object of that type not supported" }, /* NFS3ERR_BADTYPE */ { 10008, "Request couldn't be completed in time" }, /* NFS3ERR_JUKEBOX */ { 0, NULL } }; static const struct tok nfsv3_writemodes[] = { { 0, "unstable" }, { 1, "datasync" }, { 2, "filesync" }, { 0, NULL } }; static const struct tok type2str[] = { { NFNON, "NON" }, { NFREG, "REG" }, { NFDIR, "DIR" }, { NFBLK, "BLK" }, { NFCHR, "CHR" }, { NFLNK, "LNK" }, { NFFIFO, "FIFO" }, { 0, NULL } }; static const struct tok sunrpc_auth_str[] = { { SUNRPC_AUTH_OK, "OK" }, { SUNRPC_AUTH_BADCRED, "Bogus Credentials (seal broken)" }, { SUNRPC_AUTH_REJECTEDCRED, "Rejected Credentials (client should begin new session)" }, { SUNRPC_AUTH_BADVERF, "Bogus Verifier (seal broken)" }, { SUNRPC_AUTH_REJECTEDVERF, "Verifier expired or was replayed" }, { SUNRPC_AUTH_TOOWEAK, "Credentials are too weak" }, { SUNRPC_AUTH_INVALIDRESP, "Bogus response verifier" }, { SUNRPC_AUTH_FAILED, "Unknown failure" }, { 0, NULL } }; static const struct tok sunrpc_str[] = { { SUNRPC_PROG_UNAVAIL, "PROG_UNAVAIL" }, { SUNRPC_PROG_MISMATCH, "PROG_MISMATCH" }, { SUNRPC_PROC_UNAVAIL, "PROC_UNAVAIL" }, { SUNRPC_GARBAGE_ARGS, "GARBAGE_ARGS" }, { SUNRPC_SYSTEM_ERR, "SYSTEM_ERR" }, { 0, NULL } }; static void print_nfsaddr(netdissect_options *ndo, const u_char *bp, const char *s, const char *d) { const struct ip *ip; const struct ip6_hdr *ip6; char srcaddr[INET6_ADDRSTRLEN], dstaddr[INET6_ADDRSTRLEN]; srcaddr[0] = dstaddr[0] = '\0'; switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; strlcpy(srcaddr, ipaddr_string(ndo, &ip->ip_src), sizeof(srcaddr)); strlcpy(dstaddr, ipaddr_string(ndo, &ip->ip_dst), sizeof(dstaddr)); break; case 6: ip6 = (const struct ip6_hdr *)bp; strlcpy(srcaddr, ip6addr_string(ndo, &ip6->ip6_src), sizeof(srcaddr)); strlcpy(dstaddr, ip6addr_string(ndo, &ip6->ip6_dst), sizeof(dstaddr)); break; default: strlcpy(srcaddr, "?", sizeof(srcaddr)); strlcpy(dstaddr, "?", sizeof(dstaddr)); break; } ND_PRINT((ndo, "%s.%s > %s.%s: ", srcaddr, s, dstaddr, d)); } static const uint32_t * parse_sattr3(netdissect_options *ndo, const uint32_t *dp, struct nfsv3_sattr *sa3) { ND_TCHECK(dp[0]); sa3->sa_modeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_modeset) { ND_TCHECK(dp[0]); sa3->sa_mode = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_uidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_uidset) { ND_TCHECK(dp[0]); sa3->sa_uid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_gidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_gidset) { ND_TCHECK(dp[0]); sa3->sa_gid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_sizeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_sizeset) { ND_TCHECK(dp[0]); sa3->sa_size = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_atimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_atime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_atime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_mtimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_mtime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_mtime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } return dp; trunc: return NULL; } static int nfserr; /* true if we error rather than trunc */ static void print_sattr3(netdissect_options *ndo, const struct nfsv3_sattr *sa3, int verbose) { if (sa3->sa_modeset) ND_PRINT((ndo, " mode %o", sa3->sa_mode)); if (sa3->sa_uidset) ND_PRINT((ndo, " uid %u", sa3->sa_uid)); if (sa3->sa_gidset) ND_PRINT((ndo, " gid %u", sa3->sa_gid)); if (verbose > 1) { if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " atime %u.%06u", sa3->sa_atime.nfsv3_sec, sa3->sa_atime.nfsv3_nsec)); if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " mtime %u.%06u", sa3->sa_mtime.nfsv3_sec, sa3->sa_mtime.nfsv3_nsec)); } } void nfsreply_print(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; char srcid[20], dstid[20]; /*fits 32bit*/ nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_xid); if (!ndo->ndo_nflag) { strlcpy(srcid, "nfs", sizeof(srcid)); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } else { snprintf(srcid, sizeof(srcid), "%u", NFS_PORT); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } print_nfsaddr(ndo, bp2, srcid, dstid); nfsreply_print_noaddr(ndo, bp, length, bp2); return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } void nfsreply_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; uint32_t proc, vers, reply_stat; enum sunrpc_reject_stat rstat; uint32_t rlow; uint32_t rhigh; enum sunrpc_auth_stat rwhy; nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_reply.rp_stat); reply_stat = EXTRACT_32BITS(&rp->rm_reply.rp_stat); switch (reply_stat) { case SUNRPC_MSG_ACCEPTED: ND_PRINT((ndo, "reply ok %u", length)); if (xid_map_find(rp, bp2, &proc, &vers) >= 0) interp_reply(ndo, rp, proc, vers, length); break; case SUNRPC_MSG_DENIED: ND_PRINT((ndo, "reply ERR %u: ", length)); ND_TCHECK(rp->rm_reply.rp_reject.rj_stat); rstat = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_stat); switch (rstat) { case SUNRPC_RPC_MISMATCH: ND_TCHECK(rp->rm_reply.rp_reject.rj_vers.high); rlow = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.low); rhigh = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.high); ND_PRINT((ndo, "RPC Version mismatch (%u-%u)", rlow, rhigh)); break; case SUNRPC_AUTH_ERROR: ND_TCHECK(rp->rm_reply.rp_reject.rj_why); rwhy = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_why); ND_PRINT((ndo, "Auth %s", tok2str(sunrpc_auth_str, "Invalid failure code %u", rwhy))); break; default: ND_PRINT((ndo, "Unknown reason for rejecting rpc message %u", (unsigned int)rstat)); break; } break; default: ND_PRINT((ndo, "reply Unknown rpc response code=%u %u", reply_stat, length)); break; } return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Return a pointer to the first file handle in the packet. * If the packet was truncated, return 0. */ static const uint32_t * parsereq(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; register u_int len; /* * find the start of the req data (if we captured it) */ dp = (const uint32_t *)&rp->rm_call.cb_cred; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK2(dp[0], 0); return (dp); } } trunc: return (NULL); } /* * Print out an NFS file handle and return a pointer to following word. * If packet was truncated, return 0. */ static const uint32_t * parsefh(netdissect_options *ndo, register const uint32_t *dp, int v3) { u_int len; if (v3) { ND_TCHECK(dp[0]); len = EXTRACT_32BITS(dp) / 4; dp++; } else len = NFSX_V2FH / 4; if (ND_TTEST2(*dp, len * sizeof(*dp))) { nfs_printfh(ndo, dp, len); return (dp + len); } trunc: return (NULL); } /* * Print out a file name and return pointer to 32-bit word past it. * If packet was truncated, return 0. */ static const uint32_t * parsefn(netdissect_options *ndo, register const uint32_t *dp) { register uint32_t len; register const u_char *cp; /* Bail if we don't have the string length */ ND_TCHECK(*dp); /* Fetch string length; convert to host order */ len = *dp++; NTOHL(len); ND_TCHECK2(*dp, ((len + 3) & ~3)); cp = (const u_char *)dp; /* Update 32-bit pointer (NFS filenames padded to 32-bit boundaries) */ dp += ((len + 3) & ~3) / sizeof(*dp); ND_PRINT((ndo, "\"")); if (fn_printn(ndo, cp, len, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); return (dp); trunc: return NULL; } /* * Print out file handle and file name. * Return pointer to 32-bit word past file name. * If packet was truncated (or there was some other error), return 0. */ static const uint32_t * parsefhn(netdissect_options *ndo, register const uint32_t *dp, int v3) { dp = parsefh(ndo, dp, v3); if (dp == NULL) return (NULL); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp)); } void nfsreq_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; register const uint32_t *dp; nfs_type type; int v3; uint32_t proc; uint32_t access_flags; struct nfsv3_sattr sa3; ND_PRINT((ndo, "%d", length)); nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */ goto trunc; v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3); proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: case NFSPROC_SETATTR: case NFSPROC_READLINK: case NFSPROC_FSSTAT: case NFSPROC_FSINFO: case NFSPROC_PATHCONF: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefh(ndo, dp, v3) != NULL) return; break; case NFSPROC_LOOKUP: case NFSPROC_CREATE: case NFSPROC_MKDIR: case NFSPROC_REMOVE: case NFSPROC_RMDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefhn(ndo, dp, v3) != NULL) return; break; case NFSPROC_ACCESS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[0]); access_flags = EXTRACT_32BITS(&dp[0]); if (access_flags & ~NFSV3ACCESS_FULL) { /* NFSV3ACCESS definitions aren't up to date */ ND_PRINT((ndo, " %04x", access_flags)); } else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) { ND_PRINT((ndo, " NFS_ACCESS_FULL")); } else { char separator = ' '; if (access_flags & NFSV3ACCESS_READ) { ND_PRINT((ndo, " NFS_ACCESS_READ")); separator = '|'; } if (access_flags & NFSV3ACCESS_LOOKUP) { ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_MODIFY) { ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXTEND) { ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_DELETE) { ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXECUTE) ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator)); } return; } break; case NFSPROC_READ: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); } else { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes @ %u", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_WRITE: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64, EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[3])))); } } else { ND_TCHECK(dp[3]); ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)", EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_SYMLINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; if (parsefn(ndo, dp) == NULL) break; if (v3 && ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_MKNOD: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_TCHECK(*dp); type = (nfs_type)EXTRACT_32BITS(dp); dp++; if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type))); if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u/%u", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); dp += 2; } if (ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_RENAME: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_LINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_READDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); /* * We shouldn't really try to interpret the * offset cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3])); } else { ND_TCHECK(dp[1]); /* * Print the offset as signed, since -1 is * common, but offsets > 2^31 aren't. */ ND_PRINT((ndo, " %u bytes @ %d", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_READDIRPLUS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[4]); /* * We don't try to interpret the offset * cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_TCHECK(dp[5]); ND_PRINT((ndo, " max %u verf %08x%08x", EXTRACT_32BITS(&dp[5]), dp[2], dp[3])); } return; } break; case NFSPROC_COMMIT: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); return; } break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Print out an NFS file handle. * We assume packet was not truncated before the end of the * file handle pointed to by dp. * * Note: new version (using portable file-handle parser) doesn't produce * generation number. It probably could be made to do that, with some * additional hacking on the parser code. */ static void nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ char temp[NFSX_V3FHMAX+1]; u_int stringlen; /* Make sure string is null-terminated */ stringlen = len; if (stringlen > NFSX_V3FHMAX) stringlen = NFSX_V3FHMAX; strncpy(temp, sfsname, stringlen); temp[stringlen] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); } /* * Maintain a small cache of recent client.XID.server/proc pairs, to allow * us to match up replies with requests and thus to know how to parse * the reply. */ struct xid_map_entry { uint32_t xid; /* transaction ID (net order) */ int ipver; /* IP version (4 or 6) */ struct in6_addr client; /* client IP address (net order) */ struct in6_addr server; /* server IP address (net order) */ uint32_t proc; /* call proc number (host order) */ uint32_t vers; /* program version (host order) */ }; /* * Map entries are kept in an array that we manage as a ring; * new entries are always added at the tail of the ring. Initially, * all the entries are zero and hence don't match anything. */ #define XIDMAPSIZE 64 static struct xid_map_entry xid_map[XIDMAPSIZE]; static int xid_map_next = 0; static int xid_map_hint = 0; static int xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } /* * Returns 0 and puts NFSPROC_xxx in proc return and * version in vers return, or returns -1 on failure */ static int xid_map_find(const struct sunrpc_msg *rp, const u_char *bp, uint32_t *proc, uint32_t *vers) { int i; struct xid_map_entry *xmep; uint32_t xid; const struct ip *ip = (const struct ip *)bp; const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp; int cmp; UNALIGNED_MEMCPY(&xid, &rp->rm_xid, sizeof(xmep->xid)); /* Start searching from where we last left off */ i = xid_map_hint; do { xmep = &xid_map[i]; cmp = 1; if (xmep->ipver != IP_V(ip) || xmep->xid != xid) goto nextitem; switch (xmep->ipver) { case 4: if (UNALIGNED_MEMCMP(&ip->ip_src, &xmep->server, sizeof(ip->ip_src)) != 0 || UNALIGNED_MEMCMP(&ip->ip_dst, &xmep->client, sizeof(ip->ip_dst)) != 0) { cmp = 0; } break; case 6: if (UNALIGNED_MEMCMP(&ip6->ip6_src, &xmep->server, sizeof(ip6->ip6_src)) != 0 || UNALIGNED_MEMCMP(&ip6->ip6_dst, &xmep->client, sizeof(ip6->ip6_dst)) != 0) { cmp = 0; } break; default: cmp = 0; break; } if (cmp) { /* match */ xid_map_hint = i; *proc = xmep->proc; *vers = xmep->vers; return 0; } nextitem: if (++i >= XIDMAPSIZE) i = 0; } while (i != xid_map_hint); /* search failed */ return (-1); } /* * Routines for parsing reply packets */ /* * Return a pointer to the beginning of the actual results. * If the packet was truncated, return 0. */ static const uint32_t * parserep(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; u_int len; enum sunrpc_accept_stat astat; /* * Portability note: * Here we find the address of the ar_verf credentials. * Originally, this calculation was * dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf * On the wire, the rp_acpt field starts immediately after * the (32 bit) rp_stat field. However, rp_acpt (which is a * "struct accepted_reply") contains a "struct opaque_auth", * whose internal representation contains a pointer, so on a * 64-bit machine the compiler inserts 32 bits of padding * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use * the internal representation to parse the on-the-wire * representation. Instead, we skip past the rp_stat field, * which is an "enum" and so occupies one 32-bit word. */ dp = ((const uint32_t *)&rp->rm_reply) + 1; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len >= length) return (NULL); /* * skip past the ar_verf credentials. */ dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t); /* * now we can check the ar_stat field */ ND_TCHECK(dp[0]); astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp); if (astat != SUNRPC_SUCCESS) { ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat))); nfserr = 1; /* suppress trunc string */ return (NULL); } /* successful return */ ND_TCHECK2(*dp, sizeof(astat)); return ((const uint32_t *) (sizeof(astat) + ((const char *)dp))); trunc: return (0); } static const uint32_t * parsestatus(netdissect_options *ndo, const uint32_t *dp, int *er) { int errnum; ND_TCHECK(dp[0]); errnum = EXTRACT_32BITS(&dp[0]); if (er) *er = errnum; if (errnum != 0) { if (!ndo->ndo_qflag) ND_PRINT((ndo, " ERROR: %s", tok2str(status2str, "unk %d", errnum))); nfserr = 1; } return (dp + 1); trunc: return NULL; } static const uint32_t * parsefattr(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { const struct nfs_fattr *fap; fap = (const struct nfs_fattr *)dp; ND_TCHECK(fap->fa_gid); if (verbose) { ND_PRINT((ndo, " %s %o ids %d/%d", tok2str(type2str, "unk-ft %d ", EXTRACT_32BITS(&fap->fa_type)), EXTRACT_32BITS(&fap->fa_mode), EXTRACT_32BITS(&fap->fa_uid), EXTRACT_32BITS(&fap->fa_gid))); if (v3) { ND_TCHECK(fap->fa3_size); ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_size))); } else { ND_TCHECK(fap->fa2_size); ND_PRINT((ndo, " sz %d", EXTRACT_32BITS(&fap->fa2_size))); } } /* print lots more stuff */ if (verbose > 1) { if (v3) { ND_TCHECK(fap->fa3_ctime); ND_PRINT((ndo, " nlink %d rdev %d/%d", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa3_rdev.specdata1), EXTRACT_32BITS(&fap->fa3_rdev.specdata2))); ND_PRINT((ndo, " fsid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fsid))); ND_PRINT((ndo, " fileid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fileid))); ND_PRINT((ndo, " a/m/ctime %u.%06u", EXTRACT_32BITS(&fap->fa3_atime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_atime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_nsec))); } else { ND_TCHECK(fap->fa2_ctime); ND_PRINT((ndo, " nlink %d rdev 0x%x fsid 0x%x nodeid 0x%x a/m/ctime", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa2_rdev), EXTRACT_32BITS(&fap->fa2_fsid), EXTRACT_32BITS(&fap->fa2_fileid))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_atime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_atime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_usec))); } } return ((const uint32_t *)((const unsigned char *)dp + (v3 ? NFSX_V3FATTR : NFSX_V2FATTR))); trunc: return (NULL); } static int parseattrstat(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); return (parsefattr(ndo, dp, verbose, v3) != NULL); } static int parsediropres(netdissect_options *ndo, const uint32_t *dp) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) return (1); dp = parsefh(ndo, dp, 0); if (dp == NULL) return (0); return (parsefattr(ndo, dp, ndo->ndo_vflag, 0) != NULL); } static int parselinkres(netdissect_options *ndo, const uint32_t *dp, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return(0); if (er) return(1); if (v3 && !(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp) != NULL); } static int parsestatfs(netdissect_options *ndo, const uint32_t *dp, int v3) { const struct nfs_statfs *sfsp; int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (!v3 && er) return (1); if (ndo->ndo_qflag) return(1); if (v3) { if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); } ND_TCHECK2(*dp, (v3 ? NFSX_V3STATFS : NFSX_V2STATFS)); sfsp = (const struct nfs_statfs *)dp; if (v3) { ND_PRINT((ndo, " tbytes %" PRIu64 " fbytes %" PRIu64 " abytes %" PRIu64, EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_fbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_abytes))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " tfiles %" PRIu64 " ffiles %" PRIu64 " afiles %" PRIu64 " invar %u", EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tfiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_ffiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_afiles), EXTRACT_32BITS(&sfsp->sf_invarsec))); } } else { ND_PRINT((ndo, " tsize %d bsize %d blocks %d bfree %d bavail %d", EXTRACT_32BITS(&sfsp->sf_tsize), EXTRACT_32BITS(&sfsp->sf_bsize), EXTRACT_32BITS(&sfsp->sf_blocks), EXTRACT_32BITS(&sfsp->sf_bfree), EXTRACT_32BITS(&sfsp->sf_bavail))); } return (1); trunc: return (0); } static int parserddires(netdissect_options *ndo, const uint32_t *dp) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); if (ndo->ndo_qflag) return (1); ND_TCHECK(dp[2]); ND_PRINT((ndo, " offset 0x%x size %d ", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); if (dp[2] != 0) ND_PRINT((ndo, " eof")); return (1); trunc: return (0); } static const uint32_t * parse_wcc_attr(netdissect_options *ndo, const uint32_t *dp) { /* Our caller has already checked this */ ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0]))); ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u", EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5]))); return (dp + 6); } /* * Pre operation attributes. Print only if vflag > 1. */ static const uint32_t * parse_pre_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; ND_TCHECK2(*dp, 24); if (verbose > 1) { return parse_wcc_attr(ndo, dp); } else { /* If not verbose enough, just skip over wcc_attr */ return (dp + 6); } trunc: return (NULL); } /* * Post operation attributes are printed if vflag >= 1 */ static const uint32_t * parse_post_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (verbose) { return parsefattr(ndo, dp, verbose, 1); } else return (dp + (NFSX_V3FATTR / sizeof (uint32_t))); trunc: return (NULL); } static const uint32_t * parse_wcc_data(netdissect_options *ndo, const uint32_t *dp, int verbose) { if (verbose > 1) ND_PRINT((ndo, " PRE:")); if (!(dp = parse_pre_op_attr(ndo, dp, verbose))) return (0); if (verbose) ND_PRINT((ndo, " POST:")); return parse_post_op_attr(ndo, dp, verbose); } static const uint32_t * parsecreateopres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) dp = parse_wcc_data(ndo, dp, verbose); else { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (!(dp = parsefh(ndo, dp, 1))) return (0); if (verbose) { if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " dir attr:")); dp = parse_wcc_data(ndo, dp, verbose); } } } return (dp); trunc: return (NULL); } static int parsewccres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); return parse_wcc_data(ndo, dp, verbose) != NULL; } static const uint32_t * parsev3rddirres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (er) return dp; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " verf %08x%08x", dp[0], dp[1])); dp += 2; } return dp; trunc: return (NULL); } static int parsefsinfo(netdissect_options *ndo, const uint32_t *dp) { const struct nfsv3_fsinfo *sfp; int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); sfp = (const struct nfsv3_fsinfo *)dp; ND_TCHECK(*sfp); ND_PRINT((ndo, " rtmax %u rtpref %u wtmax %u wtpref %u dtpref %u", EXTRACT_32BITS(&sfp->fs_rtmax), EXTRACT_32BITS(&sfp->fs_rtpref), EXTRACT_32BITS(&sfp->fs_wtmax), EXTRACT_32BITS(&sfp->fs_wtpref), EXTRACT_32BITS(&sfp->fs_dtpref))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " rtmult %u wtmult %u maxfsz %" PRIu64, EXTRACT_32BITS(&sfp->fs_rtmult), EXTRACT_32BITS(&sfp->fs_wtmult), EXTRACT_64BITS((const uint32_t *)&sfp->fs_maxfilesize))); ND_PRINT((ndo, " delta %u.%06u ", EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_sec), EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_nsec))); } return (1); trunc: return (0); } static int parsepathconf(netdissect_options *ndo, const uint32_t *dp) { int er; const struct nfsv3_pathconf *spp; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); spp = (const struct nfsv3_pathconf *)dp; ND_TCHECK(*spp); ND_PRINT((ndo, " linkmax %u namemax %u %s %s %s %s", EXTRACT_32BITS(&spp->pc_linkmax), EXTRACT_32BITS(&spp->pc_namemax), EXTRACT_32BITS(&spp->pc_notrunc) ? "notrunc" : "", EXTRACT_32BITS(&spp->pc_chownrestricted) ? "chownres" : "", EXTRACT_32BITS(&spp->pc_caseinsensitive) ? "igncase" : "", EXTRACT_32BITS(&spp->pc_casepreserving) ? "keepcase" : "")); return (1); trunc: return (0); } static void interp_reply(netdissect_options *ndo, const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length) { register const uint32_t *dp; register int v3; int er; v3 = (vers == NFS_VER3); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: dp = parserep(ndo, rp, length); if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0) return; break; case NFSPROC_SETATTR: if (!(dp = parserep(ndo, rp, length))) return; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0) return; } break; case NFSPROC_LOOKUP: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (er) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } else { if (!(dp = parsefh(ndo, dp, v3))) break; if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) && ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } if (dp) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_ACCESS: if (!(dp = parserep(ndo, rp, length))) break; if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) ND_PRINT((ndo, " attr:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (!er) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0]))); } return; case NFSPROC_READLINK: dp = parserep(ndo, rp, length); if (dp != NULL && parselinkres(ndo, dp, v3) != 0) return; break; case NFSPROC_READ: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (EXTRACT_32BITS(&dp[1])) ND_PRINT((ndo, " EOF")); } return; } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0) return; } break; case NFSPROC_WRITE: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (ndo->ndo_vflag > 1) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[1])))); } return; } } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0) return; } break; case NFSPROC_CREATE: case NFSPROC_MKDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_SYMLINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_MKNOD: if (!(dp = parserep(ndo, rp, length))) break; if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; break; case NFSPROC_REMOVE: case NFSPROC_RMDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_RENAME: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " from:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " to:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; } return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_LINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " file POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " dir:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; return; } } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_READDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parserddires(ndo, dp) != 0) return; } break; case NFSPROC_READDIRPLUS: if (!(dp = parserep(ndo, rp, length))) break; if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; break; case NFSPROC_FSSTAT: dp = parserep(ndo, rp, length); if (dp != NULL && parsestatfs(ndo, dp, v3) != 0) return; break; case NFSPROC_FSINFO: dp = parserep(ndo, rp, length); if (dp != NULL && parsefsinfo(ndo, dp) != 0) return; break; case NFSPROC_PATHCONF: dp = parserep(ndo, rp, length); if (dp != NULL && parsepathconf(ndo, dp) != 0) return; break; case NFSPROC_COMMIT: dp = parserep(ndo, rp, length); if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0) return; break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2681_0
crossvul-cpp_data_bad_5241_5
404: Not Found
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5241_5
crossvul-cpp_data_good_628_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // dsdiff.c // This module is a helper to the WavPack command-line programs to support DFF files. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #ifdef _WIN32 #define strdup(x) _strdup(x) #endif #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; #pragma pack(push,2) typedef struct { char ckID [4]; int64_t ckDataSize; } DFFChunkHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char formType [4]; } DFFFileHeader; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t version; } DFFVersionChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t sampleRate; } DFFSampleRateChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint16_t numChannels; } DFFChannelsHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char compressionType [4]; } DFFCompressionHeader; #pragma pack(pop) #define DFFChunkHeaderFormat "4D" #define DFFFileHeaderFormat "4D4" #define DFFVersionChunkFormat "4DL" #define DFFSampleRateChunkFormat "4DL" #define DFFChannelsHeaderFormat "4DS" #define DFFCompressionHeaderFormat "4D4" int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteDsdiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { uint32_t chan_mask = WavpackGetChannelMask (wpc); int num_channels = WavpackGetNumChannels (wpc); DFFFileHeader file_header, prop_header; DFFChunkHeader data_header; DFFVersionChunk ver_chunk; DFFSampleRateChunk fs_chunk; DFFChannelsHeader chan_header; DFFCompressionHeader cmpr_header; char *cmpr_name = "\016not compressed", *chan_ids; int64_t file_size, prop_chunk_size, data_size; int cmpr_name_size, chan_ids_size; uint32_t bcount; if (debug_logging_mode) error_line ("WriteDsdiffHeader (), total samples = %lld, qmode = 0x%02x\n", (long long) total_samples, qmode); cmpr_name_size = (strlen (cmpr_name) + 1) & ~1; chan_ids_size = num_channels * 4; chan_ids = malloc (chan_ids_size); if (chan_ids) { uint32_t scan_mask = 0x1; char *cptr = chan_ids; int ci, uci = 0; for (ci = 0; ci < num_channels; ++ci) { while (scan_mask && !(scan_mask & chan_mask)) scan_mask <<= 1; if (scan_mask & 0x1) memcpy (cptr, num_channels <= 2 ? "SLFT" : "MLFT", 4); else if (scan_mask & 0x2) memcpy (cptr, num_channels <= 2 ? "SRGT" : "MRGT", 4); else if (scan_mask & 0x4) memcpy (cptr, "C ", 4); else if (scan_mask & 0x8) memcpy (cptr, "LFE ", 4); else if (scan_mask & 0x10) memcpy (cptr, "LS ", 4); else if (scan_mask & 0x20) memcpy (cptr, "RS ", 4); else { cptr [0] = 'C'; cptr [1] = (uci / 100) + '0'; cptr [2] = ((uci % 100) / 10) + '0'; cptr [3] = (uci % 10) + '0'; uci++; } scan_mask <<= 1; cptr += 4; } } else { error_line ("can't allocate memory!"); return FALSE; } data_size = total_samples * num_channels; prop_chunk_size = sizeof (prop_header) + sizeof (fs_chunk) + sizeof (chan_header) + chan_ids_size + sizeof (cmpr_header) + cmpr_name_size; file_size = sizeof (file_header) + sizeof (ver_chunk) + prop_chunk_size + sizeof (data_header) + ((data_size + 1) & ~(int64_t)1); memcpy (file_header.ckID, "FRM8", 4); file_header.ckDataSize = file_size - 12; memcpy (file_header.formType, "DSD ", 4); memcpy (prop_header.ckID, "PROP", 4); prop_header.ckDataSize = prop_chunk_size - 12; memcpy (prop_header.formType, "SND ", 4); memcpy (ver_chunk.ckID, "FVER", 4); ver_chunk.ckDataSize = sizeof (ver_chunk) - 12; ver_chunk.version = 0x01050000; memcpy (fs_chunk.ckID, "FS ", 4); fs_chunk.ckDataSize = sizeof (fs_chunk) - 12; fs_chunk.sampleRate = WavpackGetSampleRate (wpc) * 8; memcpy (chan_header.ckID, "CHNL", 4); chan_header.ckDataSize = sizeof (chan_header) + chan_ids_size - 12; chan_header.numChannels = num_channels; memcpy (cmpr_header.ckID, "CMPR", 4); cmpr_header.ckDataSize = sizeof (cmpr_header) + cmpr_name_size - 12; memcpy (cmpr_header.compressionType, "DSD ", 4); memcpy (data_header.ckID, "DSD ", 4); data_header.ckDataSize = data_size; WavpackNativeToBigEndian (&file_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&ver_chunk, DFFVersionChunkFormat); WavpackNativeToBigEndian (&prop_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&fs_chunk, DFFSampleRateChunkFormat); WavpackNativeToBigEndian (&chan_header, DFFChannelsHeaderFormat); WavpackNativeToBigEndian (&cmpr_header, DFFCompressionHeaderFormat); WavpackNativeToBigEndian (&data_header, DFFChunkHeaderFormat); if (!DoWriteFile (outfile, &file_header, sizeof (file_header), &bcount) || bcount != sizeof (file_header) || !DoWriteFile (outfile, &ver_chunk, sizeof (ver_chunk), &bcount) || bcount != sizeof (ver_chunk) || !DoWriteFile (outfile, &prop_header, sizeof (prop_header), &bcount) || bcount != sizeof (prop_header) || !DoWriteFile (outfile, &fs_chunk, sizeof (fs_chunk), &bcount) || bcount != sizeof (fs_chunk) || !DoWriteFile (outfile, &chan_header, sizeof (chan_header), &bcount) || bcount != sizeof (chan_header) || !DoWriteFile (outfile, chan_ids, chan_ids_size, &bcount) || bcount != chan_ids_size || !DoWriteFile (outfile, &cmpr_header, sizeof (cmpr_header), &bcount) || bcount != sizeof (cmpr_header) || !DoWriteFile (outfile, cmpr_name, cmpr_name_size, &bcount) || bcount != cmpr_name_size || !DoWriteFile (outfile, &data_header, sizeof (data_header), &bcount) || bcount != sizeof (data_header)) { error_line ("can't write .DSF data, disk probably full!"); free (chan_ids); return FALSE; } free (chan_ids); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_628_0
crossvul-cpp_data_good_149_0
/* radare - LGPL - Copyright 2010-2013 eloi<limited-entropy.com> */ #include <string.h> #include <r_types.h> #include <r_lib.h> #include <r_asm.h> #include <r_anal.h> #define API static #define LONG_SIZE 4 #define WORD_SIZE 2 #define BYTE_SIZE 1 /* missing opcodes : - FPU (opcodes 0xF___) - opcodes > SH2E - cmp* - "special" regs : PR, SR, VBR, GBR, MACL, MACH - T flag handling - 0x0___ - 0x2___ - 0x3___ ops : cmp*, div, dmul - 0x4___ ops : ld*, st* - 0x6___ implement (ext*, pop, swap, ...) - 0x8___ implement cmp/eq imm,Rn - 0xC___ implement {mova, T flag dest, (disp,GBR) src/dst} - 0xF___ FPU: everything *** complete : 0x1___ 0x5___ 0x7___ 0x9___ (XXX verify if @(disp,PC) works) 0xA___ 0xB___ 0xD___ 0xE___ */ //Macros for different instruction types #define IS_CLRT(x) x == 0x0008 #define IS_NOP(x) x == 0x0009 #define IS_RTS(x) x == 0x000b #define IS_SETT(x) x == 0x0018 #define IS_DIV0U(x) x == 0x0019 #define IS_SLEEP(x) x == 0x001b #define IS_CLRMAC(x) x == 0x0028 #define IS_RTE(x) x == 0x002b //#define IS_CLRS(x) #define IS_STCSR1(x) (((x) & 0xF0CF) == 0x0002) //mask stc Rn,{SR,GBR,VBR,SSR} #define IS_BSRF(x) (x & 0xf0ff) == 0x0003 #define IS_BRAF(x) (((x) & 0xf0ff) == 0x0023) #define IS_MOVB_REG_TO_R0REL(x) (((x) & 0xF00F) == 0x0004) #define IS_MOVW_REG_TO_R0REL(x) (((x) & 0xF00F) == 0x0005) #define IS_MOVL_REG_TO_R0REL(x) (((x) & 0xF00F) == 0x0006) #define IS_MULL(x) (((x) & 0xF00F) == 0x0007) #define IS_MOVB_R0REL_TO_REG(x) (((x) & 0xF00F) == 0x000C) #define IS_MOVW_R0REL_TO_REG(x) (((x) & 0xF00F) == 0x000D) #define IS_MOVL_R0REL_TO_REG(x) (((x) & 0xF00F) == 0x000E) //#define IS_MACL(x) (((x) & 0xF00F) == 0x000F) //complicated ! #define IS_MOVT(x) (((x) & 0xF0FF) == 0x0029) #define IS_STSMAC(x) (((x) & 0xF0EF) == 0x000A) //mask sts Rn, MAC* #define IS_STSPR(x) (((x) & 0xF0FF) == 0x002A) //#define IS_STSFPUL(x) (((x) & 0xF0FF) == 0x005A) //FP*: todo maybe someday //#define IS_STSFPSCR(x) (((x) & 0xF0FF) == 0x006A) #define IS_MOVB_REG_TO_REGREF(x) (((x) & 0xF00F) == 0x2000) #define IS_MOVW_REG_TO_REGREF(x) (((x) & 0xF00F) == 0x2001) #define IS_MOVL_REG_TO_REGREF(x) (((x) & 0xF00F) == 0x2002) //#define invalid?(x) (((x) & 0xF00F) == 0x2003) //illegal on sh2e #define IS_PUSHB(x) (((x) & 0xF00F) == 0x2004) #define IS_PUSHW(x) (((x) & 0xF00F) == 0x2005) #define IS_PUSHL(x) (((x) & 0xF00F) == 0x2006) #define IS_DIV0S(x) (((x) & 0xF00F) == 0x2007) #define IS_TSTRR(x) (((x) & 0xF00F) == 0x2008) #define IS_AND_REGS(x) (((x) & 0xF00F) == 0x2009) #define IS_XOR_REGS(x) (((x) & 0xF00F) == 0x200A) #define IS_OR_REGS(x) (((x) & 0xF00F) == 0x200B) #define IS_CMPSTR(x) (((x) & 0xF00F) == 0x200C) #define IS_XTRCT(x) (((x) & 0xF00F) == 0x200D) #define IS_MULUW(x) (((x) & 0xF00F) == 0x200E) #define IS_MULSW(x) (((x) & 0xF00F) == 0x200F) #define IS_CMPEQ(x) (((x) & 0xF00F) == 0x3000) //#define invalid?(x) (((x) & 0xF00F) == 0x3001) #define IS_CMPHS(x) (((x) & 0xF00F) == 0x3002) #define IS_CMPGE(x) (((x) & 0xF00F) == 0x3003) #define IS_CMPHI(x) (((x) & 0xF00F) == 0x3006) #define IS_CMPGT(x) (((x) & 0xF00F) == 0x3007) #define IS_DIV1(x) (((x) & 0xF00F) == 0x3004) #define IS_DMULU(x) (((x) & 0xF00F) == 0x3005) #define IS_DMULS(x) (((x) & 0xF00F) == 0x300D) #define IS_SUB(x) (((x) & 0xF00F) == 0x3008) //#define invalid?(x) (((x) & 0xF00F) == 0x3009) #define IS_SUBC(x) (((x) & 0xF00F) == 0x300A) #define IS_SUBV(x) (((x) & 0xF00F) == 0x300B) #define IS_ADD(x) (((x) & 0xF00F) == 0x300C) #define IS_ADDC(x) (((x) & 0xF00F) == 0x300E) #define IS_ADDV(x) (((x) & 0xF00F) == 0x300F) //#define IS_MACW(x) (((x) & 0xF00F) == 0x400F) //complex #define IS_JSR(x) (((x) & 0xf0ff) == 0x400b) #define IS_JMP(x) (((x) & 0xf0ff) == 0x402b) #define IS_CMPPL(x) (((x) & 0xf0ff) == 0x4015) #define IS_CMPPZ(x) (((x) & 0xf0ff) == 0x4011) #define IS_LDCSR1(x) (((x) & 0xF0CF) == 0x400E) //mask ldc Rn,{SR,GBR,VBR,SSR} #define IS_LDCLSR1(x) (((x) & 0xF0CF) == 0x4007) //mask ldc.l @Rn+,{SR,GBR,VBR,SSR} #define IS_LDSMAC(x) (((x) & 0xF0EF) == 0x400A) //mask lds Rn, MAC* #define IS_LDSLMAC(x) (((x) & 0xF0EF) == 0x4006) //mask lds.l @Rn+, MAC* #define IS_LDSPR(x) (((x) & 0xF0FF) == 0x402A) #define IS_LDSLPR(x) (((x) & 0xF0FF) == 0x4026) //#define IS_LDSFPUL(x) (((x) & 0xF0FF) == 0x405A) //FP*: todo maybe someday //#define IS_LDSFPSCR(x) (((x) & 0xF0FF) == 0x406A) //#define IS_LDSLFPUL(x) (((x) & 0xF0FF) == 0x4066) //#define IS_LDSLFPSCR(x) (((x) & 0xF0FF) == 0x4056) #define IS_ROT(x) (((x) & 0xF0DE) == 0x4004) //mask rot{,c}{l,r} //not on sh2e : shad, shld //#define IS_SHIFT1(x) (((x) & 0xF0DE) == 0x4000) //unused (treated as switch-case) //other shl{l,r}{,2,8,16} in switch case also. #define IS_STSLMAC(x) (((x) & 0xF0EF) == 0x4002) //mask sts.l mac*, @-Rn #define IS_STCLSR1(x) (((x) & 0xF0CF) == 0x4003) //mask stc.l {SR,GBR,VBR,SSR},@-Rn //todo: other stc.l not on sh2e #define IS_STSLPR(x) (((x) & 0xF0FF) == 0x4022) //#define IS_STSLFPUL(x) (((x) & 0xF0FF) == 0x4052) //#define IS_STSLFPSCR(x) (((x) & 0xF0FF) == 0x4062) #define IS_TASB(x) (((x) & 0xF0FF) == 0x401B) #define IS_DT(x) (((x) & 0xF0FF) == 0x4010) #define IS_MOVB_REGREF_TO_REG(x) (((x) & 0xF00F) == 0x6000) #define IS_MOVW_REGREF_TO_REG(x) (((x) & 0xF00F) == 0x6001) #define IS_MOVL_REGREF_TO_REG(x) (((x) & 0xF00F) == 0x6002) #define IS_MOV_REGS(x) (((x) & 0xf00f) == 0x6003) #define IS_MOVB_POP(x) (((x) & 0xF00F) == 0x6004) #define IS_MOVW_POP(x) (((x) & 0xF00F) == 0x6005) #define IS_MOVL_POP(x) (((x) & 0xF00F) == 0x6006) #define IS_NOT(x) (((x) & 0xF00F) == 0x6007) #define IS_SWAP(x) (((x) & 0xF00E) == 0x6008) //match swap.{b,w} #define IS_NEG(x) (((x) & 0xF00E) == 0x600A) //match neg{,c} #define IS_EXT(x) (((x) & 0xF00C) == 0x600C) //match ext{s,u}.{b,w} #define IS_MOVB_R0_REGDISP(x) (((x) & 0xFF00) == 0x8000) #define IS_MOVW_R0_REGDISP(x) (((x) & 0xFF00) == 0x8100) //#define illegal?(x) (((x) & 0xF900) == 0x8000) //match 8{2,3,6,7}00 #define IS_MOVB_REGDISP_R0(x) (((x) & 0xFF00) == 0x8400) #define IS_MOVW_REGDISP_R0(x) (((x) & 0xFF00) == 0x8500) #define IS_CMPIMM(x) (((x) & 0xFF00) == 0x8800) //#define illegal?(x) (((x) & 0xFB00) == 0x8A00) //match 8{A,E}00 #define IS_BT(x) (((x) & 0xff00) == 0x8900) #define IS_BF(x) (((x) & 0xff00) == 0x8B00) #define IS_BTS(x) (((x) & 0xff00) == 0x8D00) #define IS_BFS(x) (((x) & 0xff00) == 0x8F00) #define IS_BT_OR_BF(x) IS_BT(x)||IS_BTS(x)||IS_BF(x)||IS_BFS(x) #define IS_MOVB_R0_GBRREF(x) (((x) & 0xFF00) == 0xC000) #define IS_MOVW_R0_GBRREF(x) (((x) & 0xFF00) == 0xC100) #define IS_MOVL_R0_GBRREF(x) (((x) & 0xFF00) == 0xC200) #define IS_TRAP(x) (((x) & 0xFF00) == 0xC300) #define IS_MOVB_GBRREF_R0(x) (((x) & 0xFF00) == 0xC400) #define IS_MOVW_GBRREF_R0(x) (((x) & 0xFF00) == 0xC500) #define IS_MOVL_GBRREF_R0(x) (((x) & 0xFF00) == 0xC600) #define IS_MOVA_PCREL_R0(x) (((x) & 0xFF00) == 0xC700) #define IS_BINLOGIC_IMM_R0(x) (((x) & 0xFC00) == 0xC800) //match C{8,9,A,B}00 #define IS_BINLOGIC_IMM_GBR(x) (((x) & 0xFC00) == 0xCC00) //match C{C,D,E,F}00 : *.b #imm, @(R0,GBR) /* Compute PC-relative displacement for branch instructions */ #define GET_BRA_OFFSET(x) ((x) & 0x0fff) #define GET_BTF_OFFSET(x) ((x) & 0x00ff) /* Compute reg nr for BRAF,BSR,BSRF,JMP,JSR */ #define GET_TARGET_REG(x) ((x >> 8) & 0x0f) #define GET_SOURCE_REG(x) ((x >> 4) & 0x0f) /* index of PC reg in regs[] array*/ #define PC_IDX 16 /* for {bra,bsr} only: (sign-extend 12bit offset)<<1 + PC +4 */ static ut64 disarm_12bit_offset (RAnalOp *op, unsigned int insoff) { ut64 off = insoff; /* sign extend if higher bit is 1 (0x0800) */ if ((off & 0x0800) == 0x0800) { off |= ~0xFFF; } return (op->addr) + (off<<1) + 4; } /* for bt,bf sign-extended offsets : return PC+4+ (exts.b offset)<<1 */ static ut64 disarm_8bit_offset (ut64 pc, ut32 offs) { /* pc (really, op->addr) is 64 bits, so we need to sign-extend * to 64 bits instead of the 32 the actual CPU does */ ut64 off = offs; /* sign extend if higher bit is 1 (0x08) */ if ((off & 0x80) == 0x80) { off |= ~0xFF; } return (off<<1) + pc + 4; } static char *regs[]={"r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc"}; static RAnalValue *anal_fill_ai_rg(RAnal *anal, int idx) { RAnalValue *ret = r_anal_value_new (); ret->reg = r_reg_get (anal->reg, regs[idx], R_REG_TYPE_GPR); return ret; } static RAnalValue *anal_fill_im(RAnal *anal, st32 v) { RAnalValue *ret = r_anal_value_new (); ret->imm = v; return ret; } /* Implements @(disp,Rn) , size=1 for .b, 2 for .w, 4 for .l */ static RAnalValue *anal_fill_reg_disp_mem(RAnal *anal, int reg, st64 delta, st64 size) { RAnalValue *ret = anal_fill_ai_rg (anal, reg); ret->memref = size; ret->delta = delta*size; return ret; } /* Rn */ static RAnalValue *anal_fill_reg_ref(RAnal *anal, int reg, st64 size){ RAnalValue *ret = anal_fill_ai_rg (anal, reg); ret->memref = size; return ret; } /* @(R0,Rx) references for all sizes */ static RAnalValue *anal_fill_r0_reg_ref(RAnal *anal, int reg, st64 size){ RAnalValue *ret = anal_fill_ai_rg (anal, 0); ret->regdelta = r_reg_get (anal->reg, regs[reg], R_REG_TYPE_GPR); ret->memref = size; return ret; } // @(disp,PC) for size=2(.w), size=4(.l). disp is 0-extended static RAnalValue *anal_pcrel_disp_mov(RAnal* anal, RAnalOp* op, ut8 disp, int size){ RAnalValue *ret = r_anal_value_new (); if (size==2) { ret->base = op->addr+4; ret->delta = disp<<1; } else { ret->base = (op->addr+4) & ~0x03; ret->delta = disp<<2; } return ret; } //= PC+4+R<reg> static RAnalValue *anal_regrel_jump(RAnal* anal, RAnalOp* op, ut8 reg){ RAnalValue *ret = r_anal_value_new (); ret->reg = r_reg_get (anal->reg, regs[reg], R_REG_TYPE_GPR); ret->base = op->addr+4; return ret; } /* 16 decoder routines, based on 1st nibble value */ static int first_nibble_is_0(RAnal* anal, RAnalOp* op, ut16 code){ if(IS_BSRF(code)) { /* Call 'far' subroutine Rn+PC+4 */ op->type = R_ANAL_OP_TYPE_UCALL; op->delay = 1; op->dst = anal_regrel_jump (anal, op, GET_TARGET_REG(code)); } else if (IS_BRAF(code)) { /* Unconditional branch to Rn+PC+4, no delay slot */ op->type = R_ANAL_OP_TYPE_UJMP; op->dst = anal_regrel_jump (anal, op, GET_TARGET_REG(code)); op->eob = true; } else if( IS_RTS(code) ) { /* Ret from subroutine. Returns to pr */ //TODO Convert into jump pr? op->type = R_ANAL_OP_TYPE_RET; op->delay = 1; op->eob = true; } else if (IS_RTE(code)) { //TODO Convert into jmp spc? Indicate ssr->sr as well? op->type = R_ANAL_OP_TYPE_RET; op->delay = 1; op->eob = true; } else if (IS_MOVB_REG_TO_R0REL(code)) { //0000nnnnmmmm0100 mov.b <REG_M>,@(R0,<REG_N>) op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_r0_reg_ref (anal, GET_TARGET_REG(code), BYTE_SIZE); } else if (IS_MOVW_REG_TO_R0REL(code)) { op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_r0_reg_ref (anal, GET_TARGET_REG(code), WORD_SIZE); } else if (IS_MOVL_REG_TO_R0REL(code)) { op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_r0_reg_ref(anal, GET_TARGET_REG(code), LONG_SIZE); } else if (IS_MOVB_R0REL_TO_REG(code)) { op->type = R_ANAL_OP_TYPE_LOAD; op->src[0] = anal_fill_r0_reg_ref (anal, GET_SOURCE_REG(code), BYTE_SIZE); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_MOVW_R0REL_TO_REG(code)) { op->type = R_ANAL_OP_TYPE_LOAD; op->src[0] = anal_fill_r0_reg_ref (anal, GET_SOURCE_REG(code), WORD_SIZE); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_MOVL_R0REL_TO_REG(code)) { op->type = R_ANAL_OP_TYPE_LOAD; op->src[0] = anal_fill_r0_reg_ref (anal, GET_SOURCE_REG(code), LONG_SIZE); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_NOP(code)) { op->type = R_ANAL_OP_TYPE_NOP; } else if (IS_CLRT(code)) { op->type = R_ANAL_OP_TYPE_UNK; //TODO : implement flag } else if (IS_SETT(code)) { op->type = R_ANAL_OP_TYPE_UNK; } else if (IS_CLRMAC(code)) { op->type = R_ANAL_OP_TYPE_UNK; //TODO : type_mov ? } else if (IS_DIV0U(code)) { op->type = R_ANAL_OP_TYPE_DIV; } else if (IS_MOVT(code)) { op->type = R_ANAL_OP_TYPE_MOV; //op->src[0] = //TODO: figure out how to get T flag from sr reg op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_MULL(code)) { op->type = R_ANAL_OP_TYPE_MUL; op->src[0] = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->src[1] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); //op->dst = //TODO: figure out how to set MACL + MACH } else if (IS_SLEEP(code)) { op->type = R_ANAL_OP_TYPE_UNK; } else if (IS_STSMAC(code)) { //0000nnnn0000101_ sts MAC*,<REG_N> op->type = R_ANAL_OP_TYPE_MOV; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_STCSR1(code)) { //0000nnnn00010010 stc {sr,gbr,vbr,ssr},<REG_N> op->type = R_ANAL_OP_TYPE_MOV; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); //todo: plug in src } else if (IS_STSPR(code)) { //0000nnnn00101010 sts PR,<REG_N> op->type = R_ANAL_OP_TYPE_MOV; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); //todo: plug in src } //TODO Check missing insns, especially STC might be interesting return op->size; } //nibble=1; 0001nnnnmmmmi4*4 mov.l <REG_M>,@(<disp>,<REG_N>) static int movl_reg_rdisp(RAnal* anal, RAnalOp* op, ut16 code){ op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_reg_disp_mem (anal, GET_TARGET_REG(code), code&0x0F, LONG_SIZE); return op->size; } static int first_nibble_is_2(RAnal* anal, RAnalOp* op, ut16 code){ if (IS_MOVB_REG_TO_REGREF(code)) { // 0010nnnnmmmm0000 mov.b <REG_M>,@<REG_N> op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_reg_ref (anal, GET_TARGET_REG(code), BYTE_SIZE); } else if (IS_MOVW_REG_TO_REGREF(code)) { op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_reg_ref (anal, GET_TARGET_REG(code), WORD_SIZE); } else if (IS_MOVL_REG_TO_REGREF(code)) { op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_reg_ref (anal, GET_TARGET_REG(code), LONG_SIZE); } else if (IS_AND_REGS(code)) { op->type = R_ANAL_OP_TYPE_AND; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_XOR_REGS(code)) { op->type = R_ANAL_OP_TYPE_XOR; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_OR_REGS(code)) { op->type = R_ANAL_OP_TYPE_OR; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_PUSHB(code) || IS_PUSHW(code) || IS_PUSHL(code)) { op->type = R_ANAL_OP_TYPE_PUSH; //TODO Handle 'pushes' (mov Rm,@-Rn) } else if (IS_TSTRR(code)) { op->type = R_ANAL_OP_TYPE_ACMP; //TODO: handle tst reg,reg } else if (IS_CMPSTR(code)) { //0010nnnnmmmm1100 cmp/str <REG_M>,<REG_N> op->type = R_ANAL_OP_TYPE_ACMP; //maybe not? op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->src[1] = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); //todo: handle cmp/str byte-per-byte cmp? } else if (IS_XTRCT(code)) { //0010nnnnmmmm1101 xtrct <REG_M>,<REG_N> op->type = R_ANAL_OP_TYPE_MOV; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->src[1] = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); //todo: add details ? } else if (IS_DIV0S(code)) { op->type = R_ANAL_OP_TYPE_DIV; //todo: add details? } else if (IS_MULUW(code) || IS_MULSW(code)) { //0010nnnnmmmm111_ mul{s,u}.w <REG_M>,<REG_N> op->type = R_ANAL_OP_TYPE_MUL; op->src[0] = anal_fill_ai_rg(anal,GET_SOURCE_REG(code)); op->src[1] = anal_fill_ai_rg(anal,GET_TARGET_REG(code)); //todo: dest=MACL } return op->size; } static int first_nibble_is_3(RAnal* anal, RAnalOp* op, ut16 code){ //TODO Handle carry/overflow , CMP/xx? if( IS_ADD(code) || IS_ADDC(code) || IS_ADDV(code) ) { op->type = R_ANAL_OP_TYPE_ADD; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if ( IS_SUB(code) || IS_SUBC(code) || IS_SUBV(code)) { op->type = R_ANAL_OP_TYPE_SUB; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_CMPEQ(code) || IS_CMPGE(code) || IS_CMPGT(code) || IS_CMPHI(code) || IS_CMPHS(code)) { //TODO : finish implementing op->type = R_ANAL_OP_TYPE_CMP; op->src[0] = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->src[1] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); } else if (IS_DIV1(code)) { op->type = R_ANAL_OP_TYPE_DIV; op->src[0] = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->src[1] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); //todo: dest ? } else if (IS_DMULU(code) || IS_DMULS(code)) { op->type = R_ANAL_OP_TYPE_MUL; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->src[1] = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); //todo: dest=MACL,MACH } return op->size; } static int first_nibble_is_4(RAnal* anal, RAnalOp* op, ut16 code){ switch (code & 0xF0FF) { //todo: implement case 0x4020: //shal op->type = R_ANAL_OP_TYPE_SAL; break; case 0x4021: //shar op->type = R_ANAL_OP_TYPE_SAR; break; case 0x4000: //shll case 0x4008: //shll2 case 0x4018: //shll8 case 0x4028: //shll16 op->type = R_ANAL_OP_TYPE_SHL; break; case 0x4001: //shlr case 0x4009: //shlr2 case 0x4019: //shlr8 case 0x4029: //shlr16 op->type = R_ANAL_OP_TYPE_SHR; break; default: break; } if (IS_JSR(code)) { op->type = R_ANAL_OP_TYPE_UCALL; //call to reg op->delay = 1; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if ( IS_JMP(code) ) { op->type = R_ANAL_OP_TYPE_UJMP; //jmp to reg op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->delay = 1; op->eob = true; } else if (IS_CMPPL(code) || IS_CMPPZ(code)) { op->type = R_ANAL_OP_TYPE_CMP; //todo: implement } else if (IS_LDCLSR1(code) || IS_LDSLMAC(code) || IS_LDSLPR(code)) { op->type = R_ANAL_OP_TYPE_POP; //todo: implement } else if (IS_LDCSR1(code) || IS_LDSMAC(code) || IS_LDSPR(code)) { op->type = R_ANAL_OP_TYPE_MOV; //todo: implement } else if (IS_ROT(code)) { op->type = (code&1)? R_ANAL_OP_TYPE_ROR:R_ANAL_OP_TYPE_ROL; //todo: implement rot* vs rotc* } else if (IS_STCLSR1(code) || IS_STSLMAC(code) || IS_STSLPR(code)) { op->type = R_ANAL_OP_TYPE_PUSH; //todo: implement st*.l *,@-Rn } else if (IS_TASB(code)) { op->type = R_ANAL_OP_TYPE_UNK; //todo: implement } else if (IS_DT(code)) { op->type = R_ANAL_OP_TYPE_UNK; //todo: implement } return op->size; } //nibble=5; 0101nnnnmmmmi4*4 mov.l @(<disp>,<REG_M>),<REG_N> static int movl_rdisp_reg(RAnal* anal, RAnalOp* op, ut16 code){ op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->src[0] = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, LONG_SIZE); return op->size; } static int first_nibble_is_6(RAnal* anal, RAnalOp* op, ut16 code){ if (IS_MOV_REGS(code)) { op->type = R_ANAL_OP_TYPE_MOV; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_MOVB_REGREF_TO_REG(code)) { op->type = R_ANAL_OP_TYPE_LOAD; op->src[0] = anal_fill_reg_ref (anal, GET_SOURCE_REG(code), BYTE_SIZE); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_MOVW_REGREF_TO_REG(code)) { op->type = R_ANAL_OP_TYPE_LOAD; op->src[0] = anal_fill_reg_ref (anal, GET_SOURCE_REG(code), WORD_SIZE); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_MOVL_REGREF_TO_REG(code)) { op->type = R_ANAL_OP_TYPE_LOAD; op->src[0] = anal_fill_reg_ref (anal, GET_SOURCE_REG(code), LONG_SIZE); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_EXT(code)) { //ext{s,u}.{b,w} instructs. todo : more detail ? op->type = R_ANAL_OP_TYPE_MOV; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_MOVB_POP(code) || IS_MOVW_POP(code) || IS_MOVL_POP(code)) { /* 0110nnnnmmmm0100 mov.b @<REG_M>+,<REG_N>*/ /* 0110nnnnmmmm0101 mov.w @<REG_M>+,<REG_N>*/ /* 0110nnnnmmmm0110 mov.l @<REG_M>+,<REG_N>*/ op->type = R_ANAL_OP_TYPE_POP; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); //todo : op->src for pop = ? } else if (IS_NEG(code)) { //todo: neg and negc details op->type = R_ANAL_OP_TYPE_UNK; /* 0110nnnnmmmm1010 negc*/ /* 0110nnnnmmmm1010 neg */ op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_NOT(code)) { //todo : details? op->type = R_ANAL_OP_TYPE_NOT; op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code)); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); } else if (IS_SWAP(code)) { /* 0110nnnnmmmm1000 swap.b <REG_M>,<REG_N>*/ /* 0110nnnnmmmm1001 swap.w <REG_M>,<REG_N>*/ op->type = R_ANAL_OP_TYPE_MOV; //todo : details } return op->size; } //nibble=7; 0111nnnni8*1.... add #<imm>,<REG_N> static int add_imm(RAnal* anal, RAnalOp* op, ut16 code){ op->type = R_ANAL_OP_TYPE_ADD; op->src[0] = anal_fill_im (anal, (st8)(code&0xFF)); //Casting to (st8) forces sign-extension. op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); return op->size; } static int first_nibble_is_8(RAnal* anal, RAnalOp* op, ut16 code){ if (IS_BT_OR_BF(code)) { op->type = R_ANAL_OP_TYPE_CJMP; //Jump if true or jump if false insns op->jump = disarm_8bit_offset (op->addr, GET_BTF_OFFSET(code)); op->fail = op->addr + 2 ; op->eob = true; if (IS_BTS(code) || IS_BFS(code)) op->delay = 1; //Only /S versions have a delay slot } else if (IS_MOVB_REGDISP_R0(code)) { // 10000100mmmmi4*1 mov.b @(<disp>,<REG_M>),R0 op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, 0); op->src[0] = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, BYTE_SIZE); } else if (IS_MOVW_REGDISP_R0(code)) { // 10000101mmmmi4*2 mov.w @(<disp>,<REG_M>),R0 op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, 0); op->src[0] = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, WORD_SIZE); } else if (IS_CMPIMM(code)) { op->type = R_ANAL_OP_TYPE_CMP; //todo : finish implementing } else if (IS_MOVB_R0_REGDISP(code)) { /* 10000000mmmmi4*1 mov.b R0,@(<disp>,<REG_M>)*/ op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, 0); op->dst = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, BYTE_SIZE); } else if (IS_MOVW_R0_REGDISP(code)) { // 10000001mmmmi4*2 mov.w R0,@(<disp>,<REG_M>)) op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, 0); op->dst = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, WORD_SIZE); } return op->size; } //nibble=9; 1001nnnni8p2.... mov.w @(<disp>,PC),<REG_N> static int movw_pcdisp_reg(RAnal* anal, RAnalOp* op, ut16 code){ op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); //op->src[0] = anal_fill_reg_disp_mem(anal,PC_IDX,code&0xFF,WORD_SIZE); //XXX trash in 2 commits op->src[0] = anal_pcrel_disp_mov (anal, op, code&0xFF, WORD_SIZE); return op->size; } //nibble=A; 1010i12......... bra <bdisp12> static int bra(RAnal* anal, RAnalOp* op, ut16 code){ /* Unconditional branch, relative to PC */ op->type = R_ANAL_OP_TYPE_JMP; op->delay = 1; op->jump = disarm_12bit_offset (op, GET_BRA_OFFSET(code)); op->eob = true; return op->size; } //nibble=B; 1011i12......... bsr <bdisp12> static int bsr(RAnal* anal, RAnalOp* op, ut16 code){ /* Subroutine call, relative to PC */ op->type = R_ANAL_OP_TYPE_CALL; op->jump = disarm_12bit_offset (op, GET_BRA_OFFSET(code)); op->delay = 1; return op->size; } static int first_nibble_is_c(RAnal* anal, RAnalOp* op, ut16 code){ if (IS_TRAP(code)) { op->type = R_ANAL_OP_TYPE_SWI; op->val = (ut8)(code&0xFF); } else if (IS_MOVA_PCREL_R0(code)) { // 11000111i8p4.... mova @(<disp>,PC),R0 op->type = R_ANAL_OP_TYPE_LEA; op->src[0] = anal_pcrel_disp_mov (anal, op, code&0xFF, LONG_SIZE); //this is wrong ! op->dst = anal_fill_ai_rg (anal, 0); //Always R0 } else if (IS_BINLOGIC_IMM_R0(code)) { // 110010__i8 (binop) #imm, R0 op->src[0] = anal_fill_im (anal, code&0xFF); op->src[1] = anal_fill_ai_rg (anal, 0); //Always R0 op->dst = anal_fill_ai_rg (anal, 0); //Always R0 except tst #imm, R0 switch (code & 0xFF00) { case 0xC800: //tst //TODO : get correct op->dst ! (T flag) op->type = R_ANAL_OP_TYPE_ACMP; break; case 0xC900: //and op->type = R_ANAL_OP_TYPE_AND; break; case 0xCA00: //xor op->type = R_ANAL_OP_TYPE_XOR; break; case 0xCB00: //or op->type = R_ANAL_OP_TYPE_OR; break; } } else if (IS_BINLOGIC_IMM_GBR(code)) { //110011__i8 (binop).b #imm, @(R0,GBR) op->src[0] = anal_fill_im (anal, code&0xFF); switch (code & 0xFF00) { case 0xCC00: //tst //TODO : get correct op->dst ! (T flag) op->type = R_ANAL_OP_TYPE_ACMP; break; case 0xCD00: //and op->type = R_ANAL_OP_TYPE_AND; break; case 0xCE00: //xor op->type = R_ANAL_OP_TYPE_XOR; break; case 0xCF00: //or op->type = R_ANAL_OP_TYPE_OR; break; } //TODO : implement @(R0,GBR) dest and src[1] } else if (IS_MOVB_R0_GBRREF(code)) { //11000000i8*1.... mov.b R0,@(<disp>,GBR) op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, 0); //todo: implement @(disp,GBR) dest } else if (IS_MOVW_R0_GBRREF(code)) { //11000001i8*2.... mov.w R0,@(<disp>,GBR) op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, 0); //todo: implement @(disp,GBR) dest } else if (IS_MOVL_R0_GBRREF(code)) { //11000010i8*4.... mov.l R0,@(<disp>,GBR) op->type = R_ANAL_OP_TYPE_STORE; op->src[0] = anal_fill_ai_rg (anal, 0); //todo: implement @(disp,GBR) dest } else if (IS_MOVB_GBRREF_R0(code)) { //11000100i8*1.... mov.b @(<disp>,GBR),R0 op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, 0); //todo: implement @(disp,GBR) src } else if (IS_MOVW_GBRREF_R0(code)) { //11000101i8*2.... mov.w @(<disp>,GBR),R0 op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, 0); //todo: implement @(disp,GBR) src } else if (IS_MOVL_GBRREF_R0(code)) { //11000110i8*4.... mov.l @(<disp>,GBR),R0 op->type = R_ANAL_OP_TYPE_LOAD; op->dst = anal_fill_ai_rg (anal, 0); //todo: implement @(disp,GBR) src } return op->size; } //nibble=d; 1101nnnni8 : mov.l @(<disp>,PC), Rn static int movl_pcdisp_reg(RAnal* anal, RAnalOp* op, ut16 code){ op->type = R_ANAL_OP_TYPE_LOAD; op->src[0] = anal_pcrel_disp_mov (anal, op, code&0xFF, LONG_SIZE); op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); return op->size; } //nibble=e; 1110nnnni8*1.... mov #<imm>,<REG_N> static int mov_imm_reg(RAnal* anal, RAnalOp* op, ut16 code){ op->type = R_ANAL_OP_TYPE_MOV; op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code)); op->src[0] = anal_fill_im (anal, (st8)(code & 0xFF)); return op->size; } //nibble=f; static int fpu_insn(RAnal* anal, RAnalOp* op, ut16 code){ //Not interested on FPU stuff for now op->family = R_ANAL_OP_FAMILY_FPU; return op->size; } /* Table of routines for further analysis based on 1st nibble */ static int (*first_nibble_decode[])(RAnal*,RAnalOp*,ut16) = { first_nibble_is_0, movl_reg_rdisp, first_nibble_is_2, first_nibble_is_3, first_nibble_is_4, movl_rdisp_reg, first_nibble_is_6, add_imm, first_nibble_is_8, movw_pcdisp_reg, bra, bsr, first_nibble_is_c, movl_pcdisp_reg, mov_imm_reg, fpu_insn }; /* This is the basic operation analysis. Just initialize and jump to * routines defined in first_nibble_decode table */ static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_MSB,op_LSB; int ret; if (!data || len < 2) { return 0; } memset (op, '\0', sizeof (RAnalOp)); op->addr = addr; op->type = R_ANAL_OP_TYPE_UNK; op->jump = op->fail = -1; op->ptr = op->val = -1; op->size = 2; op_MSB = anal->big_endian? data[0]: data[1]; op_LSB = anal->big_endian? data[1]: data[0]; ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB)); return ret; } /* Set the profile register */ static int sh_set_reg_profile(RAnal* anal){ //TODO Add system ( ssr, spc ) + fpu regs const char *p = "=PC pc\n" "=SP r15\n" "=BP r14\n" "gpr r0 .32 0 0\n" "gpr r1 .32 4 0\n" "gpr r2 .32 8 0\n" "gpr r3 .32 12 0\n" "gpr r4 .32 16 0\n" "gpr r5 .32 20 0\n" "gpr r6 .32 24 0\n" "gpr r7 .32 28 0\n" "gpr r8 .32 32 0\n" "gpr r9 .32 36 0\n" "gpr r10 .32 40 0\n" "gpr r11 .32 44 0\n" "gpr r12 .32 48 0\n" "gpr r13 .32 52 0\n" "gpr r14 .32 56 0\n" "gpr r15 .32 60 0\n" "gpr pc .32 64 0\n" "gpr pr .32 68 0\n" "gpr sr .32 72 0\n" "gpr gbr .32 76 0\n" "gpr mach .32 80 0\n" "gpr macl .32 84 0\n"; return r_reg_set_profile_string(anal->reg, p); } static int archinfo(RAnal *anal, int q) { return 2; /* :) */ } RAnalPlugin r_anal_plugin_sh = { .name = "sh", .desc = "SH-4 code analysis plugin", .license = "LGPL3", .arch = "sh", .archinfo = archinfo, .bits = 32, .op = &sh_op, .set_reg_profile = &sh_set_reg_profile, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_ANAL, .data = &r_anal_plugin_sh, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_149_0
crossvul-cpp_data_good_2639_0
/* * Copyright (C) Andrew Tridgell 1995-1999 * * This software may be distributed either under the terms of the * BSD-style license that accompanies tcpdump or the GNU GPL version 2 * or later */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "netdissect.h" #include "extract.h" #include "smb.h" static uint32_t stringlen; extern const u_char *startbuf; /* * interpret a 32 bit dos packed date/time to some parameters */ static void interpret_dos_date(uint32_t date, struct tm *tp) { uint32_t p0, p1, p2, p3; p0 = date & 0xFF; p1 = ((date & 0xFF00) >> 8) & 0xFF; p2 = ((date & 0xFF0000) >> 16) & 0xFF; p3 = ((date & 0xFF000000) >> 24) & 0xFF; tp->tm_sec = 2 * (p0 & 0x1F); tp->tm_min = ((p0 >> 5) & 0xFF) + ((p1 & 0x7) << 3); tp->tm_hour = (p1 >> 3) & 0xFF; tp->tm_mday = (p2 & 0x1F); tp->tm_mon = ((p2 >> 5) & 0xFF) + ((p3 & 0x1) << 3) - 1; tp->tm_year = ((p3 >> 1) & 0xFF) + 80; } /* * common portion: * create a unix date from a dos date */ static time_t int_unix_date(uint32_t dos_date) { struct tm t; if (dos_date == 0) return(0); interpret_dos_date(dos_date, &t); t.tm_wday = 1; t.tm_yday = 1; t.tm_isdst = 0; return (mktime(&t)); } /* * create a unix date from a dos date * in network byte order */ static time_t make_unix_date(const u_char *date_ptr) { uint32_t dos_date = 0; dos_date = EXTRACT_LE_32BITS(date_ptr); return int_unix_date(dos_date); } /* * create a unix date from a dos date * in halfword-swapped network byte order! */ static time_t make_unix_date2(const u_char *date_ptr) { uint32_t x, x2; x = EXTRACT_LE_32BITS(date_ptr); x2 = ((x & 0xFFFF) << 16) | ((x & 0xFFFF0000) >> 16); return int_unix_date(x2); } /* * interpret an 8 byte "filetime" structure to a time_t * It's originally in "100ns units since jan 1st 1601" */ static time_t interpret_long_date(const u_char *p) { double d; time_t ret; /* this gives us seconds since jan 1st 1601 (approx) */ d = (EXTRACT_LE_32BITS(p + 4) * 256.0 + p[3]) * (1.0e-7 * (1 << 24)); /* now adjust by 369 years to make the secs since 1970 */ d -= 369.0 * 365.25 * 24 * 60 * 60; /* and a fudge factor as we got it wrong by a few days */ d += (3 * 24 * 60 * 60 + 6 * 60 * 60 + 2); if (d < 0) return(0); ret = (time_t)d; return(ret); } /* * interpret the weird netbios "name". Return the name type, or -1 if * we run past the end of the buffer */ static int name_interpret(netdissect_options *ndo, const u_char *in, const u_char *maxbuf, char *out) { int ret; int len; if (in >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*in, 1); len = (*in++) / 2; *out=0; if (len > 30 || len < 1) return(0); while (len--) { ND_TCHECK2(*in, 2); if (in + 1 >= maxbuf) return(-1); /* name goes past the end of the buffer */ if (in[0] < 'A' || in[0] > 'P' || in[1] < 'A' || in[1] > 'P') { *out = 0; return(0); } *out = ((in[0] - 'A') << 4) + (in[1] - 'A'); in += 2; out++; } *out = 0; ret = out[-1]; return(ret); trunc: return(-1); } /* * find a pointer to a netbios name */ static const u_char * name_ptr(netdissect_options *ndo, const u_char *buf, int ofs, const u_char *maxbuf) { const u_char *p; u_char c; p = buf + ofs; if (p >= maxbuf) return(NULL); /* name goes past the end of the buffer */ ND_TCHECK2(*p, 1); c = *p; /* XXX - this should use the same code that the DNS dissector does */ if ((c & 0xC0) == 0xC0) { uint16_t l; ND_TCHECK2(*p, 2); if ((p + 1) >= maxbuf) return(NULL); /* name goes past the end of the buffer */ l = EXTRACT_16BITS(p) & 0x3FFF; if (l == 0) { /* We have a pointer that points to itself. */ return(NULL); } p = buf + l; if (p >= maxbuf) return(NULL); /* name goes past the end of the buffer */ ND_TCHECK2(*p, 1); } return(p); trunc: return(NULL); /* name goes past the end of the buffer */ } /* * extract a netbios name from a buf */ static int name_extract(netdissect_options *ndo, const u_char *buf, int ofs, const u_char *maxbuf, char *name) { const u_char *p = name_ptr(ndo, buf, ofs, maxbuf); if (p == NULL) return(-1); /* error (probably name going past end of buffer) */ name[0] = '\0'; return(name_interpret(ndo, p, maxbuf, name)); } /* * return the total storage length of a mangled name */ static int name_len(netdissect_options *ndo, const unsigned char *s, const unsigned char *maxbuf) { const unsigned char *s0 = s; unsigned char c; if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); c = *s; if ((c & 0xC0) == 0xC0) return(2); while (*s) { if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); s += (*s) + 1; ND_TCHECK2(*s, 1); } return(PTR_DIFF(s, s0) + 1); trunc: return(-1); /* name goes past the end of the buffer */ } static void print_asc(netdissect_options *ndo, const unsigned char *buf, int len) { int i; for (i = 0; i < len; i++) safeputchar(ndo, buf[i]); } static const char * name_type_str(int name_type) { const char *f = NULL; switch (name_type) { case 0: f = "Workstation"; break; case 0x03: f = "Client?"; break; case 0x20: f = "Server"; break; case 0x1d: f = "Master Browser"; break; case 0x1b: f = "Domain Controller"; break; case 0x1e: f = "Browser Server"; break; default: f = "Unknown"; break; } return(f); } void smb_print_data(netdissect_options *ndo, const unsigned char *buf, int len) { int i = 0; if (len <= 0) return; ND_PRINT((ndo, "[%03X] ", i)); for (i = 0; i < len; /*nothing*/) { ND_TCHECK(buf[i]); ND_PRINT((ndo, "%02X ", buf[i] & 0xff)); i++; if (i%8 == 0) ND_PRINT((ndo, " ")); if (i % 16 == 0) { print_asc(ndo, &buf[i - 16], 8); ND_PRINT((ndo, " ")); print_asc(ndo, &buf[i - 8], 8); ND_PRINT((ndo, "\n")); if (i < len) ND_PRINT((ndo, "[%03X] ", i)); } } if (i % 16) { int n; n = 16 - (i % 16); ND_PRINT((ndo, " ")); if (n>8) ND_PRINT((ndo, " ")); while (n--) ND_PRINT((ndo, " ")); n = min(8, i % 16); print_asc(ndo, &buf[i - (i % 16)], n); ND_PRINT((ndo, " ")); n = (i % 16) - n; if (n > 0) print_asc(ndo, &buf[i - n], n); ND_PRINT((ndo, "\n")); } return; trunc: ND_PRINT((ndo, "\n")); ND_PRINT((ndo, "WARNING: Short packet. Try increasing the snap length\n")); } static void write_bits(netdissect_options *ndo, unsigned int val, const char *fmt) { const char *p = fmt; int i = 0; while ((p = strchr(fmt, '|'))) { size_t l = PTR_DIFF(p, fmt); if (l && (val & (1 << i))) ND_PRINT((ndo, "%.*s ", (int)l, fmt)); fmt = p + 1; i++; } } /* convert a UCS-2 string into an ASCII string */ #define MAX_UNISTR_SIZE 1000 static const char * unistr(netdissect_options *ndo, const u_char *s, uint32_t *len, int use_unicode) { static char buf[MAX_UNISTR_SIZE+1]; size_t l = 0; uint32_t strsize; const u_char *sp; if (use_unicode) { /* * Skip padding that puts the string on an even boundary. */ if (((s - startbuf) % 2) != 0) { ND_TCHECK(s[0]); s++; } } if (*len == 0) { /* * Null-terminated string. */ strsize = 0; sp = s; if (!use_unicode) { for (;;) { ND_TCHECK(sp[0]); *len += 1; if (sp[0] == 0) break; sp++; } strsize = *len - 1; } else { for (;;) { ND_TCHECK2(sp[0], 2); *len += 2; if (sp[0] == 0 && sp[1] == 0) break; sp += 2; } strsize = *len - 2; } } else { /* * Counted string. */ strsize = *len; } if (!use_unicode) { while (strsize != 0) { ND_TCHECK(s[0]); if (l >= MAX_UNISTR_SIZE) break; if (ND_ISPRINT(s[0])) buf[l] = s[0]; else { if (s[0] == 0) break; buf[l] = '.'; } l++; s++; strsize--; } } else { while (strsize != 0) { ND_TCHECK2(s[0], 2); if (l >= MAX_UNISTR_SIZE) break; if (s[1] == 0 && ND_ISPRINT(s[0])) { /* It's a printable ASCII character */ buf[l] = s[0]; } else { /* It's a non-ASCII character or a non-printable ASCII character */ if (s[0] == 0 && s[1] == 0) break; buf[l] = '.'; } l++; s += 2; if (strsize == 1) break; strsize -= 2; } } buf[l] = 0; return buf; trunc: return NULL; } static const u_char * smb_fdata1(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { int reverse = 0; const char *attrib_fmt = "READONLY|HIDDEN|SYSTEM|VOLUME|DIR|ARCHIVE|"; while (*fmt && buf<maxbuf) { switch (*fmt) { case 'a': ND_TCHECK(buf[0]); write_bits(ndo, buf[0], attrib_fmt); buf++; fmt++; break; case 'A': ND_TCHECK2(buf[0], 2); write_bits(ndo, EXTRACT_LE_16BITS(buf), attrib_fmt); buf += 2; fmt++; break; case '{': { char bitfmt[128]; char *p; int l; p = strchr(++fmt, '}'); l = PTR_DIFF(p, fmt); if ((unsigned int)l > sizeof(bitfmt) - 1) l = sizeof(bitfmt)-1; strncpy(bitfmt, fmt, l); bitfmt[l] = '\0'; fmt = p + 1; ND_TCHECK(buf[0]); write_bits(ndo, buf[0], bitfmt); buf++; break; } case 'P': { int l = atoi(fmt + 1); ND_TCHECK2(buf[0], l); buf += l; fmt++; while (isdigit((unsigned char)*fmt)) fmt++; break; } case 'r': reverse = !reverse; fmt++; break; case 'b': { unsigned int x; ND_TCHECK(buf[0]); x = buf[0]; ND_PRINT((ndo, "%u (0x%x)", x, x)); buf += 1; fmt++; break; } case 'd': { unsigned int x; ND_TCHECK2(buf[0], 2); x = reverse ? EXTRACT_16BITS(buf) : EXTRACT_LE_16BITS(buf); ND_PRINT((ndo, "%d (0x%x)", x, x)); buf += 2; fmt++; break; } case 'D': { unsigned int x; ND_TCHECK2(buf[0], 4); x = reverse ? EXTRACT_32BITS(buf) : EXTRACT_LE_32BITS(buf); ND_PRINT((ndo, "%d (0x%x)", x, x)); buf += 4; fmt++; break; } case 'L': { uint64_t x; ND_TCHECK2(buf[0], 8); x = reverse ? EXTRACT_64BITS(buf) : EXTRACT_LE_64BITS(buf); ND_PRINT((ndo, "%" PRIu64 " (0x%" PRIx64 ")", x, x)); buf += 8; fmt++; break; } case 'M': { /* Weird mixed-endian length values in 64-bit locks */ uint32_t x1, x2; uint64_t x; ND_TCHECK2(buf[0], 8); x1 = reverse ? EXTRACT_32BITS(buf) : EXTRACT_LE_32BITS(buf); x2 = reverse ? EXTRACT_32BITS(buf + 4) : EXTRACT_LE_32BITS(buf + 4); x = (((uint64_t)x1) << 32) | x2; ND_PRINT((ndo, "%" PRIu64 " (0x%" PRIx64 ")", x, x)); buf += 8; fmt++; break; } case 'B': { unsigned int x; ND_TCHECK(buf[0]); x = buf[0]; ND_PRINT((ndo, "0x%X", x)); buf += 1; fmt++; break; } case 'w': { unsigned int x; ND_TCHECK2(buf[0], 2); x = reverse ? EXTRACT_16BITS(buf) : EXTRACT_LE_16BITS(buf); ND_PRINT((ndo, "0x%X", x)); buf += 2; fmt++; break; } case 'W': { unsigned int x; ND_TCHECK2(buf[0], 4); x = reverse ? EXTRACT_32BITS(buf) : EXTRACT_LE_32BITS(buf); ND_PRINT((ndo, "0x%X", x)); buf += 4; fmt++; break; } case 'l': { fmt++; switch (*fmt) { case 'b': ND_TCHECK(buf[0]); stringlen = buf[0]; ND_PRINT((ndo, "%u", stringlen)); buf += 1; break; case 'd': ND_TCHECK2(buf[0], 2); stringlen = reverse ? EXTRACT_16BITS(buf) : EXTRACT_LE_16BITS(buf); ND_PRINT((ndo, "%u", stringlen)); buf += 2; break; case 'D': ND_TCHECK2(buf[0], 4); stringlen = reverse ? EXTRACT_32BITS(buf) : EXTRACT_LE_32BITS(buf); ND_PRINT((ndo, "%u", stringlen)); buf += 4; break; } fmt++; break; } case 'S': case 'R': /* like 'S', but always ASCII */ { /*XXX unistr() */ const char *s; uint32_t len; len = 0; s = unistr(ndo, buf, &len, (*fmt == 'R') ? 0 : unicodestr); if (s == NULL) goto trunc; ND_PRINT((ndo, "%s", s)); buf += len; fmt++; break; } case 'Z': case 'Y': /* like 'Z', but always ASCII */ { const char *s; uint32_t len; ND_TCHECK(*buf); if (*buf != 4 && *buf != 2) { ND_PRINT((ndo, "Error! ASCIIZ buffer of type %u", *buf)); return maxbuf; /* give up */ } len = 0; s = unistr(ndo, buf + 1, &len, (*fmt == 'Y') ? 0 : unicodestr); if (s == NULL) goto trunc; ND_PRINT((ndo, "%s", s)); buf += len + 1; fmt++; break; } case 's': { int l = atoi(fmt + 1); ND_TCHECK2(*buf, l); ND_PRINT((ndo, "%-*.*s", l, l, buf)); buf += l; fmt++; while (isdigit((unsigned char)*fmt)) fmt++; break; } case 'c': { ND_TCHECK2(*buf, stringlen); ND_PRINT((ndo, "%-*.*s", (int)stringlen, (int)stringlen, buf)); buf += stringlen; fmt++; while (isdigit((unsigned char)*fmt)) fmt++; break; } case 'C': { const char *s; s = unistr(ndo, buf, &stringlen, unicodestr); if (s == NULL) goto trunc; ND_PRINT((ndo, "%s", s)); buf += stringlen; fmt++; break; } case 'h': { int l = atoi(fmt + 1); ND_TCHECK2(*buf, l); while (l--) ND_PRINT((ndo, "%02x", *buf++)); fmt++; while (isdigit((unsigned char)*fmt)) fmt++; break; } case 'n': { int t = atoi(fmt+1); char nbuf[255]; int name_type; int len; switch (t) { case 1: name_type = name_extract(ndo, startbuf, PTR_DIFF(buf, startbuf), maxbuf, nbuf); if (name_type < 0) goto trunc; len = name_len(ndo, buf, maxbuf); if (len < 0) goto trunc; buf += len; ND_PRINT((ndo, "%-15.15s NameType=0x%02X (%s)", nbuf, name_type, name_type_str(name_type))); break; case 2: ND_TCHECK(buf[15]); name_type = buf[15]; ND_PRINT((ndo, "%-15.15s NameType=0x%02X (%s)", buf, name_type, name_type_str(name_type))); buf += 16; break; } fmt++; while (isdigit((unsigned char)*fmt)) fmt++; break; } case 'T': { time_t t; struct tm *lt; const char *tstring; uint32_t x; switch (atoi(fmt + 1)) { case 1: ND_TCHECK2(buf[0], 4); x = EXTRACT_LE_32BITS(buf); if (x == 0 || x == 0xFFFFFFFF) t = 0; else t = make_unix_date(buf); buf += 4; break; case 2: ND_TCHECK2(buf[0], 4); x = EXTRACT_LE_32BITS(buf); if (x == 0 || x == 0xFFFFFFFF) t = 0; else t = make_unix_date2(buf); buf += 4; break; case 3: ND_TCHECK2(buf[0], 8); t = interpret_long_date(buf); buf += 8; break; default: t = 0; break; } if (t != 0) { lt = localtime(&t); if (lt != NULL) tstring = asctime(lt); else tstring = "(Can't convert time)\n"; } else tstring = "NULL\n"; ND_PRINT((ndo, "%s", tstring)); fmt++; while (isdigit((unsigned char)*fmt)) fmt++; break; } default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (buf >= maxbuf && *fmt) ND_PRINT((ndo, "END OF BUFFER\n")); return(buf); trunc: ND_PRINT((ndo, "\n")); ND_PRINT((ndo, "WARNING: Short packet. Try increasing the snap length\n")); return(NULL); } const u_char * smb_fdata(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { static int depth = 0; char s[128]; char *p; while (*fmt) { switch (*fmt) { case '*': fmt++; while (buf < maxbuf) { const u_char *buf2; depth++; buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr); depth--; if (buf2 == NULL) return(NULL); if (buf2 == buf) return(buf); buf = buf2; } return(buf); case '|': fmt++; if (buf >= maxbuf) return(buf); break; case '%': fmt++; buf = maxbuf; break; case '#': fmt++; return(buf); break; case '[': fmt++; if (buf >= maxbuf) return(buf); memset(s, 0, sizeof(s)); p = strchr(fmt, ']'); if ((size_t)(p - fmt + 1) > sizeof(s)) { /* overrun */ return(buf); } strncpy(s, fmt, p - fmt); s[p - fmt] = '\0'; fmt = p + 1; buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr); if (buf == NULL) return(NULL); break; default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (!depth && buf < maxbuf) { size_t len = PTR_DIFF(maxbuf, buf); ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len)); smb_print_data(ndo, buf, len); return(buf + len); } return(buf); } typedef struct { const char *name; int code; const char *message; } err_code_struct; /* DOS Error Messages */ static const err_code_struct dos_msgs[] = { { "ERRbadfunc", 1, "Invalid function." }, { "ERRbadfile", 2, "File not found." }, { "ERRbadpath", 3, "Directory invalid." }, { "ERRnofids", 4, "No file descriptors available" }, { "ERRnoaccess", 5, "Access denied." }, { "ERRbadfid", 6, "Invalid file handle." }, { "ERRbadmcb", 7, "Memory control blocks destroyed." }, { "ERRnomem", 8, "Insufficient server memory to perform the requested function." }, { "ERRbadmem", 9, "Invalid memory block address." }, { "ERRbadenv", 10, "Invalid environment." }, { "ERRbadformat", 11, "Invalid format." }, { "ERRbadaccess", 12, "Invalid open mode." }, { "ERRbaddata", 13, "Invalid data." }, { "ERR", 14, "reserved." }, { "ERRbaddrive", 15, "Invalid drive specified." }, { "ERRremcd", 16, "A Delete Directory request attempted to remove the server's current directory." }, { "ERRdiffdevice", 17, "Not same device." }, { "ERRnofiles", 18, "A File Search command can find no more files matching the specified criteria." }, { "ERRbadshare", 32, "The sharing mode specified for an Open conflicts with existing FIDs on the file." }, { "ERRlock", 33, "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process." }, { "ERRfilexists", 80, "The file named in a Create Directory, Make New File or Link request already exists." }, { "ERRbadpipe", 230, "Pipe invalid." }, { "ERRpipebusy", 231, "All instances of the requested pipe are busy." }, { "ERRpipeclosing", 232, "Pipe close in progress." }, { "ERRnotconnected", 233, "No process on other end of pipe." }, { "ERRmoredata", 234, "There is more data to be returned." }, { NULL, -1, NULL } }; /* Server Error Messages */ static const err_code_struct server_msgs[] = { { "ERRerror", 1, "Non-specific error code." }, { "ERRbadpw", 2, "Bad password - name/password pair in a Tree Connect or Session Setup are invalid." }, { "ERRbadtype", 3, "reserved." }, { "ERRaccess", 4, "The requester does not have the necessary access rights within the specified context for the requested function. The context is defined by the TID or the UID." }, { "ERRinvnid", 5, "The tree ID (TID) specified in a command was invalid." }, { "ERRinvnetname", 6, "Invalid network name in tree connect." }, { "ERRinvdevice", 7, "Invalid device - printer request made to non-printer connection or non-printer request made to printer connection." }, { "ERRqfull", 49, "Print queue full (files) -- returned by open print file." }, { "ERRqtoobig", 50, "Print queue full -- no space." }, { "ERRqeof", 51, "EOF on print queue dump." }, { "ERRinvpfid", 52, "Invalid print file FID." }, { "ERRsmbcmd", 64, "The server did not recognize the command received." }, { "ERRsrverror", 65, "The server encountered an internal error, e.g., system file unavailable." }, { "ERRfilespecs", 67, "The file handle (FID) and pathname parameters contained an invalid combination of values." }, { "ERRreserved", 68, "reserved." }, { "ERRbadpermits", 69, "The access permissions specified for a file or directory are not a valid combination. The server cannot set the requested attribute." }, { "ERRreserved", 70, "reserved." }, { "ERRsetattrmode", 71, "The attribute mode in the Set File Attribute request is invalid." }, { "ERRpaused", 81, "Server is paused." }, { "ERRmsgoff", 82, "Not receiving messages." }, { "ERRnoroom", 83, "No room to buffer message." }, { "ERRrmuns", 87, "Too many remote user names." }, { "ERRtimeout", 88, "Operation timed out." }, { "ERRnoresource", 89, "No resources currently available for request." }, { "ERRtoomanyuids", 90, "Too many UIDs active on this session." }, { "ERRbaduid", 91, "The UID is not known as a valid ID on this session." }, { "ERRusempx", 250, "Temp unable to support Raw, use MPX mode." }, { "ERRusestd", 251, "Temp unable to support Raw, use standard read/write." }, { "ERRcontmpx", 252, "Continue in MPX mode." }, { "ERRreserved", 253, "reserved." }, { "ERRreserved", 254, "reserved." }, { "ERRnosupport", 0xFFFF, "Function not supported." }, { NULL, -1, NULL } }; /* Hard Error Messages */ static const err_code_struct hard_msgs[] = { { "ERRnowrite", 19, "Attempt to write on write-protected diskette." }, { "ERRbadunit", 20, "Unknown unit." }, { "ERRnotready", 21, "Drive not ready." }, { "ERRbadcmd", 22, "Unknown command." }, { "ERRdata", 23, "Data error (CRC)." }, { "ERRbadreq", 24, "Bad request structure length." }, { "ERRseek", 25 , "Seek error." }, { "ERRbadmedia", 26, "Unknown media type." }, { "ERRbadsector", 27, "Sector not found." }, { "ERRnopaper", 28, "Printer out of paper." }, { "ERRwrite", 29, "Write fault." }, { "ERRread", 30, "Read fault." }, { "ERRgeneral", 31, "General failure." }, { "ERRbadshare", 32, "A open conflicts with an existing open." }, { "ERRlock", 33, "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process." }, { "ERRwrongdisk", 34, "The wrong disk was found in a drive." }, { "ERRFCBUnavail", 35, "No FCBs are available to process request." }, { "ERRsharebufexc", 36, "A sharing buffer has been exceeded." }, { NULL, -1, NULL } }; static const struct { int code; const char *class; const err_code_struct *err_msgs; } err_classes[] = { { 0, "SUCCESS", NULL }, { 0x01, "ERRDOS", dos_msgs }, { 0x02, "ERRSRV", server_msgs }, { 0x03, "ERRHRD", hard_msgs }, { 0x04, "ERRXOS", NULL }, { 0xE1, "ERRRMX1", NULL }, { 0xE2, "ERRRMX2", NULL }, { 0xE3, "ERRRMX3", NULL }, { 0xFF, "ERRCMD", NULL }, { -1, NULL, NULL } }; /* * return a SMB error string from a SMB buffer */ char * smb_errstr(int class, int num) { static char ret[128]; int i, j; ret[0] = 0; for (i = 0; err_classes[i].class; i++) if (err_classes[i].code == class) { if (err_classes[i].err_msgs) { const err_code_struct *err = err_classes[i].err_msgs; for (j = 0; err[j].name; j++) if (num == err[j].code) { snprintf(ret, sizeof(ret), "%s - %s (%s)", err_classes[i].class, err[j].name, err[j].message); return ret; } } snprintf(ret, sizeof(ret), "%s - %d", err_classes[i].class, num); return ret; } snprintf(ret, sizeof(ret), "ERROR: Unknown error (%d,%d)", class, num); return(ret); } typedef struct { uint32_t code; const char *name; } nt_err_code_struct; /* * NT Error codes */ static const nt_err_code_struct nt_errors[] = { { 0x00000000, "STATUS_SUCCESS" }, { 0x00000000, "STATUS_WAIT_0" }, { 0x00000001, "STATUS_WAIT_1" }, { 0x00000002, "STATUS_WAIT_2" }, { 0x00000003, "STATUS_WAIT_3" }, { 0x0000003F, "STATUS_WAIT_63" }, { 0x00000080, "STATUS_ABANDONED" }, { 0x00000080, "STATUS_ABANDONED_WAIT_0" }, { 0x000000BF, "STATUS_ABANDONED_WAIT_63" }, { 0x000000C0, "STATUS_USER_APC" }, { 0x00000100, "STATUS_KERNEL_APC" }, { 0x00000101, "STATUS_ALERTED" }, { 0x00000102, "STATUS_TIMEOUT" }, { 0x00000103, "STATUS_PENDING" }, { 0x00000104, "STATUS_REPARSE" }, { 0x00000105, "STATUS_MORE_ENTRIES" }, { 0x00000106, "STATUS_NOT_ALL_ASSIGNED" }, { 0x00000107, "STATUS_SOME_NOT_MAPPED" }, { 0x00000108, "STATUS_OPLOCK_BREAK_IN_PROGRESS" }, { 0x00000109, "STATUS_VOLUME_MOUNTED" }, { 0x0000010A, "STATUS_RXACT_COMMITTED" }, { 0x0000010B, "STATUS_NOTIFY_CLEANUP" }, { 0x0000010C, "STATUS_NOTIFY_ENUM_DIR" }, { 0x0000010D, "STATUS_NO_QUOTAS_FOR_ACCOUNT" }, { 0x0000010E, "STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED" }, { 0x00000110, "STATUS_PAGE_FAULT_TRANSITION" }, { 0x00000111, "STATUS_PAGE_FAULT_DEMAND_ZERO" }, { 0x00000112, "STATUS_PAGE_FAULT_COPY_ON_WRITE" }, { 0x00000113, "STATUS_PAGE_FAULT_GUARD_PAGE" }, { 0x00000114, "STATUS_PAGE_FAULT_PAGING_FILE" }, { 0x00000115, "STATUS_CACHE_PAGE_LOCKED" }, { 0x00000116, "STATUS_CRASH_DUMP" }, { 0x00000117, "STATUS_BUFFER_ALL_ZEROS" }, { 0x00000118, "STATUS_REPARSE_OBJECT" }, { 0x0000045C, "STATUS_NO_SHUTDOWN_IN_PROGRESS" }, { 0x40000000, "STATUS_OBJECT_NAME_EXISTS" }, { 0x40000001, "STATUS_THREAD_WAS_SUSPENDED" }, { 0x40000002, "STATUS_WORKING_SET_LIMIT_RANGE" }, { 0x40000003, "STATUS_IMAGE_NOT_AT_BASE" }, { 0x40000004, "STATUS_RXACT_STATE_CREATED" }, { 0x40000005, "STATUS_SEGMENT_NOTIFICATION" }, { 0x40000006, "STATUS_LOCAL_USER_SESSION_KEY" }, { 0x40000007, "STATUS_BAD_CURRENT_DIRECTORY" }, { 0x40000008, "STATUS_SERIAL_MORE_WRITES" }, { 0x40000009, "STATUS_REGISTRY_RECOVERED" }, { 0x4000000A, "STATUS_FT_READ_RECOVERY_FROM_BACKUP" }, { 0x4000000B, "STATUS_FT_WRITE_RECOVERY" }, { 0x4000000C, "STATUS_SERIAL_COUNTER_TIMEOUT" }, { 0x4000000D, "STATUS_NULL_LM_PASSWORD" }, { 0x4000000E, "STATUS_IMAGE_MACHINE_TYPE_MISMATCH" }, { 0x4000000F, "STATUS_RECEIVE_PARTIAL" }, { 0x40000010, "STATUS_RECEIVE_EXPEDITED" }, { 0x40000011, "STATUS_RECEIVE_PARTIAL_EXPEDITED" }, { 0x40000012, "STATUS_EVENT_DONE" }, { 0x40000013, "STATUS_EVENT_PENDING" }, { 0x40000014, "STATUS_CHECKING_FILE_SYSTEM" }, { 0x40000015, "STATUS_FATAL_APP_EXIT" }, { 0x40000016, "STATUS_PREDEFINED_HANDLE" }, { 0x40000017, "STATUS_WAS_UNLOCKED" }, { 0x40000018, "STATUS_SERVICE_NOTIFICATION" }, { 0x40000019, "STATUS_WAS_LOCKED" }, { 0x4000001A, "STATUS_LOG_HARD_ERROR" }, { 0x4000001B, "STATUS_ALREADY_WIN32" }, { 0x4000001C, "STATUS_WX86_UNSIMULATE" }, { 0x4000001D, "STATUS_WX86_CONTINUE" }, { 0x4000001E, "STATUS_WX86_SINGLE_STEP" }, { 0x4000001F, "STATUS_WX86_BREAKPOINT" }, { 0x40000020, "STATUS_WX86_EXCEPTION_CONTINUE" }, { 0x40000021, "STATUS_WX86_EXCEPTION_LASTCHANCE" }, { 0x40000022, "STATUS_WX86_EXCEPTION_CHAIN" }, { 0x40000023, "STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE" }, { 0x40000024, "STATUS_NO_YIELD_PERFORMED" }, { 0x40000025, "STATUS_TIMER_RESUME_IGNORED" }, { 0x80000001, "STATUS_GUARD_PAGE_VIOLATION" }, { 0x80000002, "STATUS_DATATYPE_MISALIGNMENT" }, { 0x80000003, "STATUS_BREAKPOINT" }, { 0x80000004, "STATUS_SINGLE_STEP" }, { 0x80000005, "STATUS_BUFFER_OVERFLOW" }, { 0x80000006, "STATUS_NO_MORE_FILES" }, { 0x80000007, "STATUS_WAKE_SYSTEM_DEBUGGER" }, { 0x8000000A, "STATUS_HANDLES_CLOSED" }, { 0x8000000B, "STATUS_NO_INHERITANCE" }, { 0x8000000C, "STATUS_GUID_SUBSTITUTION_MADE" }, { 0x8000000D, "STATUS_PARTIAL_COPY" }, { 0x8000000E, "STATUS_DEVICE_PAPER_EMPTY" }, { 0x8000000F, "STATUS_DEVICE_POWERED_OFF" }, { 0x80000010, "STATUS_DEVICE_OFF_LINE" }, { 0x80000011, "STATUS_DEVICE_BUSY" }, { 0x80000012, "STATUS_NO_MORE_EAS" }, { 0x80000013, "STATUS_INVALID_EA_NAME" }, { 0x80000014, "STATUS_EA_LIST_INCONSISTENT" }, { 0x80000015, "STATUS_INVALID_EA_FLAG" }, { 0x80000016, "STATUS_VERIFY_REQUIRED" }, { 0x80000017, "STATUS_EXTRANEOUS_INFORMATION" }, { 0x80000018, "STATUS_RXACT_COMMIT_NECESSARY" }, { 0x8000001A, "STATUS_NO_MORE_ENTRIES" }, { 0x8000001B, "STATUS_FILEMARK_DETECTED" }, { 0x8000001C, "STATUS_MEDIA_CHANGED" }, { 0x8000001D, "STATUS_BUS_RESET" }, { 0x8000001E, "STATUS_END_OF_MEDIA" }, { 0x8000001F, "STATUS_BEGINNING_OF_MEDIA" }, { 0x80000020, "STATUS_MEDIA_CHECK" }, { 0x80000021, "STATUS_SETMARK_DETECTED" }, { 0x80000022, "STATUS_NO_DATA_DETECTED" }, { 0x80000023, "STATUS_REDIRECTOR_HAS_OPEN_HANDLES" }, { 0x80000024, "STATUS_SERVER_HAS_OPEN_HANDLES" }, { 0x80000025, "STATUS_ALREADY_DISCONNECTED" }, { 0x80000026, "STATUS_LONGJUMP" }, { 0x80040111, "MAPI_E_LOGON_FAILED" }, { 0x80090300, "SEC_E_INSUFFICIENT_MEMORY" }, { 0x80090301, "SEC_E_INVALID_HANDLE" }, { 0x80090302, "SEC_E_UNSUPPORTED_FUNCTION" }, { 0x8009030B, "SEC_E_NO_IMPERSONATION" }, { 0x8009030D, "SEC_E_UNKNOWN_CREDENTIALS" }, { 0x8009030E, "SEC_E_NO_CREDENTIALS" }, { 0x8009030F, "SEC_E_MESSAGE_ALTERED" }, { 0x80090310, "SEC_E_OUT_OF_SEQUENCE" }, { 0x80090311, "SEC_E_NO_AUTHENTICATING_AUTHORITY" }, { 0xC0000001, "STATUS_UNSUCCESSFUL" }, { 0xC0000002, "STATUS_NOT_IMPLEMENTED" }, { 0xC0000003, "STATUS_INVALID_INFO_CLASS" }, { 0xC0000004, "STATUS_INFO_LENGTH_MISMATCH" }, { 0xC0000005, "STATUS_ACCESS_VIOLATION" }, { 0xC0000006, "STATUS_IN_PAGE_ERROR" }, { 0xC0000007, "STATUS_PAGEFILE_QUOTA" }, { 0xC0000008, "STATUS_INVALID_HANDLE" }, { 0xC0000009, "STATUS_BAD_INITIAL_STACK" }, { 0xC000000A, "STATUS_BAD_INITIAL_PC" }, { 0xC000000B, "STATUS_INVALID_CID" }, { 0xC000000C, "STATUS_TIMER_NOT_CANCELED" }, { 0xC000000D, "STATUS_INVALID_PARAMETER" }, { 0xC000000E, "STATUS_NO_SUCH_DEVICE" }, { 0xC000000F, "STATUS_NO_SUCH_FILE" }, { 0xC0000010, "STATUS_INVALID_DEVICE_REQUEST" }, { 0xC0000011, "STATUS_END_OF_FILE" }, { 0xC0000012, "STATUS_WRONG_VOLUME" }, { 0xC0000013, "STATUS_NO_MEDIA_IN_DEVICE" }, { 0xC0000014, "STATUS_UNRECOGNIZED_MEDIA" }, { 0xC0000015, "STATUS_NONEXISTENT_SECTOR" }, { 0xC0000016, "STATUS_MORE_PROCESSING_REQUIRED" }, { 0xC0000017, "STATUS_NO_MEMORY" }, { 0xC0000018, "STATUS_CONFLICTING_ADDRESSES" }, { 0xC0000019, "STATUS_NOT_MAPPED_VIEW" }, { 0xC000001A, "STATUS_UNABLE_TO_FREE_VM" }, { 0xC000001B, "STATUS_UNABLE_TO_DELETE_SECTION" }, { 0xC000001C, "STATUS_INVALID_SYSTEM_SERVICE" }, { 0xC000001D, "STATUS_ILLEGAL_INSTRUCTION" }, { 0xC000001E, "STATUS_INVALID_LOCK_SEQUENCE" }, { 0xC000001F, "STATUS_INVALID_VIEW_SIZE" }, { 0xC0000020, "STATUS_INVALID_FILE_FOR_SECTION" }, { 0xC0000021, "STATUS_ALREADY_COMMITTED" }, { 0xC0000022, "STATUS_ACCESS_DENIED" }, { 0xC0000023, "STATUS_BUFFER_TOO_SMALL" }, { 0xC0000024, "STATUS_OBJECT_TYPE_MISMATCH" }, { 0xC0000025, "STATUS_NONCONTINUABLE_EXCEPTION" }, { 0xC0000026, "STATUS_INVALID_DISPOSITION" }, { 0xC0000027, "STATUS_UNWIND" }, { 0xC0000028, "STATUS_BAD_STACK" }, { 0xC0000029, "STATUS_INVALID_UNWIND_TARGET" }, { 0xC000002A, "STATUS_NOT_LOCKED" }, { 0xC000002B, "STATUS_PARITY_ERROR" }, { 0xC000002C, "STATUS_UNABLE_TO_DECOMMIT_VM" }, { 0xC000002D, "STATUS_NOT_COMMITTED" }, { 0xC000002E, "STATUS_INVALID_PORT_ATTRIBUTES" }, { 0xC000002F, "STATUS_PORT_MESSAGE_TOO_LONG" }, { 0xC0000030, "STATUS_INVALID_PARAMETER_MIX" }, { 0xC0000031, "STATUS_INVALID_QUOTA_LOWER" }, { 0xC0000032, "STATUS_DISK_CORRUPT_ERROR" }, { 0xC0000033, "STATUS_OBJECT_NAME_INVALID" }, { 0xC0000034, "STATUS_OBJECT_NAME_NOT_FOUND" }, { 0xC0000035, "STATUS_OBJECT_NAME_COLLISION" }, { 0xC0000037, "STATUS_PORT_DISCONNECTED" }, { 0xC0000038, "STATUS_DEVICE_ALREADY_ATTACHED" }, { 0xC0000039, "STATUS_OBJECT_PATH_INVALID" }, { 0xC000003A, "STATUS_OBJECT_PATH_NOT_FOUND" }, { 0xC000003B, "STATUS_OBJECT_PATH_SYNTAX_BAD" }, { 0xC000003C, "STATUS_DATA_OVERRUN" }, { 0xC000003D, "STATUS_DATA_LATE_ERROR" }, { 0xC000003E, "STATUS_DATA_ERROR" }, { 0xC000003F, "STATUS_CRC_ERROR" }, { 0xC0000040, "STATUS_SECTION_TOO_BIG" }, { 0xC0000041, "STATUS_PORT_CONNECTION_REFUSED" }, { 0xC0000042, "STATUS_INVALID_PORT_HANDLE" }, { 0xC0000043, "STATUS_SHARING_VIOLATION" }, { 0xC0000044, "STATUS_QUOTA_EXCEEDED" }, { 0xC0000045, "STATUS_INVALID_PAGE_PROTECTION" }, { 0xC0000046, "STATUS_MUTANT_NOT_OWNED" }, { 0xC0000047, "STATUS_SEMAPHORE_LIMIT_EXCEEDED" }, { 0xC0000048, "STATUS_PORT_ALREADY_SET" }, { 0xC0000049, "STATUS_SECTION_NOT_IMAGE" }, { 0xC000004A, "STATUS_SUSPEND_COUNT_EXCEEDED" }, { 0xC000004B, "STATUS_THREAD_IS_TERMINATING" }, { 0xC000004C, "STATUS_BAD_WORKING_SET_LIMIT" }, { 0xC000004D, "STATUS_INCOMPATIBLE_FILE_MAP" }, { 0xC000004E, "STATUS_SECTION_PROTECTION" }, { 0xC000004F, "STATUS_EAS_NOT_SUPPORTED" }, { 0xC0000050, "STATUS_EA_TOO_LARGE" }, { 0xC0000051, "STATUS_NONEXISTENT_EA_ENTRY" }, { 0xC0000052, "STATUS_NO_EAS_ON_FILE" }, { 0xC0000053, "STATUS_EA_CORRUPT_ERROR" }, { 0xC0000054, "STATUS_FILE_LOCK_CONFLICT" }, { 0xC0000055, "STATUS_LOCK_NOT_GRANTED" }, { 0xC0000056, "STATUS_DELETE_PENDING" }, { 0xC0000057, "STATUS_CTL_FILE_NOT_SUPPORTED" }, { 0xC0000058, "STATUS_UNKNOWN_REVISION" }, { 0xC0000059, "STATUS_REVISION_MISMATCH" }, { 0xC000005A, "STATUS_INVALID_OWNER" }, { 0xC000005B, "STATUS_INVALID_PRIMARY_GROUP" }, { 0xC000005C, "STATUS_NO_IMPERSONATION_TOKEN" }, { 0xC000005D, "STATUS_CANT_DISABLE_MANDATORY" }, { 0xC000005E, "STATUS_NO_LOGON_SERVERS" }, { 0xC000005F, "STATUS_NO_SUCH_LOGON_SESSION" }, { 0xC0000060, "STATUS_NO_SUCH_PRIVILEGE" }, { 0xC0000061, "STATUS_PRIVILEGE_NOT_HELD" }, { 0xC0000062, "STATUS_INVALID_ACCOUNT_NAME" }, { 0xC0000063, "STATUS_USER_EXISTS" }, { 0xC0000064, "STATUS_NO_SUCH_USER" }, { 0xC0000065, "STATUS_GROUP_EXISTS" }, { 0xC0000066, "STATUS_NO_SUCH_GROUP" }, { 0xC0000067, "STATUS_MEMBER_IN_GROUP" }, { 0xC0000068, "STATUS_MEMBER_NOT_IN_GROUP" }, { 0xC0000069, "STATUS_LAST_ADMIN" }, { 0xC000006A, "STATUS_WRONG_PASSWORD" }, { 0xC000006B, "STATUS_ILL_FORMED_PASSWORD" }, { 0xC000006C, "STATUS_PASSWORD_RESTRICTION" }, { 0xC000006D, "STATUS_LOGON_FAILURE" }, { 0xC000006E, "STATUS_ACCOUNT_RESTRICTION" }, { 0xC000006F, "STATUS_INVALID_LOGON_HOURS" }, { 0xC0000070, "STATUS_INVALID_WORKSTATION" }, { 0xC0000071, "STATUS_PASSWORD_EXPIRED" }, { 0xC0000072, "STATUS_ACCOUNT_DISABLED" }, { 0xC0000073, "STATUS_NONE_MAPPED" }, { 0xC0000074, "STATUS_TOO_MANY_LUIDS_REQUESTED" }, { 0xC0000075, "STATUS_LUIDS_EXHAUSTED" }, { 0xC0000076, "STATUS_INVALID_SUB_AUTHORITY" }, { 0xC0000077, "STATUS_INVALID_ACL" }, { 0xC0000078, "STATUS_INVALID_SID" }, { 0xC0000079, "STATUS_INVALID_SECURITY_DESCR" }, { 0xC000007A, "STATUS_PROCEDURE_NOT_FOUND" }, { 0xC000007B, "STATUS_INVALID_IMAGE_FORMAT" }, { 0xC000007C, "STATUS_NO_TOKEN" }, { 0xC000007D, "STATUS_BAD_INHERITANCE_ACL" }, { 0xC000007E, "STATUS_RANGE_NOT_LOCKED" }, { 0xC000007F, "STATUS_DISK_FULL" }, { 0xC0000080, "STATUS_SERVER_DISABLED" }, { 0xC0000081, "STATUS_SERVER_NOT_DISABLED" }, { 0xC0000082, "STATUS_TOO_MANY_GUIDS_REQUESTED" }, { 0xC0000083, "STATUS_GUIDS_EXHAUSTED" }, { 0xC0000084, "STATUS_INVALID_ID_AUTHORITY" }, { 0xC0000085, "STATUS_AGENTS_EXHAUSTED" }, { 0xC0000086, "STATUS_INVALID_VOLUME_LABEL" }, { 0xC0000087, "STATUS_SECTION_NOT_EXTENDED" }, { 0xC0000088, "STATUS_NOT_MAPPED_DATA" }, { 0xC0000089, "STATUS_RESOURCE_DATA_NOT_FOUND" }, { 0xC000008A, "STATUS_RESOURCE_TYPE_NOT_FOUND" }, { 0xC000008B, "STATUS_RESOURCE_NAME_NOT_FOUND" }, { 0xC000008C, "STATUS_ARRAY_BOUNDS_EXCEEDED" }, { 0xC000008D, "STATUS_FLOAT_DENORMAL_OPERAND" }, { 0xC000008E, "STATUS_FLOAT_DIVIDE_BY_ZERO" }, { 0xC000008F, "STATUS_FLOAT_INEXACT_RESULT" }, { 0xC0000090, "STATUS_FLOAT_INVALID_OPERATION" }, { 0xC0000091, "STATUS_FLOAT_OVERFLOW" }, { 0xC0000092, "STATUS_FLOAT_STACK_CHECK" }, { 0xC0000093, "STATUS_FLOAT_UNDERFLOW" }, { 0xC0000094, "STATUS_INTEGER_DIVIDE_BY_ZERO" }, { 0xC0000095, "STATUS_INTEGER_OVERFLOW" }, { 0xC0000096, "STATUS_PRIVILEGED_INSTRUCTION" }, { 0xC0000097, "STATUS_TOO_MANY_PAGING_FILES" }, { 0xC0000098, "STATUS_FILE_INVALID" }, { 0xC0000099, "STATUS_ALLOTTED_SPACE_EXCEEDED" }, { 0xC000009A, "STATUS_INSUFFICIENT_RESOURCES" }, { 0xC000009B, "STATUS_DFS_EXIT_PATH_FOUND" }, { 0xC000009C, "STATUS_DEVICE_DATA_ERROR" }, { 0xC000009D, "STATUS_DEVICE_NOT_CONNECTED" }, { 0xC000009E, "STATUS_DEVICE_POWER_FAILURE" }, { 0xC000009F, "STATUS_FREE_VM_NOT_AT_BASE" }, { 0xC00000A0, "STATUS_MEMORY_NOT_ALLOCATED" }, { 0xC00000A1, "STATUS_WORKING_SET_QUOTA" }, { 0xC00000A2, "STATUS_MEDIA_WRITE_PROTECTED" }, { 0xC00000A3, "STATUS_DEVICE_NOT_READY" }, { 0xC00000A4, "STATUS_INVALID_GROUP_ATTRIBUTES" }, { 0xC00000A5, "STATUS_BAD_IMPERSONATION_LEVEL" }, { 0xC00000A6, "STATUS_CANT_OPEN_ANONYMOUS" }, { 0xC00000A7, "STATUS_BAD_VALIDATION_CLASS" }, { 0xC00000A8, "STATUS_BAD_TOKEN_TYPE" }, { 0xC00000A9, "STATUS_BAD_MASTER_BOOT_RECORD" }, { 0xC00000AA, "STATUS_INSTRUCTION_MISALIGNMENT" }, { 0xC00000AB, "STATUS_INSTANCE_NOT_AVAILABLE" }, { 0xC00000AC, "STATUS_PIPE_NOT_AVAILABLE" }, { 0xC00000AD, "STATUS_INVALID_PIPE_STATE" }, { 0xC00000AE, "STATUS_PIPE_BUSY" }, { 0xC00000AF, "STATUS_ILLEGAL_FUNCTION" }, { 0xC00000B0, "STATUS_PIPE_DISCONNECTED" }, { 0xC00000B1, "STATUS_PIPE_CLOSING" }, { 0xC00000B2, "STATUS_PIPE_CONNECTED" }, { 0xC00000B3, "STATUS_PIPE_LISTENING" }, { 0xC00000B4, "STATUS_INVALID_READ_MODE" }, { 0xC00000B5, "STATUS_IO_TIMEOUT" }, { 0xC00000B6, "STATUS_FILE_FORCED_CLOSED" }, { 0xC00000B7, "STATUS_PROFILING_NOT_STARTED" }, { 0xC00000B8, "STATUS_PROFILING_NOT_STOPPED" }, { 0xC00000B9, "STATUS_COULD_NOT_INTERPRET" }, { 0xC00000BA, "STATUS_FILE_IS_A_DIRECTORY" }, { 0xC00000BB, "STATUS_NOT_SUPPORTED" }, { 0xC00000BC, "STATUS_REMOTE_NOT_LISTENING" }, { 0xC00000BD, "STATUS_DUPLICATE_NAME" }, { 0xC00000BE, "STATUS_BAD_NETWORK_PATH" }, { 0xC00000BF, "STATUS_NETWORK_BUSY" }, { 0xC00000C0, "STATUS_DEVICE_DOES_NOT_EXIST" }, { 0xC00000C1, "STATUS_TOO_MANY_COMMANDS" }, { 0xC00000C2, "STATUS_ADAPTER_HARDWARE_ERROR" }, { 0xC00000C3, "STATUS_INVALID_NETWORK_RESPONSE" }, { 0xC00000C4, "STATUS_UNEXPECTED_NETWORK_ERROR" }, { 0xC00000C5, "STATUS_BAD_REMOTE_ADAPTER" }, { 0xC00000C6, "STATUS_PRINT_QUEUE_FULL" }, { 0xC00000C7, "STATUS_NO_SPOOL_SPACE" }, { 0xC00000C8, "STATUS_PRINT_CANCELLED" }, { 0xC00000C9, "STATUS_NETWORK_NAME_DELETED" }, { 0xC00000CA, "STATUS_NETWORK_ACCESS_DENIED" }, { 0xC00000CB, "STATUS_BAD_DEVICE_TYPE" }, { 0xC00000CC, "STATUS_BAD_NETWORK_NAME" }, { 0xC00000CD, "STATUS_TOO_MANY_NAMES" }, { 0xC00000CE, "STATUS_TOO_MANY_SESSIONS" }, { 0xC00000CF, "STATUS_SHARING_PAUSED" }, { 0xC00000D0, "STATUS_REQUEST_NOT_ACCEPTED" }, { 0xC00000D1, "STATUS_REDIRECTOR_PAUSED" }, { 0xC00000D2, "STATUS_NET_WRITE_FAULT" }, { 0xC00000D3, "STATUS_PROFILING_AT_LIMIT" }, { 0xC00000D4, "STATUS_NOT_SAME_DEVICE" }, { 0xC00000D5, "STATUS_FILE_RENAMED" }, { 0xC00000D6, "STATUS_VIRTUAL_CIRCUIT_CLOSED" }, { 0xC00000D7, "STATUS_NO_SECURITY_ON_OBJECT" }, { 0xC00000D8, "STATUS_CANT_WAIT" }, { 0xC00000D9, "STATUS_PIPE_EMPTY" }, { 0xC00000DA, "STATUS_CANT_ACCESS_DOMAIN_INFO" }, { 0xC00000DB, "STATUS_CANT_TERMINATE_SELF" }, { 0xC00000DC, "STATUS_INVALID_SERVER_STATE" }, { 0xC00000DD, "STATUS_INVALID_DOMAIN_STATE" }, { 0xC00000DE, "STATUS_INVALID_DOMAIN_ROLE" }, { 0xC00000DF, "STATUS_NO_SUCH_DOMAIN" }, { 0xC00000E0, "STATUS_DOMAIN_EXISTS" }, { 0xC00000E1, "STATUS_DOMAIN_LIMIT_EXCEEDED" }, { 0xC00000E2, "STATUS_OPLOCK_NOT_GRANTED" }, { 0xC00000E3, "STATUS_INVALID_OPLOCK_PROTOCOL" }, { 0xC00000E4, "STATUS_INTERNAL_DB_CORRUPTION" }, { 0xC00000E5, "STATUS_INTERNAL_ERROR" }, { 0xC00000E6, "STATUS_GENERIC_NOT_MAPPED" }, { 0xC00000E7, "STATUS_BAD_DESCRIPTOR_FORMAT" }, { 0xC00000E8, "STATUS_INVALID_USER_BUFFER" }, { 0xC00000E9, "STATUS_UNEXPECTED_IO_ERROR" }, { 0xC00000EA, "STATUS_UNEXPECTED_MM_CREATE_ERR" }, { 0xC00000EB, "STATUS_UNEXPECTED_MM_MAP_ERROR" }, { 0xC00000EC, "STATUS_UNEXPECTED_MM_EXTEND_ERR" }, { 0xC00000ED, "STATUS_NOT_LOGON_PROCESS" }, { 0xC00000EE, "STATUS_LOGON_SESSION_EXISTS" }, { 0xC00000EF, "STATUS_INVALID_PARAMETER_1" }, { 0xC00000F0, "STATUS_INVALID_PARAMETER_2" }, { 0xC00000F1, "STATUS_INVALID_PARAMETER_3" }, { 0xC00000F2, "STATUS_INVALID_PARAMETER_4" }, { 0xC00000F3, "STATUS_INVALID_PARAMETER_5" }, { 0xC00000F4, "STATUS_INVALID_PARAMETER_6" }, { 0xC00000F5, "STATUS_INVALID_PARAMETER_7" }, { 0xC00000F6, "STATUS_INVALID_PARAMETER_8" }, { 0xC00000F7, "STATUS_INVALID_PARAMETER_9" }, { 0xC00000F8, "STATUS_INVALID_PARAMETER_10" }, { 0xC00000F9, "STATUS_INVALID_PARAMETER_11" }, { 0xC00000FA, "STATUS_INVALID_PARAMETER_12" }, { 0xC00000FB, "STATUS_REDIRECTOR_NOT_STARTED" }, { 0xC00000FC, "STATUS_REDIRECTOR_STARTED" }, { 0xC00000FD, "STATUS_STACK_OVERFLOW" }, { 0xC00000FE, "STATUS_NO_SUCH_PACKAGE" }, { 0xC00000FF, "STATUS_BAD_FUNCTION_TABLE" }, { 0xC0000100, "STATUS_VARIABLE_NOT_FOUND" }, { 0xC0000101, "STATUS_DIRECTORY_NOT_EMPTY" }, { 0xC0000102, "STATUS_FILE_CORRUPT_ERROR" }, { 0xC0000103, "STATUS_NOT_A_DIRECTORY" }, { 0xC0000104, "STATUS_BAD_LOGON_SESSION_STATE" }, { 0xC0000105, "STATUS_LOGON_SESSION_COLLISION" }, { 0xC0000106, "STATUS_NAME_TOO_LONG" }, { 0xC0000107, "STATUS_FILES_OPEN" }, { 0xC0000108, "STATUS_CONNECTION_IN_USE" }, { 0xC0000109, "STATUS_MESSAGE_NOT_FOUND" }, { 0xC000010A, "STATUS_PROCESS_IS_TERMINATING" }, { 0xC000010B, "STATUS_INVALID_LOGON_TYPE" }, { 0xC000010C, "STATUS_NO_GUID_TRANSLATION" }, { 0xC000010D, "STATUS_CANNOT_IMPERSONATE" }, { 0xC000010E, "STATUS_IMAGE_ALREADY_LOADED" }, { 0xC000010F, "STATUS_ABIOS_NOT_PRESENT" }, { 0xC0000110, "STATUS_ABIOS_LID_NOT_EXIST" }, { 0xC0000111, "STATUS_ABIOS_LID_ALREADY_OWNED" }, { 0xC0000112, "STATUS_ABIOS_NOT_LID_OWNER" }, { 0xC0000113, "STATUS_ABIOS_INVALID_COMMAND" }, { 0xC0000114, "STATUS_ABIOS_INVALID_LID" }, { 0xC0000115, "STATUS_ABIOS_SELECTOR_NOT_AVAILABLE" }, { 0xC0000116, "STATUS_ABIOS_INVALID_SELECTOR" }, { 0xC0000117, "STATUS_NO_LDT" }, { 0xC0000118, "STATUS_INVALID_LDT_SIZE" }, { 0xC0000119, "STATUS_INVALID_LDT_OFFSET" }, { 0xC000011A, "STATUS_INVALID_LDT_DESCRIPTOR" }, { 0xC000011B, "STATUS_INVALID_IMAGE_NE_FORMAT" }, { 0xC000011C, "STATUS_RXACT_INVALID_STATE" }, { 0xC000011D, "STATUS_RXACT_COMMIT_FAILURE" }, { 0xC000011E, "STATUS_MAPPED_FILE_SIZE_ZERO" }, { 0xC000011F, "STATUS_TOO_MANY_OPENED_FILES" }, { 0xC0000120, "STATUS_CANCELLED" }, { 0xC0000121, "STATUS_CANNOT_DELETE" }, { 0xC0000122, "STATUS_INVALID_COMPUTER_NAME" }, { 0xC0000123, "STATUS_FILE_DELETED" }, { 0xC0000124, "STATUS_SPECIAL_ACCOUNT" }, { 0xC0000125, "STATUS_SPECIAL_GROUP" }, { 0xC0000126, "STATUS_SPECIAL_USER" }, { 0xC0000127, "STATUS_MEMBERS_PRIMARY_GROUP" }, { 0xC0000128, "STATUS_FILE_CLOSED" }, { 0xC0000129, "STATUS_TOO_MANY_THREADS" }, { 0xC000012A, "STATUS_THREAD_NOT_IN_PROCESS" }, { 0xC000012B, "STATUS_TOKEN_ALREADY_IN_USE" }, { 0xC000012C, "STATUS_PAGEFILE_QUOTA_EXCEEDED" }, { 0xC000012D, "STATUS_COMMITMENT_LIMIT" }, { 0xC000012E, "STATUS_INVALID_IMAGE_LE_FORMAT" }, { 0xC000012F, "STATUS_INVALID_IMAGE_NOT_MZ" }, { 0xC0000130, "STATUS_INVALID_IMAGE_PROTECT" }, { 0xC0000131, "STATUS_INVALID_IMAGE_WIN_16" }, { 0xC0000132, "STATUS_LOGON_SERVER_CONFLICT" }, { 0xC0000133, "STATUS_TIME_DIFFERENCE_AT_DC" }, { 0xC0000134, "STATUS_SYNCHRONIZATION_REQUIRED" }, { 0xC0000135, "STATUS_DLL_NOT_FOUND" }, { 0xC0000136, "STATUS_OPEN_FAILED" }, { 0xC0000137, "STATUS_IO_PRIVILEGE_FAILED" }, { 0xC0000138, "STATUS_ORDINAL_NOT_FOUND" }, { 0xC0000139, "STATUS_ENTRYPOINT_NOT_FOUND" }, { 0xC000013A, "STATUS_CONTROL_C_EXIT" }, { 0xC000013B, "STATUS_LOCAL_DISCONNECT" }, { 0xC000013C, "STATUS_REMOTE_DISCONNECT" }, { 0xC000013D, "STATUS_REMOTE_RESOURCES" }, { 0xC000013E, "STATUS_LINK_FAILED" }, { 0xC000013F, "STATUS_LINK_TIMEOUT" }, { 0xC0000140, "STATUS_INVALID_CONNECTION" }, { 0xC0000141, "STATUS_INVALID_ADDRESS" }, { 0xC0000142, "STATUS_DLL_INIT_FAILED" }, { 0xC0000143, "STATUS_MISSING_SYSTEMFILE" }, { 0xC0000144, "STATUS_UNHANDLED_EXCEPTION" }, { 0xC0000145, "STATUS_APP_INIT_FAILURE" }, { 0xC0000146, "STATUS_PAGEFILE_CREATE_FAILED" }, { 0xC0000147, "STATUS_NO_PAGEFILE" }, { 0xC0000148, "STATUS_INVALID_LEVEL" }, { 0xC0000149, "STATUS_WRONG_PASSWORD_CORE" }, { 0xC000014A, "STATUS_ILLEGAL_FLOAT_CONTEXT" }, { 0xC000014B, "STATUS_PIPE_BROKEN" }, { 0xC000014C, "STATUS_REGISTRY_CORRUPT" }, { 0xC000014D, "STATUS_REGISTRY_IO_FAILED" }, { 0xC000014E, "STATUS_NO_EVENT_PAIR" }, { 0xC000014F, "STATUS_UNRECOGNIZED_VOLUME" }, { 0xC0000150, "STATUS_SERIAL_NO_DEVICE_INITED" }, { 0xC0000151, "STATUS_NO_SUCH_ALIAS" }, { 0xC0000152, "STATUS_MEMBER_NOT_IN_ALIAS" }, { 0xC0000153, "STATUS_MEMBER_IN_ALIAS" }, { 0xC0000154, "STATUS_ALIAS_EXISTS" }, { 0xC0000155, "STATUS_LOGON_NOT_GRANTED" }, { 0xC0000156, "STATUS_TOO_MANY_SECRETS" }, { 0xC0000157, "STATUS_SECRET_TOO_LONG" }, { 0xC0000158, "STATUS_INTERNAL_DB_ERROR" }, { 0xC0000159, "STATUS_FULLSCREEN_MODE" }, { 0xC000015A, "STATUS_TOO_MANY_CONTEXT_IDS" }, { 0xC000015B, "STATUS_LOGON_TYPE_NOT_GRANTED" }, { 0xC000015C, "STATUS_NOT_REGISTRY_FILE" }, { 0xC000015D, "STATUS_NT_CROSS_ENCRYPTION_REQUIRED" }, { 0xC000015E, "STATUS_DOMAIN_CTRLR_CONFIG_ERROR" }, { 0xC000015F, "STATUS_FT_MISSING_MEMBER" }, { 0xC0000160, "STATUS_ILL_FORMED_SERVICE_ENTRY" }, { 0xC0000161, "STATUS_ILLEGAL_CHARACTER" }, { 0xC0000162, "STATUS_UNMAPPABLE_CHARACTER" }, { 0xC0000163, "STATUS_UNDEFINED_CHARACTER" }, { 0xC0000164, "STATUS_FLOPPY_VOLUME" }, { 0xC0000165, "STATUS_FLOPPY_ID_MARK_NOT_FOUND" }, { 0xC0000166, "STATUS_FLOPPY_WRONG_CYLINDER" }, { 0xC0000167, "STATUS_FLOPPY_UNKNOWN_ERROR" }, { 0xC0000168, "STATUS_FLOPPY_BAD_REGISTERS" }, { 0xC0000169, "STATUS_DISK_RECALIBRATE_FAILED" }, { 0xC000016A, "STATUS_DISK_OPERATION_FAILED" }, { 0xC000016B, "STATUS_DISK_RESET_FAILED" }, { 0xC000016C, "STATUS_SHARED_IRQ_BUSY" }, { 0xC000016D, "STATUS_FT_ORPHANING" }, { 0xC000016E, "STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT" }, { 0xC0000172, "STATUS_PARTITION_FAILURE" }, { 0xC0000173, "STATUS_INVALID_BLOCK_LENGTH" }, { 0xC0000174, "STATUS_DEVICE_NOT_PARTITIONED" }, { 0xC0000175, "STATUS_UNABLE_TO_LOCK_MEDIA" }, { 0xC0000176, "STATUS_UNABLE_TO_UNLOAD_MEDIA" }, { 0xC0000177, "STATUS_EOM_OVERFLOW" }, { 0xC0000178, "STATUS_NO_MEDIA" }, { 0xC000017A, "STATUS_NO_SUCH_MEMBER" }, { 0xC000017B, "STATUS_INVALID_MEMBER" }, { 0xC000017C, "STATUS_KEY_DELETED" }, { 0xC000017D, "STATUS_NO_LOG_SPACE" }, { 0xC000017E, "STATUS_TOO_MANY_SIDS" }, { 0xC000017F, "STATUS_LM_CROSS_ENCRYPTION_REQUIRED" }, { 0xC0000180, "STATUS_KEY_HAS_CHILDREN" }, { 0xC0000181, "STATUS_CHILD_MUST_BE_VOLATILE" }, { 0xC0000182, "STATUS_DEVICE_CONFIGURATION_ERROR" }, { 0xC0000183, "STATUS_DRIVER_INTERNAL_ERROR" }, { 0xC0000184, "STATUS_INVALID_DEVICE_STATE" }, { 0xC0000185, "STATUS_IO_DEVICE_ERROR" }, { 0xC0000186, "STATUS_DEVICE_PROTOCOL_ERROR" }, { 0xC0000187, "STATUS_BACKUP_CONTROLLER" }, { 0xC0000188, "STATUS_LOG_FILE_FULL" }, { 0xC0000189, "STATUS_TOO_LATE" }, { 0xC000018A, "STATUS_NO_TRUST_LSA_SECRET" }, { 0xC000018B, "STATUS_NO_TRUST_SAM_ACCOUNT" }, { 0xC000018C, "STATUS_TRUSTED_DOMAIN_FAILURE" }, { 0xC000018D, "STATUS_TRUSTED_RELATIONSHIP_FAILURE" }, { 0xC000018E, "STATUS_EVENTLOG_FILE_CORRUPT" }, { 0xC000018F, "STATUS_EVENTLOG_CANT_START" }, { 0xC0000190, "STATUS_TRUST_FAILURE" }, { 0xC0000191, "STATUS_MUTANT_LIMIT_EXCEEDED" }, { 0xC0000192, "STATUS_NETLOGON_NOT_STARTED" }, { 0xC0000193, "STATUS_ACCOUNT_EXPIRED" }, { 0xC0000194, "STATUS_POSSIBLE_DEADLOCK" }, { 0xC0000195, "STATUS_NETWORK_CREDENTIAL_CONFLICT" }, { 0xC0000196, "STATUS_REMOTE_SESSION_LIMIT" }, { 0xC0000197, "STATUS_EVENTLOG_FILE_CHANGED" }, { 0xC0000198, "STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT" }, { 0xC0000199, "STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT" }, { 0xC000019A, "STATUS_NOLOGON_SERVER_TRUST_ACCOUNT" }, { 0xC000019B, "STATUS_DOMAIN_TRUST_INCONSISTENT" }, { 0xC000019C, "STATUS_FS_DRIVER_REQUIRED" }, { 0xC0000202, "STATUS_NO_USER_SESSION_KEY" }, { 0xC0000203, "STATUS_USER_SESSION_DELETED" }, { 0xC0000204, "STATUS_RESOURCE_LANG_NOT_FOUND" }, { 0xC0000205, "STATUS_INSUFF_SERVER_RESOURCES" }, { 0xC0000206, "STATUS_INVALID_BUFFER_SIZE" }, { 0xC0000207, "STATUS_INVALID_ADDRESS_COMPONENT" }, { 0xC0000208, "STATUS_INVALID_ADDRESS_WILDCARD" }, { 0xC0000209, "STATUS_TOO_MANY_ADDRESSES" }, { 0xC000020A, "STATUS_ADDRESS_ALREADY_EXISTS" }, { 0xC000020B, "STATUS_ADDRESS_CLOSED" }, { 0xC000020C, "STATUS_CONNECTION_DISCONNECTED" }, { 0xC000020D, "STATUS_CONNECTION_RESET" }, { 0xC000020E, "STATUS_TOO_MANY_NODES" }, { 0xC000020F, "STATUS_TRANSACTION_ABORTED" }, { 0xC0000210, "STATUS_TRANSACTION_TIMED_OUT" }, { 0xC0000211, "STATUS_TRANSACTION_NO_RELEASE" }, { 0xC0000212, "STATUS_TRANSACTION_NO_MATCH" }, { 0xC0000213, "STATUS_TRANSACTION_RESPONDED" }, { 0xC0000214, "STATUS_TRANSACTION_INVALID_ID" }, { 0xC0000215, "STATUS_TRANSACTION_INVALID_TYPE" }, { 0xC0000216, "STATUS_NOT_SERVER_SESSION" }, { 0xC0000217, "STATUS_NOT_CLIENT_SESSION" }, { 0xC0000218, "STATUS_CANNOT_LOAD_REGISTRY_FILE" }, { 0xC0000219, "STATUS_DEBUG_ATTACH_FAILED" }, { 0xC000021A, "STATUS_SYSTEM_PROCESS_TERMINATED" }, { 0xC000021B, "STATUS_DATA_NOT_ACCEPTED" }, { 0xC000021C, "STATUS_NO_BROWSER_SERVERS_FOUND" }, { 0xC000021D, "STATUS_VDM_HARD_ERROR" }, { 0xC000021E, "STATUS_DRIVER_CANCEL_TIMEOUT" }, { 0xC000021F, "STATUS_REPLY_MESSAGE_MISMATCH" }, { 0xC0000220, "STATUS_MAPPED_ALIGNMENT" }, { 0xC0000221, "STATUS_IMAGE_CHECKSUM_MISMATCH" }, { 0xC0000222, "STATUS_LOST_WRITEBEHIND_DATA" }, { 0xC0000223, "STATUS_CLIENT_SERVER_PARAMETERS_INVALID" }, { 0xC0000224, "STATUS_PASSWORD_MUST_CHANGE" }, { 0xC0000225, "STATUS_NOT_FOUND" }, { 0xC0000226, "STATUS_NOT_TINY_STREAM" }, { 0xC0000227, "STATUS_RECOVERY_FAILURE" }, { 0xC0000228, "STATUS_STACK_OVERFLOW_READ" }, { 0xC0000229, "STATUS_FAIL_CHECK" }, { 0xC000022A, "STATUS_DUPLICATE_OBJECTID" }, { 0xC000022B, "STATUS_OBJECTID_EXISTS" }, { 0xC000022C, "STATUS_CONVERT_TO_LARGE" }, { 0xC000022D, "STATUS_RETRY" }, { 0xC000022E, "STATUS_FOUND_OUT_OF_SCOPE" }, { 0xC000022F, "STATUS_ALLOCATE_BUCKET" }, { 0xC0000230, "STATUS_PROPSET_NOT_FOUND" }, { 0xC0000231, "STATUS_MARSHALL_OVERFLOW" }, { 0xC0000232, "STATUS_INVALID_VARIANT" }, { 0xC0000233, "STATUS_DOMAIN_CONTROLLER_NOT_FOUND" }, { 0xC0000234, "STATUS_ACCOUNT_LOCKED_OUT" }, { 0xC0000235, "STATUS_HANDLE_NOT_CLOSABLE" }, { 0xC0000236, "STATUS_CONNECTION_REFUSED" }, { 0xC0000237, "STATUS_GRACEFUL_DISCONNECT" }, { 0xC0000238, "STATUS_ADDRESS_ALREADY_ASSOCIATED" }, { 0xC0000239, "STATUS_ADDRESS_NOT_ASSOCIATED" }, { 0xC000023A, "STATUS_CONNECTION_INVALID" }, { 0xC000023B, "STATUS_CONNECTION_ACTIVE" }, { 0xC000023C, "STATUS_NETWORK_UNREACHABLE" }, { 0xC000023D, "STATUS_HOST_UNREACHABLE" }, { 0xC000023E, "STATUS_PROTOCOL_UNREACHABLE" }, { 0xC000023F, "STATUS_PORT_UNREACHABLE" }, { 0xC0000240, "STATUS_REQUEST_ABORTED" }, { 0xC0000241, "STATUS_CONNECTION_ABORTED" }, { 0xC0000242, "STATUS_BAD_COMPRESSION_BUFFER" }, { 0xC0000243, "STATUS_USER_MAPPED_FILE" }, { 0xC0000244, "STATUS_AUDIT_FAILED" }, { 0xC0000245, "STATUS_TIMER_RESOLUTION_NOT_SET" }, { 0xC0000246, "STATUS_CONNECTION_COUNT_LIMIT" }, { 0xC0000247, "STATUS_LOGIN_TIME_RESTRICTION" }, { 0xC0000248, "STATUS_LOGIN_WKSTA_RESTRICTION" }, { 0xC0000249, "STATUS_IMAGE_MP_UP_MISMATCH" }, { 0xC0000250, "STATUS_INSUFFICIENT_LOGON_INFO" }, { 0xC0000251, "STATUS_BAD_DLL_ENTRYPOINT" }, { 0xC0000252, "STATUS_BAD_SERVICE_ENTRYPOINT" }, { 0xC0000253, "STATUS_LPC_REPLY_LOST" }, { 0xC0000254, "STATUS_IP_ADDRESS_CONFLICT1" }, { 0xC0000255, "STATUS_IP_ADDRESS_CONFLICT2" }, { 0xC0000256, "STATUS_REGISTRY_QUOTA_LIMIT" }, { 0xC0000257, "STATUS_PATH_NOT_COVERED" }, { 0xC0000258, "STATUS_NO_CALLBACK_ACTIVE" }, { 0xC0000259, "STATUS_LICENSE_QUOTA_EXCEEDED" }, { 0xC000025A, "STATUS_PWD_TOO_SHORT" }, { 0xC000025B, "STATUS_PWD_TOO_RECENT" }, { 0xC000025C, "STATUS_PWD_HISTORY_CONFLICT" }, { 0xC000025E, "STATUS_PLUGPLAY_NO_DEVICE" }, { 0xC000025F, "STATUS_UNSUPPORTED_COMPRESSION" }, { 0xC0000260, "STATUS_INVALID_HW_PROFILE" }, { 0xC0000261, "STATUS_INVALID_PLUGPLAY_DEVICE_PATH" }, { 0xC0000262, "STATUS_DRIVER_ORDINAL_NOT_FOUND" }, { 0xC0000263, "STATUS_DRIVER_ENTRYPOINT_NOT_FOUND" }, { 0xC0000264, "STATUS_RESOURCE_NOT_OWNED" }, { 0xC0000265, "STATUS_TOO_MANY_LINKS" }, { 0xC0000266, "STATUS_QUOTA_LIST_INCONSISTENT" }, { 0xC0000267, "STATUS_FILE_IS_OFFLINE" }, { 0xC0000268, "STATUS_EVALUATION_EXPIRATION" }, { 0xC0000269, "STATUS_ILLEGAL_DLL_RELOCATION" }, { 0xC000026A, "STATUS_LICENSE_VIOLATION" }, { 0xC000026B, "STATUS_DLL_INIT_FAILED_LOGOFF" }, { 0xC000026C, "STATUS_DRIVER_UNABLE_TO_LOAD" }, { 0xC000026D, "STATUS_DFS_UNAVAILABLE" }, { 0xC000026E, "STATUS_VOLUME_DISMOUNTED" }, { 0xC000026F, "STATUS_WX86_INTERNAL_ERROR" }, { 0xC0000270, "STATUS_WX86_FLOAT_STACK_CHECK" }, { 0xC0000271, "STATUS_VALIDATE_CONTINUE" }, { 0xC0000272, "STATUS_NO_MATCH" }, { 0xC0000273, "STATUS_NO_MORE_MATCHES" }, { 0xC0000275, "STATUS_NOT_A_REPARSE_POINT" }, { 0xC0000276, "STATUS_IO_REPARSE_TAG_INVALID" }, { 0xC0000277, "STATUS_IO_REPARSE_TAG_MISMATCH" }, { 0xC0000278, "STATUS_IO_REPARSE_DATA_INVALID" }, { 0xC0000279, "STATUS_IO_REPARSE_TAG_NOT_HANDLED" }, { 0xC0000280, "STATUS_REPARSE_POINT_NOT_RESOLVED" }, { 0xC0000281, "STATUS_DIRECTORY_IS_A_REPARSE_POINT" }, { 0xC0000282, "STATUS_RANGE_LIST_CONFLICT" }, { 0xC0000283, "STATUS_SOURCE_ELEMENT_EMPTY" }, { 0xC0000284, "STATUS_DESTINATION_ELEMENT_FULL" }, { 0xC0000285, "STATUS_ILLEGAL_ELEMENT_ADDRESS" }, { 0xC0000286, "STATUS_MAGAZINE_NOT_PRESENT" }, { 0xC0000287, "STATUS_REINITIALIZATION_NEEDED" }, { 0x80000288, "STATUS_DEVICE_REQUIRES_CLEANING" }, { 0x80000289, "STATUS_DEVICE_DOOR_OPEN" }, { 0xC000028A, "STATUS_ENCRYPTION_FAILED" }, { 0xC000028B, "STATUS_DECRYPTION_FAILED" }, { 0xC000028C, "STATUS_RANGE_NOT_FOUND" }, { 0xC000028D, "STATUS_NO_RECOVERY_POLICY" }, { 0xC000028E, "STATUS_NO_EFS" }, { 0xC000028F, "STATUS_WRONG_EFS" }, { 0xC0000290, "STATUS_NO_USER_KEYS" }, { 0xC0000291, "STATUS_FILE_NOT_ENCRYPTED" }, { 0xC0000292, "STATUS_NOT_EXPORT_FORMAT" }, { 0xC0000293, "STATUS_FILE_ENCRYPTED" }, { 0x40000294, "STATUS_WAKE_SYSTEM" }, { 0xC0000295, "STATUS_WMI_GUID_NOT_FOUND" }, { 0xC0000296, "STATUS_WMI_INSTANCE_NOT_FOUND" }, { 0xC0000297, "STATUS_WMI_ITEMID_NOT_FOUND" }, { 0xC0000298, "STATUS_WMI_TRY_AGAIN" }, { 0xC0000299, "STATUS_SHARED_POLICY" }, { 0xC000029A, "STATUS_POLICY_OBJECT_NOT_FOUND" }, { 0xC000029B, "STATUS_POLICY_ONLY_IN_DS" }, { 0xC000029C, "STATUS_VOLUME_NOT_UPGRADED" }, { 0xC000029D, "STATUS_REMOTE_STORAGE_NOT_ACTIVE" }, { 0xC000029E, "STATUS_REMOTE_STORAGE_MEDIA_ERROR" }, { 0xC000029F, "STATUS_NO_TRACKING_SERVICE" }, { 0xC00002A0, "STATUS_SERVER_SID_MISMATCH" }, { 0xC00002A1, "STATUS_DS_NO_ATTRIBUTE_OR_VALUE" }, { 0xC00002A2, "STATUS_DS_INVALID_ATTRIBUTE_SYNTAX" }, { 0xC00002A3, "STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED" }, { 0xC00002A4, "STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS" }, { 0xC00002A5, "STATUS_DS_BUSY" }, { 0xC00002A6, "STATUS_DS_UNAVAILABLE" }, { 0xC00002A7, "STATUS_DS_NO_RIDS_ALLOCATED" }, { 0xC00002A8, "STATUS_DS_NO_MORE_RIDS" }, { 0xC00002A9, "STATUS_DS_INCORRECT_ROLE_OWNER" }, { 0xC00002AA, "STATUS_DS_RIDMGR_INIT_ERROR" }, { 0xC00002AB, "STATUS_DS_OBJ_CLASS_VIOLATION" }, { 0xC00002AC, "STATUS_DS_CANT_ON_NON_LEAF" }, { 0xC00002AD, "STATUS_DS_CANT_ON_RDN" }, { 0xC00002AE, "STATUS_DS_CANT_MOD_OBJ_CLASS" }, { 0xC00002AF, "STATUS_DS_CROSS_DOM_MOVE_FAILED" }, { 0xC00002B0, "STATUS_DS_GC_NOT_AVAILABLE" }, { 0xC00002B1, "STATUS_DIRECTORY_SERVICE_REQUIRED" }, { 0xC00002B2, "STATUS_REPARSE_ATTRIBUTE_CONFLICT" }, { 0xC00002B3, "STATUS_CANT_ENABLE_DENY_ONLY" }, { 0xC00002B4, "STATUS_FLOAT_MULTIPLE_FAULTS" }, { 0xC00002B5, "STATUS_FLOAT_MULTIPLE_TRAPS" }, { 0xC00002B6, "STATUS_DEVICE_REMOVED" }, { 0xC00002B7, "STATUS_JOURNAL_DELETE_IN_PROGRESS" }, { 0xC00002B8, "STATUS_JOURNAL_NOT_ACTIVE" }, { 0xC00002B9, "STATUS_NOINTERFACE" }, { 0xC00002C1, "STATUS_DS_ADMIN_LIMIT_EXCEEDED" }, { 0xC00002C2, "STATUS_DRIVER_FAILED_SLEEP" }, { 0xC00002C3, "STATUS_MUTUAL_AUTHENTICATION_FAILED" }, { 0xC00002C4, "STATUS_CORRUPT_SYSTEM_FILE" }, { 0xC00002C5, "STATUS_DATATYPE_MISALIGNMENT_ERROR" }, { 0xC00002C6, "STATUS_WMI_READ_ONLY" }, { 0xC00002C7, "STATUS_WMI_SET_FAILURE" }, { 0xC00002C8, "STATUS_COMMITMENT_MINIMUM" }, { 0xC00002C9, "STATUS_REG_NAT_CONSUMPTION" }, { 0xC00002CA, "STATUS_TRANSPORT_FULL" }, { 0xC00002CB, "STATUS_DS_SAM_INIT_FAILURE" }, { 0xC00002CC, "STATUS_ONLY_IF_CONNECTED" }, { 0xC00002CD, "STATUS_DS_SENSITIVE_GROUP_VIOLATION" }, { 0xC00002CE, "STATUS_PNP_RESTART_ENUMERATION" }, { 0xC00002CF, "STATUS_JOURNAL_ENTRY_DELETED" }, { 0xC00002D0, "STATUS_DS_CANT_MOD_PRIMARYGROUPID" }, { 0xC00002D1, "STATUS_SYSTEM_IMAGE_BAD_SIGNATURE" }, { 0xC00002D2, "STATUS_PNP_REBOOT_REQUIRED" }, { 0xC00002D3, "STATUS_POWER_STATE_INVALID" }, { 0xC00002D4, "STATUS_DS_INVALID_GROUP_TYPE" }, { 0xC00002D5, "STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN" }, { 0xC00002D6, "STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN" }, { 0xC00002D7, "STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER" }, { 0xC00002D8, "STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER" }, { 0xC00002D9, "STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER" }, { 0xC00002DA, "STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER" }, { 0xC00002DB, "STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER" }, { 0xC00002DC, "STATUS_DS_HAVE_PRIMARY_MEMBERS" }, { 0xC00002DD, "STATUS_WMI_NOT_SUPPORTED" }, { 0xC00002DE, "STATUS_INSUFFICIENT_POWER" }, { 0xC00002DF, "STATUS_SAM_NEED_BOOTKEY_PASSWORD" }, { 0xC00002E0, "STATUS_SAM_NEED_BOOTKEY_FLOPPY" }, { 0xC00002E1, "STATUS_DS_CANT_START" }, { 0xC00002E2, "STATUS_DS_INIT_FAILURE" }, { 0xC00002E3, "STATUS_SAM_INIT_FAILURE" }, { 0xC00002E4, "STATUS_DS_GC_REQUIRED" }, { 0xC00002E5, "STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY" }, { 0xC00002E6, "STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS" }, { 0xC00002E7, "STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED" }, { 0xC00002E8, "STATUS_MULTIPLE_FAULT_VIOLATION" }, { 0xC0000300, "STATUS_NOT_SUPPORTED_ON_SBS" }, { 0xC0009898, "STATUS_WOW_ASSERTION" }, { 0xC0020001, "RPC_NT_INVALID_STRING_BINDING" }, { 0xC0020002, "RPC_NT_WRONG_KIND_OF_BINDING" }, { 0xC0020003, "RPC_NT_INVALID_BINDING" }, { 0xC0020004, "RPC_NT_PROTSEQ_NOT_SUPPORTED" }, { 0xC0020005, "RPC_NT_INVALID_RPC_PROTSEQ" }, { 0xC0020006, "RPC_NT_INVALID_STRING_UUID" }, { 0xC0020007, "RPC_NT_INVALID_ENDPOINT_FORMAT" }, { 0xC0020008, "RPC_NT_INVALID_NET_ADDR" }, { 0xC0020009, "RPC_NT_NO_ENDPOINT_FOUND" }, { 0xC002000A, "RPC_NT_INVALID_TIMEOUT" }, { 0xC002000B, "RPC_NT_OBJECT_NOT_FOUND" }, { 0xC002000C, "RPC_NT_ALREADY_REGISTERED" }, { 0xC002000D, "RPC_NT_TYPE_ALREADY_REGISTERED" }, { 0xC002000E, "RPC_NT_ALREADY_LISTENING" }, { 0xC002000F, "RPC_NT_NO_PROTSEQS_REGISTERED" }, { 0xC0020010, "RPC_NT_NOT_LISTENING" }, { 0xC0020011, "RPC_NT_UNKNOWN_MGR_TYPE" }, { 0xC0020012, "RPC_NT_UNKNOWN_IF" }, { 0xC0020013, "RPC_NT_NO_BINDINGS" }, { 0xC0020014, "RPC_NT_NO_PROTSEQS" }, { 0xC0020015, "RPC_NT_CANT_CREATE_ENDPOINT" }, { 0xC0020016, "RPC_NT_OUT_OF_RESOURCES" }, { 0xC0020017, "RPC_NT_SERVER_UNAVAILABLE" }, { 0xC0020018, "RPC_NT_SERVER_TOO_BUSY" }, { 0xC0020019, "RPC_NT_INVALID_NETWORK_OPTIONS" }, { 0xC002001A, "RPC_NT_NO_CALL_ACTIVE" }, { 0xC002001B, "RPC_NT_CALL_FAILED" }, { 0xC002001C, "RPC_NT_CALL_FAILED_DNE" }, { 0xC002001D, "RPC_NT_PROTOCOL_ERROR" }, { 0xC002001F, "RPC_NT_UNSUPPORTED_TRANS_SYN" }, { 0xC0020021, "RPC_NT_UNSUPPORTED_TYPE" }, { 0xC0020022, "RPC_NT_INVALID_TAG" }, { 0xC0020023, "RPC_NT_INVALID_BOUND" }, { 0xC0020024, "RPC_NT_NO_ENTRY_NAME" }, { 0xC0020025, "RPC_NT_INVALID_NAME_SYNTAX" }, { 0xC0020026, "RPC_NT_UNSUPPORTED_NAME_SYNTAX" }, { 0xC0020028, "RPC_NT_UUID_NO_ADDRESS" }, { 0xC0020029, "RPC_NT_DUPLICATE_ENDPOINT" }, { 0xC002002A, "RPC_NT_UNKNOWN_AUTHN_TYPE" }, { 0xC002002B, "RPC_NT_MAX_CALLS_TOO_SMALL" }, { 0xC002002C, "RPC_NT_STRING_TOO_LONG" }, { 0xC002002D, "RPC_NT_PROTSEQ_NOT_FOUND" }, { 0xC002002E, "RPC_NT_PROCNUM_OUT_OF_RANGE" }, { 0xC002002F, "RPC_NT_BINDING_HAS_NO_AUTH" }, { 0xC0020030, "RPC_NT_UNKNOWN_AUTHN_SERVICE" }, { 0xC0020031, "RPC_NT_UNKNOWN_AUTHN_LEVEL" }, { 0xC0020032, "RPC_NT_INVALID_AUTH_IDENTITY" }, { 0xC0020033, "RPC_NT_UNKNOWN_AUTHZ_SERVICE" }, { 0xC0020034, "EPT_NT_INVALID_ENTRY" }, { 0xC0020035, "EPT_NT_CANT_PERFORM_OP" }, { 0xC0020036, "EPT_NT_NOT_REGISTERED" }, { 0xC0020037, "RPC_NT_NOTHING_TO_EXPORT" }, { 0xC0020038, "RPC_NT_INCOMPLETE_NAME" }, { 0xC0020039, "RPC_NT_INVALID_VERS_OPTION" }, { 0xC002003A, "RPC_NT_NO_MORE_MEMBERS" }, { 0xC002003B, "RPC_NT_NOT_ALL_OBJS_UNEXPORTED" }, { 0xC002003C, "RPC_NT_INTERFACE_NOT_FOUND" }, { 0xC002003D, "RPC_NT_ENTRY_ALREADY_EXISTS" }, { 0xC002003E, "RPC_NT_ENTRY_NOT_FOUND" }, { 0xC002003F, "RPC_NT_NAME_SERVICE_UNAVAILABLE" }, { 0xC0020040, "RPC_NT_INVALID_NAF_ID" }, { 0xC0020041, "RPC_NT_CANNOT_SUPPORT" }, { 0xC0020042, "RPC_NT_NO_CONTEXT_AVAILABLE" }, { 0xC0020043, "RPC_NT_INTERNAL_ERROR" }, { 0xC0020044, "RPC_NT_ZERO_DIVIDE" }, { 0xC0020045, "RPC_NT_ADDRESS_ERROR" }, { 0xC0020046, "RPC_NT_FP_DIV_ZERO" }, { 0xC0020047, "RPC_NT_FP_UNDERFLOW" }, { 0xC0020048, "RPC_NT_FP_OVERFLOW" }, { 0xC0021007, "RPC_P_RECEIVE_ALERTED" }, { 0xC0021008, "RPC_P_CONNECTION_CLOSED" }, { 0xC0021009, "RPC_P_RECEIVE_FAILED" }, { 0xC002100A, "RPC_P_SEND_FAILED" }, { 0xC002100B, "RPC_P_TIMEOUT" }, { 0xC002100C, "RPC_P_SERVER_TRANSPORT_ERROR" }, { 0xC002100E, "RPC_P_EXCEPTION_OCCURED" }, { 0xC0021012, "RPC_P_CONNECTION_SHUTDOWN" }, { 0xC0021015, "RPC_P_THREAD_LISTENING" }, { 0xC0030001, "RPC_NT_NO_MORE_ENTRIES" }, { 0xC0030002, "RPC_NT_SS_CHAR_TRANS_OPEN_FAIL" }, { 0xC0030003, "RPC_NT_SS_CHAR_TRANS_SHORT_FILE" }, { 0xC0030004, "RPC_NT_SS_IN_NULL_CONTEXT" }, { 0xC0030005, "RPC_NT_SS_CONTEXT_MISMATCH" }, { 0xC0030006, "RPC_NT_SS_CONTEXT_DAMAGED" }, { 0xC0030007, "RPC_NT_SS_HANDLES_MISMATCH" }, { 0xC0030008, "RPC_NT_SS_CANNOT_GET_CALL_HANDLE" }, { 0xC0030009, "RPC_NT_NULL_REF_POINTER" }, { 0xC003000A, "RPC_NT_ENUM_VALUE_OUT_OF_RANGE" }, { 0xC003000B, "RPC_NT_BYTE_COUNT_TOO_SMALL" }, { 0xC003000C, "RPC_NT_BAD_STUB_DATA" }, { 0xC0020049, "RPC_NT_CALL_IN_PROGRESS" }, { 0xC002004A, "RPC_NT_NO_MORE_BINDINGS" }, { 0xC002004B, "RPC_NT_GROUP_MEMBER_NOT_FOUND" }, { 0xC002004C, "EPT_NT_CANT_CREATE" }, { 0xC002004D, "RPC_NT_INVALID_OBJECT" }, { 0xC002004F, "RPC_NT_NO_INTERFACES" }, { 0xC0020050, "RPC_NT_CALL_CANCELLED" }, { 0xC0020051, "RPC_NT_BINDING_INCOMPLETE" }, { 0xC0020052, "RPC_NT_COMM_FAILURE" }, { 0xC0020053, "RPC_NT_UNSUPPORTED_AUTHN_LEVEL" }, { 0xC0020054, "RPC_NT_NO_PRINC_NAME" }, { 0xC0020055, "RPC_NT_NOT_RPC_ERROR" }, { 0x40020056, "RPC_NT_UUID_LOCAL_ONLY" }, { 0xC0020057, "RPC_NT_SEC_PKG_ERROR" }, { 0xC0020058, "RPC_NT_NOT_CANCELLED" }, { 0xC0030059, "RPC_NT_INVALID_ES_ACTION" }, { 0xC003005A, "RPC_NT_WRONG_ES_VERSION" }, { 0xC003005B, "RPC_NT_WRONG_STUB_VERSION" }, { 0xC003005C, "RPC_NT_INVALID_PIPE_OBJECT" }, { 0xC003005D, "RPC_NT_INVALID_PIPE_OPERATION" }, { 0xC003005E, "RPC_NT_WRONG_PIPE_VERSION" }, { 0x400200AF, "RPC_NT_SEND_INCOMPLETE" }, { 0, NULL } }; /* * return an NT error string from a SMB buffer */ const char * nt_errstr(uint32_t err) { static char ret[128]; int i; ret[0] = 0; for (i = 0; nt_errors[i].name; i++) { if (err == nt_errors[i].code) return nt_errors[i].name; } snprintf(ret, sizeof(ret), "0x%08x", err); return ret; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2639_0
crossvul-cpp_data_bad_181_0
/* radare - Apache 2.0 - Copyright 2010-2015 - pancake and Adam Pridgen <dso@rice.edu || adam.pridgen@thecoverofnight.com> */ #include <string.h> #include <r_types.h> #include <r_lib.h> #include <r_asm.h> #include <r_anal.h> #include <r_anal_ex.h> #include <r_cons.h> #include "../../../shlr/java/code.h" #include "../../../shlr/java/class.h" #ifdef IFDBG #define dprintf eprintf #endif #define DO_THE_DBG 0 #define IFDBG if(DO_THE_DBG) #define IFINT if(0) struct r_anal_java_access_t; typedef struct r_anal_java_access_t { char *method; ut64 addr; ut64 value; ut64 op_type; struct r_anal_java_access_t *next; struct r_anal_java_access_t *previous; } RAnalJavaAccess; typedef struct r_anal_java_local_var_t { char *name; char *type; RList *writes; RList *reads; RList *binops; } RAnalJavaLocalVar; typedef struct r_anal_ex_java_lin_sweep { RList *cfg_node_addrs; }RAnalJavaLinearSweep; ut64 METHOD_START = 0; // XXX - TODO add code in the java_op that is aware of when it is in a // switch statement, like in the shlr/java/code.c so that this does not // report bad blocks. currently is should be easy to ignore these blocks, // in output for the pdj //static int java_print_ssa_bb (RAnal *anal, char *addr); static int java_reset_counter (RAnal *anal, ut64 addr); static int java_new_method (ut64 addr); static void java_update_anal_types (RAnal *anal, RBinJavaObj *bin_obj); static void java_set_function_prototype (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method); static int java_cmd_ext(RAnal *anal, const char* input); static int analyze_from_code_buffer (RAnal *anal, RAnalFunction *fcn, ut64 addr, const ut8 *code_buf, ut64 code_length); static int analyze_from_code_attr (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method, ut64 loadaddr); static int analyze_method(RAnal *anal, RAnalFunction *fcn, RAnalState *state); static int java_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len); //static int java_bb(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut8 *buf, ut64 len, int reftype); //static int java_fn(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut8 *buf, ut64 len, int reftype); static int java_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr); static int handle_bb_cf_recursive_descent (RAnal *anal, RAnalState *state); static int java_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr); static int handle_bb_cf_linear_sweep (RAnal *anal, RAnalState *state); static int java_post_anal_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr); static RBinJavaObj * get_java_bin_obj(RAnal *anal); static RList * get_java_bin_obj_list(RAnal *anal); static int java_analyze_fns( RAnal *anal, ut64 start, ut64 end, int reftype, int depth); //static RAnalOp * java_op_from_buffer(RAnal *anal, RAnalState *state, ut64 addr); //static RAnalBlock * java_bb_from_buffer(RAnal *anal, RAnalState *state, ut64 addr); //static RAnalFunction * java_fn_from_buffer(RAnal *anal, RAnalState *state, ut64 addr); static int check_addr_in_code (RBinJavaField *method, ut64 addr); static int check_addr_less_end (RBinJavaField *method, ut64 addr); static int check_addr_less_start (RBinJavaField *method, ut64 addr); static int java_revisit_bb_anal_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr); static RBinJavaObj * get_java_bin_obj(RAnal *anal) { RBin *b = anal->binb.bin; RBinPlugin *plugin = b->cur && b->cur->o ? b->cur->o->plugin : NULL; ut8 is_java = (plugin && strcmp (plugin->name, "java") == 0) ? 1 : 0; return is_java ? b->cur->o->bin_obj : NULL; } static RList * get_java_bin_obj_list(RAnal *anal) { RBinJavaObj *bin_obj = (RBinJavaObj * )get_java_bin_obj(anal); // See libr/bin/p/bin_java.c to see what is happening here. The original intention // was to use a shared global db variable from shlr/java/class.c, but the // BIN_OBJS_ADDRS variable kept getting corrupted on Mac, so I (deeso) switched the // way the access to the db was taking place by using the bin_obj as a proxy back // to the BIN_OBJS_ADDRS which is instantiated in libr/bin/p/bin_java.c // not the easiest way to make sausage, but its getting made. return r_bin_java_get_bin_obj_list_thru_obj (bin_obj); } static int check_addr_less_end (RBinJavaField *method, ut64 addr) { ut64 end = r_bin_java_get_method_code_size (method); return (addr < end); } static int check_addr_in_code (RBinJavaField *method, ut64 addr) { return !check_addr_less_start (method, addr) && \ check_addr_less_end ( method, addr); } static int check_addr_less_start (RBinJavaField *method, ut64 addr) { ut64 start = r_bin_java_get_method_code_offset (method); return (addr < start); } static int java_new_method (ut64 method_start) { METHOD_START = method_start; // reset the current bytes consumed counter r_java_new_method (); return 0; } static ut64 java_get_method_start () { return METHOD_START; } static int java_revisit_bb_anal_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr) { RAnalBlock *current_head = state && state->current_bb_head ? state->current_bb_head : NULL; if (current_head && state->current_bb && state->current_bb->type & R_ANAL_BB_TYPE_TAIL) { r_anal_ex_update_bb_cfg_head_tail (current_head, current_head, state->current_bb); // XXX should i do this instead -> r_anal_ex_perform_post_anal_bb_cb (anal, state, addr+offset); state->done = 1; } return R_ANAL_RET_END; } static int java_recursive_descent(RAnal *anal, RAnalState *state, ut64 addr) { RAnalBlock *bb; RAnalBlock *current_head; if (!anal || !state || !state->current_bb || state->current_bb_head) return 0; bb = state->current_bb; current_head = state->current_bb_head; if (current_head && state->current_bb->type & R_ANAL_BB_TYPE_TAIL) { r_anal_ex_update_bb_cfg_head_tail (current_head, current_head, state->current_bb); } // basic filter for handling the different type of operations // depending on flags some may be called more than once // if (bb->type2 & R_ANAL_EX_ILL_OP) handle_bb_ill_op (anal, state); // if (bb->type2 & R_ANAL_EX_COND_OP) handle_bb_cond_op (anal, state); // if (bb->type2 & R_ANAL_EX_UNK_OP) handle_bb_unknown_op (anal, state); // if (bb->type2 & R_ANAL_EX_NULL_OP) handle_bb_null_op (anal, state); // if (bb->type2 & R_ANAL_EX_NOP_OP) handle_bb_nop_op (anal, state); // if (bb->type2 & R_ANAL_EX_REP_OP) handle_bb_rep_op (anal, state); // if (bb->type2 & R_ANAL_EX_STORE_OP) handle_bb_store_op (anal, state); // if (bb->type2 & R_ANAL_EX_LOAD_OP) handle_bb_load_op (anal, state // if (bb->type2 & R_ANAL_EX_REG_OP) handle_bb_reg_op (anal, state); // if (bb->type2 & R_ANAL_EX_OBJ_OP) handle_bb_obj_op (anal, state); // if (bb->type2 & R_ANAL_EX_STACK_OP) handle_bb_stack_op (anal, state); // if (bb->type2 & R_ANAL_EX_BIN_OP) handle_bb_bin_op (anal, state); if (bb->type2 & R_ANAL_EX_CODE_OP) handle_bb_cf_recursive_descent (anal, state); // if (bb->type2 & R_ANAL_EX_DATA_OP) handle_bb_data_op (anal, state); return 0; } static int java_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr) { RAnalBlock *bb = state->current_bb; if (state->current_bb_head && state->current_bb->type & R_ANAL_BB_TYPE_TAIL) { //r_anal_ex_update_bb_cfg_head_tail (state->current_bb_head, state->current_bb_head, state->current_bb); } // basic filter for handling the different type of operations // depending on flags some may be called more than once // if (bb->type2 & R_ANAL_EX_ILL_OP) handle_bb_ill_op (anal, state); // if (bb->type2 & R_ANAL_EX_COND_OP) handle_bb_cond_op (anal, state); // if (bb->type2 & R_ANAL_EX_UNK_OP) handle_bb_unknown_op (anal, state); // if (bb->type2 & R_ANAL_EX_NULL_OP) handle_bb_null_op (anal, state); // if (bb->type2 & R_ANAL_EX_NOP_OP) handle_bb_nop_op (anal, state); // if (bb->type2 & R_ANAL_EX_REP_OP) handle_bb_rep_op (anal, state); // if (bb->type2 & R_ANAL_EX_STORE_OP) handle_bb_store_op (anal, state); // if (bb->type2 & R_ANAL_EX_LOAD_OP) handle_bb_load_op (anal, state // if (bb->type2 & R_ANAL_EX_REG_OP) handle_bb_reg_op (anal, state); // if (bb->type2 & R_ANAL_EX_OBJ_OP) handle_bb_obj_op (anal, state); // if (bb->type2 & R_ANAL_EX_STACK_OP) handle_bb_stack_op (anal, state); // if (bb->type2 & R_ANAL_EX_BIN_OP) handle_bb_bin_op (anal, state); if (bb->type2 & R_ANAL_EX_CODE_OP) handle_bb_cf_linear_sweep (anal, state); // if (bb->type2 & R_ANAL_EX_DATA_OP) handle_bb_data_op (anal, state); return 0; } static int handle_bb_cf_recursive_descent (RAnal *anal, RAnalState *state) { RAnalBlock *bb = state->current_bb; ut64 addr = 0; int result = 0; if (!bb) { eprintf ("Error: unable to handle basic block @ 0x%08"PFMT64x"\n", addr); return R_ANAL_RET_ERROR; } else if (state->max_depth <= state->current_depth) { return R_ANAL_RET_ERROR; } state->current_depth++; addr = bb->addr; IFDBG eprintf ("Handling a control flow change @ 0x%04"PFMT64x".\n", addr); ut64 control_type = r_anal_ex_map_anal_ex_to_anal_op_type (bb->type2); // XXX - transition to type2 control flow condtions switch (control_type) { case R_ANAL_OP_TYPE_CALL: IFDBG eprintf (" - Handling a call @ 0x%04"PFMT64x".\n", addr); r_anal_xrefs_set (anal, bb->addr, bb->jump, R_ANAL_REF_TYPE_CALL); result = R_ANAL_RET_ERROR; break; case R_ANAL_OP_TYPE_JMP: { RList * jmp_list; IFDBG eprintf (" - Handling a jmp @ 0x%04"PFMT64x" to 0x%04"PFMT64x".\n", addr, bb->jump); // visited some other time if (!r_anal_state_search_bb (state, bb->jump)) { jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump ); if (jmp_list) bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); if (bb->jumpbb) bb->jump = bb->jumpbb->addr; } else { bb->jumpbb = r_anal_state_search_bb (state, bb->jump); if (bb->jumpbb) bb->jump = bb->jumpbb->addr; } if (state->done == 1) { IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr); } result = R_ANAL_RET_END; } break; case R_ANAL_OP_TYPE_CJMP: { RList *jmp_list; ut8 encountered_stop = 0; IFDBG eprintf (" - Handling a cjmp @ 0x%04"PFMT64x" jmp to 0x%04"PFMT64x" and fail to 0x%04"PFMT64x".\n", addr, bb->jump, bb->fail); IFDBG eprintf (" - Handling jmp to 0x%04"PFMT64x".\n", bb->jump); // visited some other time if (!r_anal_state_search_bb (state, bb->jump)) { jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump ); if (jmp_list) bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); if (bb->jumpbb) { bb->jump = bb->jumpbb->addr; } } else { bb->jumpbb = r_anal_state_search_bb (state, bb->jump); bb->jump = bb->jumpbb->addr; } if (state->done == 1) { IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr); state->done = 0; encountered_stop = 1; } if (!r_anal_state_search_bb (state, bb->fail)) { jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->fail ); if (jmp_list) bb->failbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); if (bb->failbb) { bb->fail = bb->failbb->addr; } } else { bb->failbb = r_anal_state_search_bb (state, bb->fail); if (bb->failbb) { bb->fail = bb->failbb->addr; } } IFDBG eprintf (" - Handling an cjmp @ 0x%04"PFMT64x" jmp to 0x%04"PFMT64x" and fail to 0x%04"PFMT64x".\n", addr, bb->jump, bb->fail); IFDBG eprintf (" - Handling fail to 0x%04"PFMT64x".\n", bb->fail); // r_anal_state_merge_bb_list (state, fail_list); if (state->done == 1) { IFDBG eprintf (" Looks like this fail (bb @ 0x%04"PFMT64x") found a return.\n", addr); } result = R_ANAL_RET_END; if (encountered_stop) state->done = 1; } break; case R_ANAL_OP_TYPE_SWITCH: { IFDBG eprintf (" - Handling an switch @ 0x%04"PFMT64x".\n", addr); if (bb->switch_op) { RAnalCaseOp *caseop; RListIter *iter; RList *jmp_list = NULL; ut8 encountered_stop = 0; r_list_foreach (bb->switch_op->cases, iter, caseop) { if (caseop) { if (r_anal_state_addr_is_valid (state, caseop->jump) ) { jmp_list = r_anal_ex_perform_analysis ( anal, state, caseop->jump ); if (jmp_list) caseop->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); if (state->done == 1) { IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr); state->done = 0; encountered_stop = 1; } } } } r_list_free (jmp_list); if (encountered_stop) state->done = 1; } result = R_ANAL_RET_END; } break; case R_ANAL_OP_TYPE_TRAP: case R_ANAL_OP_TYPE_UJMP: case R_ANAL_OP_TYPE_IJMP: case R_ANAL_OP_TYPE_RJMP: case R_ANAL_OP_TYPE_IRJMP: case R_ANAL_OP_TYPE_RET: case R_ANAL_OP_TYPE_ILL: IFDBG eprintf (" - Handling an ret @ 0x%04"PFMT64x".\n", addr); state->done = 1; result = R_ANAL_RET_END; break; default: break; } state->current_depth--; return result; } static int java_post_anal_linear_sweep(RAnal *anal, RAnalState *state, ut64 addr) { RAnalJavaLinearSweep *nodes = state->user_state; RList *jmp_list = NULL; ut64 *paddr64; state->done = 0; if (!nodes || !nodes->cfg_node_addrs) { state->done = 1; return R_ANAL_RET_ERROR; } while (r_list_length (nodes->cfg_node_addrs) > 0) { paddr64 = r_list_get_n (nodes->cfg_node_addrs, 0); r_list_del_n (nodes->cfg_node_addrs, 0); if (paddr64 && !r_anal_state_search_bb (state, *paddr64)) { ut64 list_length = 0; IFDBG eprintf (" - Visiting 0x%04"PFMT64x" for analysis.\n", *paddr64); jmp_list = r_anal_ex_perform_analysis ( anal, state, *paddr64 ); list_length = r_list_length (jmp_list); r_list_free (jmp_list); if ( list_length > 0) { IFDBG eprintf (" - Found %"PFMT64d" more basic blocks missed on the initial pass.\n", *paddr64); } } } return R_ANAL_RET_END; } static int handle_bb_cf_linear_sweep (RAnal *anal, RAnalState *state) { ut64 * paddr64; RAnalBlock *bb = state->current_bb; RAnalJavaLinearSweep *nodes = state->user_state; if (!nodes || !nodes->cfg_node_addrs) { state->done = 1; return R_ANAL_RET_ERROR; } ut64 addr = 0; int result = 0; if (!bb) { eprintf ("Error: unable to handle basic block @ 0x%08"PFMT64x"\n", addr); return R_ANAL_RET_ERROR; } else if (state->max_depth <= state->current_depth) { return R_ANAL_RET_ERROR; } state->current_depth++; addr = bb->addr; IFDBG eprintf ("Handling a control flow change @ 0x%04"PFMT64x".\n", addr); ut32 control_type = r_anal_ex_map_anal_ex_to_anal_op_type (bb->type2); // XXX - transition to type2 control flow condtions switch (control_type) { case R_ANAL_OP_TYPE_CALL: IFDBG eprintf (" - Handling a call @ 0x%04"PFMT64x"\n", addr); r_anal_xrefs_set (anal, bb->addr, bb->jump, R_ANAL_REF_TYPE_CALL); result = R_ANAL_RET_ERROR; break; case R_ANAL_OP_TYPE_JMP: paddr64 = malloc (sizeof(ut64)); *paddr64 = bb->jump; IFDBG eprintf (" - Handling a jmp @ 0x%04"PFMT64x", adding for future visit\n", addr); r_list_append (nodes->cfg_node_addrs, paddr64); result = R_ANAL_RET_END; break; case R_ANAL_OP_TYPE_CJMP: paddr64 = malloc (sizeof(ut64)); *paddr64 = bb->jump; IFDBG eprintf (" - Handling a bb->jump @ 0x%04"PFMT64x", adding 0x%04"PFMT64x" for future visit\n", addr, *paddr64); r_list_append (nodes->cfg_node_addrs, paddr64); paddr64 = malloc (sizeof(ut64)); if (paddr64) { *paddr64 = bb->fail; IFDBG eprintf (" - Handling a bb->fail @ 0x%04"PFMT64x", adding 0x%04"PFMT64x" for future visit\n", addr, *paddr64); r_list_append (nodes->cfg_node_addrs, paddr64); } result = R_ANAL_RET_END; break; case R_ANAL_OP_TYPE_SWITCH: if (bb->switch_op) { RAnalCaseOp *caseop; RListIter *iter; //RList *jmp_list = NULL; IFDBG eprintf (" - Handling a switch_op @ 0x%04"PFMT64x":\n", addr); r_list_foreach (bb->switch_op->cases, iter, caseop) { ut64 * paddr64; if (caseop) { paddr64 = malloc (sizeof(ut64)); *paddr64 = caseop->jump; IFDBG eprintf ("Adding 0x%04"PFMT64x" for future visit\n", *paddr64); r_list_append (nodes->cfg_node_addrs, paddr64); } } } result = R_ANAL_RET_END; break; case R_ANAL_OP_TYPE_TRAP: case R_ANAL_OP_TYPE_UJMP: case R_ANAL_OP_TYPE_RJMP: case R_ANAL_OP_TYPE_IJMP: case R_ANAL_OP_TYPE_IRJMP: case R_ANAL_OP_TYPE_RET: IFDBG eprintf (" - Handling an ret @ 0x%04"PFMT64x".\n", addr); state->done = 1; result = R_ANAL_RET_END; break; default: break; } state->current_depth--; return result; } //many flaws UAF static int analyze_from_code_buffer(RAnal *anal, RAnalFunction *fcn, ut64 addr, const ut8 *code_buf, ut64 code_length) { char gen_name[1025]; RListIter *bb_iter; RAnalBlock *bb; ut64 actual_size = 0; RAnalState *state = NULL; int result = R_ANAL_RET_ERROR; RAnalJavaLinearSweep *nodes; free (fcn->name); free (fcn->dsc); snprintf (gen_name, 1024, "sym.%08"PFMT64x"", addr); fcn->name = strdup (gen_name); fcn->dsc = strdup ("unknown"); r_anal_fcn_set_size (NULL, fcn, code_length); fcn->type = R_ANAL_FCN_TYPE_FCN; fcn->addr = addr; state = r_anal_state_new (addr, (ut8*) code_buf, code_length); nodes = R_NEW0 (RAnalJavaLinearSweep); nodes->cfg_node_addrs = r_list_new (); nodes->cfg_node_addrs->free = free; state->user_state = nodes; result = analyze_method (anal, fcn, state); r_list_foreach (fcn->bbs, bb_iter, bb) { actual_size += bb->size; } r_anal_fcn_set_size (NULL, fcn, state->bytes_consumed); result = state->anal_ret_val; r_list_free (nodes->cfg_node_addrs); free (nodes); //leak to avoid UAF is the easy solution otherwise a whole rewrite is needed //r_anal_state_free (state); if (r_anal_fcn_size (fcn) != code_length) { return R_ANAL_RET_ERROR; #if 0 eprintf ("WARNING Analysis of %s Incorrect: Code Length: 0x%"PFMT64x", Function size reported 0x%x\n", fcn->name, code_length, r_anal_fcn_size(fcn)); eprintf ("Deadcode detected, setting code length to: 0x%"PFMT64x"\n", code_length); r_anal_fcn_set_size (fcn, code_length); #endif } return result; } static int analyze_from_code_attr (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method, ut64 loadaddr) { RBinJavaAttrInfo* code_attr = method ? r_bin_java_get_method_code_attribute(method) : NULL; ut8 * code_buf = NULL; int result = false; ut64 code_length = 0; ut64 code_addr = -1; if (!code_attr) { fcn->name = strdup ("sym.UNKNOWN"); fcn->dsc = strdup ("unknown"); r_anal_fcn_set_size (NULL, fcn, code_length); fcn->type = R_ANAL_FCN_TYPE_FCN; fcn->addr = 0; return R_ANAL_RET_ERROR; } code_length = code_attr->info.code_attr.code_length; code_addr = code_attr->info.code_attr.code_offset; code_buf = calloc (1, code_length); anal->iob.read_at (anal->iob.io, code_addr + loadaddr, code_buf, code_length); result = analyze_from_code_buffer (anal, fcn, code_addr + loadaddr, code_buf, code_length); free (code_buf); char *name = strdup (method->name); if (name) { r_name_filter (name, 80); free (fcn->name); if (method->class_name) { char *cname = strdup (method->class_name); r_name_filter (cname, 50); fcn->name = r_str_newf ("sym.%s.%s", cname, name); free (cname); } else { fcn->name = r_str_newf ("sym.%s", name); } free (name); } free (fcn->dsc); fcn->dsc = strdup (method->descriptor); IFDBG eprintf ("Completed analysing code from attr, name: %s, desc: %s", fcn->name, fcn->dsc); return result; } static int analyze_method(RAnal *anal, RAnalFunction *fcn, RAnalState *state) { // deallocate niceties r_list_free (fcn->bbs); fcn->bbs = r_anal_bb_list_new (); java_new_method (fcn->addr); state->current_fcn = fcn; // Not a resource leak. Basic blocks should be stored in the state->fcn // TODO: ? RList *bbs = r_anal_ex_perform_analysis (anal, state, fcn->addr); return state->anal_ret_val; } static int java_analyze_fns_from_buffer( RAnal *anal, ut64 start, ut64 end, int reftype, int depth) { int result = R_ANAL_RET_ERROR; ut64 addr = start; ut64 offset = 0; ut64 buf_len = end - start; ut8 analyze_all = 0, *buffer = NULL; if (end == UT64_MAX) { //analyze_all = 1; buf_len = anal->iob.desc_size (anal->iob.io->desc); if (buf_len == UT64_MAX) buf_len = 1024; end = start + buf_len; } buffer = malloc (buf_len); if (!buffer) { return R_ANAL_RET_ERROR; } anal->iob.read_at (anal->iob.io, addr, buffer, buf_len); while (offset < buf_len) { ut64 length = buf_len - offset; RAnalFunction *fcn = r_anal_fcn_new (); fcn->cc = r_str_const (r_anal_cc_default (anal)); result = analyze_from_code_buffer ( anal, fcn, addr, buffer+offset, length ); if (result == R_ANAL_RET_ERROR) { eprintf ("Failed to parse java fn: %s @ 0x%04"PFMT64x"\n", fcn->name, fcn->addr); // XXX - TO Stop or not to Stop ?? break; } //r_listrange_add (anal->fcnstore, fcn); r_anal_fcn_tree_insert (&anal->fcn_tree, fcn); r_list_append (anal->fcns, fcn); offset += r_anal_fcn_size (fcn); if (!analyze_all) break; } free (buffer); return result; } static int java_analyze_fns( RAnal *anal, ut64 start, ut64 end, int reftype, int depth) { //anal->iob.read_at (anal->iob.io, op.jump, bbuf, sizeof (bbuf)); RBinJavaObj *bin = NULL;// = get_java_bin_obj (anal); RBinJavaField *method = NULL; RListIter *methods_iter, *bin_obs_iter; RList * bin_objs_list = get_java_bin_obj_list (anal); ut8 analyze_all = 0; //RAnalRef *ref = NULL; int result = R_ANAL_RET_ERROR; if (end == UT64_MAX) { analyze_all = 1; } if (!bin_objs_list || r_list_empty (bin_objs_list)) { r_list_free (bin_objs_list); return java_analyze_fns_from_buffer (anal, start, end, reftype, depth); } r_list_foreach (bin_objs_list, bin_obs_iter, bin) { // loop over all bin object that are loaded java_update_anal_types (anal, bin); RList *methods_list = (RList *) r_bin_java_get_methods_list (bin); ut64 loadaddr = bin->loadaddr; // loop over all methods in the binary object and analyse // the functions r_list_foreach (methods_list, methods_iter, method) { if ((method && analyze_all) || (check_addr_less_start (method, end) || check_addr_in_code (method, end))) { RAnalFunction *fcn = r_anal_fcn_new (); fcn->cc = r_str_const (r_anal_cc_default (anal)); java_set_function_prototype (anal, fcn, method); result = analyze_from_code_attr (anal, fcn, method, loadaddr); if (result == R_ANAL_RET_ERROR) { //eprintf ("Failed to parse java fn: %s @ 0x%04"PFMT64x"\n", fcn->name, fcn->addr); return result; // XXX - TO Stop or not to Stop ?? } //r_listrange_add (anal->fcnstore, fcn); r_anal_fcn_update_tinyrange_bbs (fcn); r_anal_fcn_tree_insert (&anal->fcn_tree, fcn); r_list_append (anal->fcns, fcn); } } // End of methods loop }// end of bin_objs list loop return result; } /*static int java_fn(RAnal *anal, RAnalFunction *fcn, ut64 addr, ut8 *buf, ut64 len, int reftype) { // XXX - this may clash with malloc:// uris because the file name is // malloc:// ** RBinJavaObj *bin = (RBinJavaObj *) get_java_bin_obj (anal); RBinJavaField *method = bin ? r_bin_java_get_method_code_attribute_with_addr (bin, addr) : NULL; ut64 loadaddr = bin ? bin->loadaddr : 0; IFDBG eprintf ("Analyzing java functions for %s\n", anal->iob.io->fd->name); if (method) return analyze_from_code_attr (anal, fcn, method, loadaddr); return analyze_from_code_buffer (anal, fcn, addr, buf, len); }*/ static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { ut8 op_byte = data[0]; ut64 offset = addr - java_get_method_start (); ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1; if (op_byte == 0xaa) { // handle a table switch condition if (pos + 8 > len) { return op->size; } int min_val = (ut32)(UINT (data, pos + 4)), max_val = (ut32)(UINT (data, pos + 8)); ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc); RAnalCaseOp *caseop = NULL; pos += 12; if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) { //caseop = r_anal_switch_op_add_case(op->switch_op, addr+default_loc, -1, addr+offset); for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) { //ut32 value = (ut32)(UINT (data, pos)); if (pos + 4 >= len) { // switch is too big cant read further break; } int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos)); caseop = r_anal_switch_op_add_case (op->switch_op, addr + pos, cur_case + min_val, addr + offset); if (caseop) { caseop->bb_ref_to = addr+offset; caseop->bb_ref_from = addr; // TODO figure this one out } } } else { eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr); } } op->size = pos; return op->size; } static int java_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { /* get opcode size */ //ut8 op_byte = data[0]; ut8 op_byte = data[0]; int sz = JAVA_OPS[op_byte].size; if (!op) { return sz; } memset (op, '\0', sizeof (RAnalOp)); IFDBG { //eprintf ("Extracting op from buffer (%d byte(s)) @ 0x%04x\n", len, addr); //eprintf ("Parsing op: (0x%02x) %s.\n", op_byte, JAVA_OPS[op_byte].name); } op->addr = addr; op->size = sz; op->id = data[0]; op->type2 = JAVA_OPS[op_byte].op_type; op->type = r_anal_ex_map_anal_ex_to_anal_op_type (op->type2); // handle lookup and table switch offsets if (op_byte == 0xaa || op_byte == 0xab) { java_switch_op (anal, op, addr, data, len); // IN_SWITCH_OP = 1; } /* TODO: // not sure how to handle the states for IN_SWITCH_OP, SWITCH_OP_CASES, // and NUM_CASES_SEEN, because these are dependent on whether or not we // are in a switch, and given the non-reentrant state of opcode analysis // this can't always be guaranteed. Below is the pseudo code for handling // the easy parts though if (IN_SWITCH_OP) { NUM_CASES_SEEN++; if (NUM_CASES_SEEN == SWITCH_OP_CASES) IN_SWITCH_OP=0; op->addr = addr; op->size = 4; op->type2 = 0; op->type = R_ANAL_OP_TYPE_CASE op->eob = 0; return op->sizes; } */ op->eob = r_anal_ex_is_op_type_eop (op->type2); IFDBG { const char *ot_str = r_anal_optype_to_string (op->type); eprintf ("op_type2: %s @ 0x%04"PFMT64x" 0x%08"PFMT64x" op_type: (0x%02"PFMT64x") %s.\n", JAVA_OPS[op_byte].name, addr, (ut64)op->type2, (ut64)op->type, ot_str); //eprintf ("op_eob: 0x%02x.\n", op->eob); //eprintf ("op_byte @ 0: 0x%02x op_byte @ 0x%04x: 0x%02x.\n", data[0], addr, data[addr]); } if (len < 4) { // incomplete analysis here return 0; } if (op->type == R_ANAL_OP_TYPE_CJMP) { op->jump = addr + (short)(USHORT (data, 1)); op->fail = addr + sz; IFDBG eprintf ("%s jmpto 0x%04"PFMT64x" failto 0x%04"PFMT64x".\n", JAVA_OPS[op_byte].name, op->jump, op->fail); } else if (op->type == R_ANAL_OP_TYPE_JMP) { op->jump = addr + (short)(USHORT (data, 1)); IFDBG eprintf ("%s jmpto 0x%04"PFMT64x".\n", JAVA_OPS[op_byte].name, op->jump); } else if ( (op->type & R_ANAL_OP_TYPE_CALL) == R_ANAL_OP_TYPE_CALL ) { op->jump = (int)(short)(USHORT (data, 1)); op->fail = addr + sz; //IFDBG eprintf ("%s callto 0x%04x failto 0x%04x.\n", JAVA_OPS[op_byte].name, op->jump, op->fail); } //r_java_disasm(addr, data, len, output, outlen); //IFDBG eprintf ("%s\n", output); return op->size; } /* static RAnalOp * java_op_from_buffer(RAnal *anal, RAnalState *state, ut64 addr) { RAnalOp *op = r_anal_op_new (); // get opcode size if (!op) return 0; memset (op, '\0', sizeof (RAnalOp)); java_op (anal, op, addr, state->buffer, state->len - (addr - state->start) ); return op; } */ static void java_set_function_prototype (RAnal *anal, RAnalFunction *fcn, RBinJavaField *method) { RList *the_list = r_bin_java_extract_type_values (method->descriptor); Sdb *D = anal->sdb_types; Sdb *A = anal->sdb_args; const char *type_fmt = "%08"PFMT64x".arg.%d.type", *namek_fmt = "%08"PFMT64x".var.%d.name", *namev_fmt = "%08"PFMT64x"local.%d"; char key_buf[1024], value_buf [1024]; RListIter *iter; char *str; if (the_list) { ut8 start = 0, stop = 0; int idx = 0; r_list_foreach (the_list, iter, str) { IFDBG eprintf ("Adding type: %s to known types.\n", str); if (str && *str == '('){ start = 1; continue; } if (str && start && *str != ')') { // set type // set arg type snprintf (key_buf, sizeof(key_buf)-1, type_fmt, (ut64)fcn->addr, idx); sdb_set (A, str, key_buf, 0); sdb_set (D, str, "type", 0); // set value snprintf (key_buf, sizeof(key_buf)-1, namek_fmt, fcn->addr, idx); snprintf (value_buf, sizeof(value_buf)-1, namev_fmt, fcn->addr, idx); sdb_set (A, value_buf, key_buf, 0); idx ++; } if (start && str && *str == ')') { stop = 1; continue; } if ((start & stop & 1) && str) { sdb_set (A, str, "ret.type", 0); sdb_set (D, str, "type", 0); } } r_list_free (the_list); } } static void java_update_anal_types (RAnal *anal, RBinJavaObj *bin_obj) { Sdb *D = anal->sdb_types; if (D && bin_obj) { RListIter *iter; char *str; RList * the_list = r_bin_java_extract_all_bin_type_values (bin_obj); if (the_list) { r_list_foreach (the_list, iter, str) { IFDBG eprintf ("Adding type: %s to known types.\n", str); if (str) sdb_set (D, str, "type", 0); } } r_list_free (the_list); } } static int java_cmd_ext(RAnal *anal, const char* input) { RBinJavaObj *obj = (RBinJavaObj *) get_java_bin_obj (anal); if (!obj) { eprintf ("Execute \"af\" to set the current bin, and this will bind the current bin\n"); return -1; } switch (*input) { case 'c': // reset bytes counter for case operations r_java_new_method (); break; case 'u': switch (*(input+1)) { case 't': {java_update_anal_types (anal, obj); return true;} default: break; } break; case 's': switch (*(input+1)) { //case 'e': return java_resolve_cp_idx_b64 (anal, input+2); default: break; } break; default: eprintf("Command not supported"); break; } return 0; } static int java_reset_counter (RAnal *anal, ut64 start_addr ) { IFDBG eprintf ("Setting the new METHOD_START to 0x%08"PFMT64x" was 0x%08"PFMT64x"\n", start_addr, METHOD_START); METHOD_START = start_addr; r_java_new_method (); return true; } RAnalPlugin r_anal_plugin_java = { .name = "java", .desc = "Java bytecode analysis plugin", .license = "Apache", .arch = "java", .bits = 32, .custom_fn_anal = 1, .reset_counter = java_reset_counter, .analyze_fns = java_analyze_fns, .post_anal_bb_cb = java_recursive_descent, .revisit_bb_anal = java_revisit_bb_anal_recursive_descent, .op = &java_op, .cmd_ext = java_cmd_ext, 0 }; RAnalPlugin r_anal_plugin_java_ls = { .name = "java_ls", .desc = "Java bytecode analysis plugin with linear sweep", .license = "Apache", .arch = "java", .bits = 32, .custom_fn_anal = 1, .analyze_fns = java_analyze_fns, .post_anal_bb_cb = java_linear_sweep, .post_anal = java_post_anal_linear_sweep, .revisit_bb_anal = java_revisit_bb_anal_recursive_descent, .op = &java_op, .cmd_ext = java_cmd_ext, 0 }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_ANAL, //.data = &r_anal_plugin_java .data = &r_anal_plugin_java_ls, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_181_0
crossvul-cpp_data_bad_2727_0
/* * Copyright (c) 1998-2007 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) */ /* \summary: Resource ReSerVation Protocol (RSVP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "ethertype.h" #include "gmpls.h" #include "af.h" #include "signature.h" static const char tstr[] = " [|rsvp]"; /* * RFC 2205 common header * * 0 1 2 3 * +-------------+-------------+-------------+-------------+ * | Vers | Flags| Msg Type | RSVP Checksum | * +-------------+-------------+-------------+-------------+ * | Send_TTL | (Reserved) | RSVP Length | * +-------------+-------------+-------------+-------------+ * */ struct rsvp_common_header { uint8_t version_flags; uint8_t msg_type; uint8_t checksum[2]; uint8_t ttl; uint8_t reserved; uint8_t length[2]; }; /* * RFC2205 object header * * * 0 1 2 3 * +-------------+-------------+-------------+-------------+ * | Length (bytes) | Class-Num | C-Type | * +-------------+-------------+-------------+-------------+ * | | * // (Object contents) // * | | * +-------------+-------------+-------------+-------------+ */ struct rsvp_object_header { uint8_t length[2]; uint8_t class_num; uint8_t ctype; }; #define RSVP_VERSION 1 #define RSVP_EXTRACT_VERSION(x) (((x)&0xf0)>>4) #define RSVP_EXTRACT_FLAGS(x) ((x)&0x0f) #define RSVP_MSGTYPE_PATH 1 #define RSVP_MSGTYPE_RESV 2 #define RSVP_MSGTYPE_PATHERR 3 #define RSVP_MSGTYPE_RESVERR 4 #define RSVP_MSGTYPE_PATHTEAR 5 #define RSVP_MSGTYPE_RESVTEAR 6 #define RSVP_MSGTYPE_RESVCONF 7 #define RSVP_MSGTYPE_BUNDLE 12 #define RSVP_MSGTYPE_ACK 13 #define RSVP_MSGTYPE_HELLO_OLD 14 /* ancient Hellos */ #define RSVP_MSGTYPE_SREFRESH 15 #define RSVP_MSGTYPE_HELLO 20 static const struct tok rsvp_msg_type_values[] = { { RSVP_MSGTYPE_PATH, "Path" }, { RSVP_MSGTYPE_RESV, "Resv" }, { RSVP_MSGTYPE_PATHERR, "PathErr" }, { RSVP_MSGTYPE_RESVERR, "ResvErr" }, { RSVP_MSGTYPE_PATHTEAR, "PathTear" }, { RSVP_MSGTYPE_RESVTEAR, "ResvTear" }, { RSVP_MSGTYPE_RESVCONF, "ResvConf" }, { RSVP_MSGTYPE_BUNDLE, "Bundle" }, { RSVP_MSGTYPE_ACK, "Acknowledgement" }, { RSVP_MSGTYPE_HELLO_OLD, "Hello (Old)" }, { RSVP_MSGTYPE_SREFRESH, "Refresh" }, { RSVP_MSGTYPE_HELLO, "Hello" }, { 0, NULL} }; static const struct tok rsvp_header_flag_values[] = { { 0x01, "Refresh reduction capable" }, /* rfc2961 */ { 0, NULL} }; #define RSVP_OBJ_SESSION 1 /* rfc2205 */ #define RSVP_OBJ_RSVP_HOP 3 /* rfc2205, rfc3473 */ #define RSVP_OBJ_INTEGRITY 4 /* rfc2747 */ #define RSVP_OBJ_TIME_VALUES 5 /* rfc2205 */ #define RSVP_OBJ_ERROR_SPEC 6 #define RSVP_OBJ_SCOPE 7 #define RSVP_OBJ_STYLE 8 /* rfc2205 */ #define RSVP_OBJ_FLOWSPEC 9 /* rfc2215 */ #define RSVP_OBJ_FILTERSPEC 10 /* rfc2215 */ #define RSVP_OBJ_SENDER_TEMPLATE 11 #define RSVP_OBJ_SENDER_TSPEC 12 /* rfc2215 */ #define RSVP_OBJ_ADSPEC 13 /* rfc2215 */ #define RSVP_OBJ_POLICY_DATA 14 #define RSVP_OBJ_CONFIRM 15 /* rfc2205 */ #define RSVP_OBJ_LABEL 16 /* rfc3209 */ #define RSVP_OBJ_LABEL_REQ 19 /* rfc3209 */ #define RSVP_OBJ_ERO 20 /* rfc3209 */ #define RSVP_OBJ_RRO 21 /* rfc3209 */ #define RSVP_OBJ_HELLO 22 /* rfc3209 */ #define RSVP_OBJ_MESSAGE_ID 23 /* rfc2961 */ #define RSVP_OBJ_MESSAGE_ID_ACK 24 /* rfc2961 */ #define RSVP_OBJ_MESSAGE_ID_LIST 25 /* rfc2961 */ #define RSVP_OBJ_RECOVERY_LABEL 34 /* rfc3473 */ #define RSVP_OBJ_UPSTREAM_LABEL 35 /* rfc3473 */ #define RSVP_OBJ_LABEL_SET 36 /* rfc3473 */ #define RSVP_OBJ_PROTECTION 37 /* rfc3473 */ #define RSVP_OBJ_S2L 50 /* rfc4875 */ #define RSVP_OBJ_DETOUR 63 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */ #define RSVP_OBJ_CLASSTYPE 66 /* rfc4124 */ #define RSVP_OBJ_CLASSTYPE_OLD 125 /* draft-ietf-tewg-diff-te-proto-07 */ #define RSVP_OBJ_SUGGESTED_LABEL 129 /* rfc3473 */ #define RSVP_OBJ_ACCEPT_LABEL_SET 130 /* rfc3473 */ #define RSVP_OBJ_RESTART_CAPABILITY 131 /* rfc3473 */ #define RSVP_OBJ_NOTIFY_REQ 195 /* rfc3473 */ #define RSVP_OBJ_ADMIN_STATUS 196 /* rfc3473 */ #define RSVP_OBJ_PROPERTIES 204 /* juniper proprietary */ #define RSVP_OBJ_FASTREROUTE 205 /* draft-ietf-mpls-rsvp-lsp-fastreroute-07 */ #define RSVP_OBJ_SESSION_ATTRIBUTE 207 /* rfc3209 */ #define RSVP_OBJ_GENERALIZED_UNI 229 /* OIF RSVP extensions UNI 1.0 Signaling, Rel. 2 */ #define RSVP_OBJ_CALL_ID 230 /* rfc3474 */ #define RSVP_OBJ_CALL_OPS 236 /* rfc3474 */ static const struct tok rsvp_obj_values[] = { { RSVP_OBJ_SESSION, "Session" }, { RSVP_OBJ_RSVP_HOP, "RSVP Hop" }, { RSVP_OBJ_INTEGRITY, "Integrity" }, { RSVP_OBJ_TIME_VALUES, "Time Values" }, { RSVP_OBJ_ERROR_SPEC, "Error Spec" }, { RSVP_OBJ_SCOPE, "Scope" }, { RSVP_OBJ_STYLE, "Style" }, { RSVP_OBJ_FLOWSPEC, "Flowspec" }, { RSVP_OBJ_FILTERSPEC, "FilterSpec" }, { RSVP_OBJ_SENDER_TEMPLATE, "Sender Template" }, { RSVP_OBJ_SENDER_TSPEC, "Sender TSpec" }, { RSVP_OBJ_ADSPEC, "Adspec" }, { RSVP_OBJ_POLICY_DATA, "Policy Data" }, { RSVP_OBJ_CONFIRM, "Confirm" }, { RSVP_OBJ_LABEL, "Label" }, { RSVP_OBJ_LABEL_REQ, "Label Request" }, { RSVP_OBJ_ERO, "ERO" }, { RSVP_OBJ_RRO, "RRO" }, { RSVP_OBJ_HELLO, "Hello" }, { RSVP_OBJ_MESSAGE_ID, "Message ID" }, { RSVP_OBJ_MESSAGE_ID_ACK, "Message ID Ack" }, { RSVP_OBJ_MESSAGE_ID_LIST, "Message ID List" }, { RSVP_OBJ_RECOVERY_LABEL, "Recovery Label" }, { RSVP_OBJ_UPSTREAM_LABEL, "Upstream Label" }, { RSVP_OBJ_LABEL_SET, "Label Set" }, { RSVP_OBJ_ACCEPT_LABEL_SET, "Acceptable Label Set" }, { RSVP_OBJ_DETOUR, "Detour" }, { RSVP_OBJ_CLASSTYPE, "Class Type" }, { RSVP_OBJ_CLASSTYPE_OLD, "Class Type (old)" }, { RSVP_OBJ_SUGGESTED_LABEL, "Suggested Label" }, { RSVP_OBJ_PROPERTIES, "Properties" }, { RSVP_OBJ_FASTREROUTE, "Fast Re-Route" }, { RSVP_OBJ_SESSION_ATTRIBUTE, "Session Attribute" }, { RSVP_OBJ_GENERALIZED_UNI, "Generalized UNI" }, { RSVP_OBJ_CALL_ID, "Call-ID" }, { RSVP_OBJ_CALL_OPS, "Call Capability" }, { RSVP_OBJ_RESTART_CAPABILITY, "Restart Capability" }, { RSVP_OBJ_NOTIFY_REQ, "Notify Request" }, { RSVP_OBJ_PROTECTION, "Protection" }, { RSVP_OBJ_ADMIN_STATUS, "Administrative Status" }, { RSVP_OBJ_S2L, "Sub-LSP to LSP" }, { 0, NULL} }; #define RSVP_CTYPE_IPV4 1 #define RSVP_CTYPE_IPV6 2 #define RSVP_CTYPE_TUNNEL_IPV4 7 #define RSVP_CTYPE_TUNNEL_IPV6 8 #define RSVP_CTYPE_UNI_IPV4 11 /* OIF RSVP extensions UNI 1.0 Signaling Rel. 2 */ #define RSVP_CTYPE_1 1 #define RSVP_CTYPE_2 2 #define RSVP_CTYPE_3 3 #define RSVP_CTYPE_4 4 #define RSVP_CTYPE_12 12 #define RSVP_CTYPE_13 13 #define RSVP_CTYPE_14 14 /* * the ctypes are not globally unique so for * translating it to strings we build a table based * on objects offsetted by the ctype */ static const struct tok rsvp_ctype_values[] = { { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" }, { 256*RSVP_OBJ_RSVP_HOP+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" }, { 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_NOTIFY_REQ+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_CONFIRM+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_TIME_VALUES+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_1, "obsolete" }, { 256*RSVP_OBJ_FLOWSPEC+RSVP_CTYPE_2, "IntServ" }, { 256*RSVP_OBJ_SENDER_TSPEC+RSVP_CTYPE_2, "IntServ" }, { 256*RSVP_OBJ_ADSPEC+RSVP_CTYPE_2, "IntServ" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_3, "IPv6 Flow-label" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_FILTERSPEC+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_UNI_IPV4, "UNI IPv4" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_13, "IPv4 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SESSION+RSVP_CTYPE_14, "IPv6 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_12, "IPv4 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_SENDER_TEMPLATE+RSVP_CTYPE_13, "IPv6 P2MP LSP Tunnel" }, { 256*RSVP_OBJ_MESSAGE_ID+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_1, "Message id ack" }, { 256*RSVP_OBJ_MESSAGE_ID_ACK+RSVP_CTYPE_2, "Message id nack" }, { 256*RSVP_OBJ_MESSAGE_ID_LIST+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_STYLE+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_HELLO+RSVP_CTYPE_1, "Hello Request" }, { 256*RSVP_OBJ_HELLO+RSVP_CTYPE_2, "Hello Ack" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_1, "without label range" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_2, "with ATM label range" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_3, "with FR label range" }, { 256*RSVP_OBJ_LABEL_REQ+RSVP_CTYPE_4, "Generalized Label" }, { 256*RSVP_OBJ_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_SUGGESTED_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_UPSTREAM_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_1, "Label" }, { 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_2, "Generalized Label" }, { 256*RSVP_OBJ_RECOVERY_LABEL+RSVP_CTYPE_3, "Waveband Switching" }, { 256*RSVP_OBJ_ERO+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_RRO+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV4, "IPv4" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_IPV6, "IPv6" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_3, "IPv4 plus opt. TLVs" }, { 256*RSVP_OBJ_ERROR_SPEC+RSVP_CTYPE_4, "IPv6 plus opt. TLVs" }, { 256*RSVP_OBJ_RESTART_CAPABILITY+RSVP_CTYPE_1, "IPv4" }, { 256*RSVP_OBJ_SESSION_ATTRIBUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, /* old style*/ { 256*RSVP_OBJ_FASTREROUTE+RSVP_CTYPE_1, "1" }, /* new style */ { 256*RSVP_OBJ_DETOUR+RSVP_CTYPE_TUNNEL_IPV4, "Tunnel IPv4" }, { 256*RSVP_OBJ_PROPERTIES+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_ADMIN_STATUS+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_CLASSTYPE+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_CLASSTYPE_OLD+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_LABEL_SET+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_GENERALIZED_UNI+RSVP_CTYPE_1, "1" }, { 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV4, "IPv4 sub-LSP" }, { 256*RSVP_OBJ_S2L+RSVP_CTYPE_IPV6, "IPv6 sub-LSP" }, { 0, NULL} }; struct rsvp_obj_integrity_t { uint8_t flags; uint8_t res; uint8_t key_id[6]; uint8_t sequence[8]; uint8_t digest[16]; }; static const struct tok rsvp_obj_integrity_flag_values[] = { { 0x80, "Handshake" }, { 0, NULL} }; struct rsvp_obj_frr_t { uint8_t setup_prio; uint8_t hold_prio; uint8_t hop_limit; uint8_t flags; uint8_t bandwidth[4]; uint8_t include_any[4]; uint8_t exclude_any[4]; uint8_t include_all[4]; }; #define RSVP_OBJ_XRO_MASK_SUBOBJ(x) ((x)&0x7f) #define RSVP_OBJ_XRO_MASK_LOOSE(x) ((x)&0x80) #define RSVP_OBJ_XRO_RES 0 #define RSVP_OBJ_XRO_IPV4 1 #define RSVP_OBJ_XRO_IPV6 2 #define RSVP_OBJ_XRO_LABEL 3 #define RSVP_OBJ_XRO_ASN 32 #define RSVP_OBJ_XRO_MPLS 64 static const struct tok rsvp_obj_xro_values[] = { { RSVP_OBJ_XRO_RES, "Reserved" }, { RSVP_OBJ_XRO_IPV4, "IPv4 prefix" }, { RSVP_OBJ_XRO_IPV6, "IPv6 prefix" }, { RSVP_OBJ_XRO_LABEL, "Label" }, { RSVP_OBJ_XRO_ASN, "Autonomous system number" }, { RSVP_OBJ_XRO_MPLS, "MPLS label switched path termination" }, { 0, NULL} }; /* draft-ietf-mpls-rsvp-lsp-fastreroute-07.txt */ static const struct tok rsvp_obj_rro_flag_values[] = { { 0x01, "Local protection available" }, { 0x02, "Local protection in use" }, { 0x04, "Bandwidth protection" }, { 0x08, "Node protection" }, { 0, NULL} }; /* RFC3209 */ static const struct tok rsvp_obj_rro_label_flag_values[] = { { 0x01, "Global" }, { 0, NULL} }; static const struct tok rsvp_resstyle_values[] = { { 17, "Wildcard Filter" }, { 10, "Fixed Filter" }, { 18, "Shared Explicit" }, { 0, NULL} }; #define RSVP_OBJ_INTSERV_GUARANTEED_SERV 2 #define RSVP_OBJ_INTSERV_CONTROLLED_LOAD 5 static const struct tok rsvp_intserv_service_type_values[] = { { 1, "Default/Global Information" }, { RSVP_OBJ_INTSERV_GUARANTEED_SERV, "Guaranteed Service" }, { RSVP_OBJ_INTSERV_CONTROLLED_LOAD, "Controlled Load" }, { 0, NULL} }; static const struct tok rsvp_intserv_parameter_id_values[] = { { 4, "IS hop cnt" }, { 6, "Path b/w estimate" }, { 8, "Minimum path latency" }, { 10, "Composed MTU" }, { 127, "Token Bucket TSpec" }, { 130, "Guaranteed Service RSpec" }, { 133, "End-to-end composed value for C" }, { 134, "End-to-end composed value for D" }, { 135, "Since-last-reshaping point composed C" }, { 136, "Since-last-reshaping point composed D" }, { 0, NULL} }; static const struct tok rsvp_session_attribute_flag_values[] = { { 0x01, "Local Protection" }, { 0x02, "Label Recording" }, { 0x04, "SE Style" }, { 0x08, "Bandwidth protection" }, /* RFC4090 */ { 0x10, "Node protection" }, /* RFC4090 */ { 0, NULL} }; static const struct tok rsvp_obj_prop_tlv_values[] = { { 0x01, "Cos" }, { 0x02, "Metric 1" }, { 0x04, "Metric 2" }, { 0x08, "CCC Status" }, { 0x10, "Path Type" }, { 0, NULL} }; #define RSVP_OBJ_ERROR_SPEC_CODE_ROUTING 24 #define RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY 25 #define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE 28 #define RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD 125 static const struct tok rsvp_obj_error_code_values[] = { { RSVP_OBJ_ERROR_SPEC_CODE_ROUTING, "Routing Problem" }, { RSVP_OBJ_ERROR_SPEC_CODE_NOTIFY, "Notify Error" }, { RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE, "Diffserv TE Error" }, { RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD, "Diffserv TE Error (Old)" }, { 0, NULL} }; static const struct tok rsvp_obj_error_code_routing_values[] = { { 1, "Bad EXPLICIT_ROUTE object" }, { 2, "Bad strict node" }, { 3, "Bad loose node" }, { 4, "Bad initial subobject" }, { 5, "No route available toward destination" }, { 6, "Unacceptable label value" }, { 7, "RRO indicated routing loops" }, { 8, "non-RSVP-capable router in the path" }, { 9, "MPLS label allocation failure" }, { 10, "Unsupported L3PID" }, { 0, NULL} }; static const struct tok rsvp_obj_error_code_diffserv_te_values[] = { { 1, "Unexpected CT object" }, { 2, "Unsupported CT" }, { 3, "Invalid CT value" }, { 4, "CT/setup priority do not form a configured TE-Class" }, { 5, "CT/holding priority do not form a configured TE-Class" }, { 6, "CT/setup priority and CT/holding priority do not form a configured TE-Class" }, { 7, "Inconsistency between signaled PSC and signaled CT" }, { 8, "Inconsistency between signaled PHBs and signaled CT" }, { 0, NULL} }; /* rfc3473 / rfc 3471 */ static const struct tok rsvp_obj_admin_status_flag_values[] = { { 0x80000000, "Reflect" }, { 0x00000004, "Testing" }, { 0x00000002, "Admin-down" }, { 0x00000001, "Delete-in-progress" }, { 0, NULL} }; /* label set actions - rfc3471 */ #define LABEL_SET_INCLUSIVE_LIST 0 #define LABEL_SET_EXCLUSIVE_LIST 1 #define LABEL_SET_INCLUSIVE_RANGE 2 #define LABEL_SET_EXCLUSIVE_RANGE 3 static const struct tok rsvp_obj_label_set_action_values[] = { { LABEL_SET_INCLUSIVE_LIST, "Inclusive list" }, { LABEL_SET_EXCLUSIVE_LIST, "Exclusive list" }, { LABEL_SET_INCLUSIVE_RANGE, "Inclusive range" }, { LABEL_SET_EXCLUSIVE_RANGE, "Exclusive range" }, { 0, NULL} }; /* OIF RSVP extensions UNI 1.0 Signaling, release 2 */ #define RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS 1 #define RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS 2 #define RSVP_GEN_UNI_SUBOBJ_DIVERSITY 3 #define RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL 4 #define RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL 5 static const struct tok rsvp_obj_generalized_uni_values[] = { { RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS, "Source TNA address" }, { RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS, "Destination TNA address" }, { RSVP_GEN_UNI_SUBOBJ_DIVERSITY, "Diversity" }, { RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL, "Egress label" }, { RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL, "Service level" }, { 0, NULL} }; /* * this is a dissector for all the intserv defined * specs as defined per rfc2215 * it is called from various rsvp objects; * returns the amount of bytes being processed */ static int rsvp_intserv_print(netdissect_options *ndo, const u_char *tptr, u_short obj_tlen) { int parameter_id,parameter_length; union { float f; uint32_t i; } bw; if (obj_tlen < 4) return 0; parameter_id = *(tptr); ND_TCHECK2(*(tptr + 2), 2); parameter_length = EXTRACT_16BITS(tptr+2)<<2; /* convert wordcount to bytecount */ ND_PRINT((ndo, "\n\t Parameter ID: %s (%u), length: %u, Flags: [0x%02x]", tok2str(rsvp_intserv_parameter_id_values,"unknown",parameter_id), parameter_id, parameter_length, *(tptr + 1))); if (obj_tlen < parameter_length+4) return 0; switch(parameter_id) { /* parameter_id */ case 4: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 4 (e) | (f) | 1 (g) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | IS hop cnt (32-bit unsigned integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tIS hop count: %u", EXTRACT_32BITS(tptr + 4))); } break; case 6: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6 (h) | (i) | 1 (j) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Path b/w estimate (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); bw.i = EXTRACT_32BITS(tptr+4); ND_PRINT((ndo, "\n\t\tPath b/w estimate: %.10g Mbps", bw.f / 125000)); } break; case 8: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 8 (k) | (l) | 1 (m) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Minimum path latency (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tMinimum path latency: ")); if (EXTRACT_32BITS(tptr+4) == 0xffffffff) ND_PRINT((ndo, "don't care")); else ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr + 4))); } break; case 10: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 10 (n) | (o) | 1 (p) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Composed MTU (32-bit unsigned integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tComposed MTU: %u bytes", EXTRACT_32BITS(tptr + 4))); } break; case 127: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 127 (e) | 0 (f) | 5 (g) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Token Bucket Rate [r] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Token Bucket Size [b] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Peak Data Rate [p] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Minimum Policed Unit [m] (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Maximum Packet Size [M] (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 20) { ND_TCHECK2(*(tptr + 4), 20); bw.i = EXTRACT_32BITS(tptr+4); ND_PRINT((ndo, "\n\t\tToken Bucket Rate: %.10g Mbps", bw.f / 125000)); bw.i = EXTRACT_32BITS(tptr+8); ND_PRINT((ndo, "\n\t\tToken Bucket Size: %.10g bytes", bw.f)); bw.i = EXTRACT_32BITS(tptr+12); ND_PRINT((ndo, "\n\t\tPeak Data Rate: %.10g Mbps", bw.f / 125000)); ND_PRINT((ndo, "\n\t\tMinimum Policed Unit: %u bytes", EXTRACT_32BITS(tptr + 16))); ND_PRINT((ndo, "\n\t\tMaximum Packet Size: %u bytes", EXTRACT_32BITS(tptr + 20))); } break; case 130: /* * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 130 (h) | 0 (i) | 2 (j) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Rate [R] (32-bit IEEE floating point number) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Slack Term [S] (32-bit integer) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ if (parameter_length == 8) { ND_TCHECK2(*(tptr + 4), 8); bw.i = EXTRACT_32BITS(tptr+4); ND_PRINT((ndo, "\n\t\tRate: %.10g Mbps", bw.f / 125000)); ND_PRINT((ndo, "\n\t\tSlack Term: %u", EXTRACT_32BITS(tptr + 8))); } break; case 133: case 134: case 135: case 136: if (parameter_length == 4) { ND_TCHECK2(*(tptr + 4), 4); ND_PRINT((ndo, "\n\t\tValue: %u", EXTRACT_32BITS(tptr + 4))); } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr + 4, "\n\t\t", parameter_length); } return (parameter_length+4); /* header length 4 bytes */ trunc: ND_PRINT((ndo, "%s", tstr)); return 0; } /* * Clear checksum prior to signature verification. */ static void rsvp_clear_checksum(void *header) { struct rsvp_common_header *rsvp_com_header = (struct rsvp_common_header *) header; rsvp_com_header->checksum[0] = 0; rsvp_com_header->checksum[1] = 0; } static int rsvp_obj_print(netdissect_options *ndo, const u_char *pptr, u_int plen, const u_char *tptr, const char *ident, u_int tlen, const struct rsvp_common_header *rsvp_com_header) { const struct rsvp_object_header *rsvp_obj_header; const u_char *obj_tptr; union { const struct rsvp_obj_integrity_t *rsvp_obj_integrity; const struct rsvp_obj_frr_t *rsvp_obj_frr; } obj_ptr; u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen; int hexdump,processed,padbytes,error_code,error_value,i,sigcheck; union { float f; uint32_t i; } bw; uint8_t namelen; u_int action, subchannel; while(tlen>=sizeof(struct rsvp_object_header)) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header)); rsvp_obj_header = (const struct rsvp_object_header *)tptr; rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length); rsvp_obj_ctype=rsvp_obj_header->ctype; if(rsvp_obj_len % 4) { ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len)); return -1; } if(rsvp_obj_len < sizeof(struct rsvp_object_header)) { ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len, (unsigned long)sizeof(const struct rsvp_object_header))); return -1; } ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s", ident, tok2str(rsvp_obj_values, "Unknown", rsvp_obj_header->class_num), rsvp_obj_header->class_num, ((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject")); if (rsvp_obj_header->class_num > 128) ND_PRINT((ndo, " %s", ((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently")); ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u", tok2str(rsvp_ctype_values, "Unknown", ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype), rsvp_obj_ctype, rsvp_obj_len)); if(tlen < rsvp_obj_len) { ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident)); return -1; } obj_tptr=tptr+sizeof(struct rsvp_object_header); obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header); /* did we capture enough for fully decoding the object ? */ if (!ND_TTEST2(*tptr, rsvp_obj_len)) return -1; hexdump=FALSE; switch(rsvp_obj_header->class_num) { case RSVP_OBJ_SESSION: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return -1; ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+5), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return -1; ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr + sizeof(struct in6_addr)))); ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u", ident, *(obj_tptr+sizeof(struct in6_addr)+1), EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 36) return -1; ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ip6addr_string(ndo, obj_tptr + 20))); obj_tlen-=36; obj_tptr+=36; break; case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */ if (obj_tlen < 26) return -1; ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_16BITS(obj_tptr+6), ip6addr_string(ndo, obj_tptr + 8))); obj_tlen-=26; obj_tptr+=26; break; case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_TUNNEL_IPV4: case RSVP_CTYPE_UNI_IPV4: if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ipaddr_string(ndo, obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_CONFIRM: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Receiver Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return -1; ND_PRINT((ndo, "%s IPv6 Receiver Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_NOTIFY_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < sizeof(struct in_addr)) return -1; ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in_addr); obj_tptr+=sizeof(struct in_addr); break; case RSVP_CTYPE_IPV6: if (obj_tlen < sizeof(struct in6_addr)) return-1; ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=sizeof(struct in6_addr); obj_tptr+=sizeof(struct in6_addr); break; default: hexdump=TRUE; } break; case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */ case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */ case RSVP_OBJ_RECOVERY_LABEL: /* fall through */ case RSVP_OBJ_LABEL: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Generalized Label: %u", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u", ident, EXTRACT_32BITS(obj_tptr), ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: hexdump=TRUE; } break; case RSVP_OBJ_STYLE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]", ident, tok2str(rsvp_resstyle_values, "Unknown", EXTRACT_24BITS(obj_tptr+1)), *(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SENDER_TEMPLATE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_REQ: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); obj_tlen-=4; obj_tptr+=4; } break; case RSVP_CTYPE_2: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" )); ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+4))&0xfff, (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff)); ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u", ident, (EXTRACT_16BITS(obj_tptr+8))&0xfff, (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff)); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_3: if (obj_tlen < 12) return-1; ND_PRINT((ndo, "%s L3 Protocol ID: %s", ident, tok2str(ethertype_values, "Unknown Protocol (0x%04x)", EXTRACT_16BITS(obj_tptr + 2)))); ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI", ident, (EXTRACT_32BITS(obj_tptr+4))&0x7fffff, (EXTRACT_32BITS(obj_tptr+8))&0x7fffff, (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "", (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : "")); obj_tlen-=12; obj_tptr+=12; break; case RSVP_CTYPE_4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)", ident, tok2str(gmpls_encoding_values, "Unknown", *obj_tptr), *obj_tptr)); ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)", ident, tok2str(gmpls_switch_cap_values, "Unknown", *(obj_tptr+1)), *(obj_tptr+1), tok2str(gmpls_payload_values, "Unknown", EXTRACT_16BITS(obj_tptr+2)), EXTRACT_16BITS(obj_tptr + 2))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RRO: case RSVP_OBJ_ERO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: while(obj_tlen >= 4 ) { u_char length; ND_TCHECK2(*obj_tptr, 4); length = *(obj_tptr + 1); ND_PRINT((ndo, "%s Subobject Type: %s, length %u", ident, tok2str(rsvp_obj_xro_values, "Unknown %u", RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)), length)); if (length == 0) { /* prevent infinite loops */ ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident)); break; } switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) { u_char prefix_length; case RSVP_OBJ_XRO_IPV4: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); prefix_length = *(obj_tptr+6); if (prefix_length != 32) { ND_PRINT((ndo, " ERROR: Prefix length %u != 32", prefix_length)); goto invalid; } ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]", RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict", ipaddr_string(ndo, obj_tptr+2), *(obj_tptr+6), bittok2str(rsvp_obj_rro_flag_values, "none", *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */ break; case RSVP_OBJ_XRO_LABEL: if (length != 8) { ND_PRINT((ndo, " ERROR: length != 8")); goto invalid; } ND_TCHECK2(*obj_tptr, 8); ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u", bittok2str(rsvp_obj_rro_label_flag_values, "none", *(obj_tptr+2)), *(obj_tptr+2), tok2str(rsvp_ctype_values, "Unknown", *(obj_tptr+3) + 256*RSVP_OBJ_RRO), *(obj_tptr+3), EXTRACT_32BITS(obj_tptr + 4))); } obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_HELLO: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_RESTART_CAPABILITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; break; default: hexdump=TRUE; } break; case RSVP_OBJ_SESSION_ATTRIBUTE: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 4) return-1; namelen = *(obj_tptr+3); if (obj_tlen < 4+namelen) return-1; ND_PRINT((ndo, "%s Session Name: ", ident)); for (i = 0; i < namelen; i++) safeputchar(ndo, *(obj_tptr + 4 + i)); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)", ident, (int)*obj_tptr, (int)*(obj_tptr+1), bittok2str(rsvp_session_attribute_flag_values, "none", *(obj_tptr+2)), *(obj_tptr + 2))); obj_tlen-=4+*(obj_tptr+3); obj_tptr+=4+*(obj_tptr+3); break; default: hexdump=TRUE; } break; case RSVP_OBJ_GENERALIZED_UNI: switch(rsvp_obj_ctype) { int subobj_type,af,subobj_len,total_subobj_len; case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; /* read variable length subobjects */ total_subobj_len = obj_tlen; while(total_subobj_len > 0) { subobj_len = EXTRACT_16BITS(obj_tptr); subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8; af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF; ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u", ident, tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type), subobj_type, tok2str(af_values, "Unknown", af), af, subobj_len)); if(subobj_len == 0) goto invalid; switch(subobj_type) { case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS: case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS: switch(af) { case AFNUM_INET: if (subobj_len < 8) return -1; ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s", ident, ipaddr_string(ndo, obj_tptr + 4))); break; case AFNUM_INET6: if (subobj_len < 20) return -1; ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s", ident, ip6addr_string(ndo, obj_tptr + 4))); break; case AFNUM_NSAP: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; } break; case RSVP_GEN_UNI_SUBOBJ_DIVERSITY: if (subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL: if (subobj_len < 16) { return -1; } ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u", ident, ((EXTRACT_32BITS(obj_tptr+4))>>31), ((EXTRACT_32BITS(obj_tptr+4))&0xFF), EXTRACT_32BITS(obj_tptr+8), EXTRACT_32BITS(obj_tptr + 12))); break; case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL: if (subobj_len < 8) { return -1; } ND_PRINT((ndo, "%s Service level: %u", ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24)); break; default: hexdump=TRUE; break; } total_subobj_len-=subobj_len; obj_tptr+=subobj_len; obj_tlen+=subobj_len; } if (total_subobj_len) { /* unless we have a TLV parser lets just hexdump */ hexdump=TRUE; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_RSVP_HOP: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; if (obj_tlen) hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_32BITS(obj_tptr + 16))); obj_tlen-=20; obj_tptr+=20; hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ break; default: hexdump=TRUE; } break; case RSVP_OBJ_TIME_VALUES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Refresh Period: %ums", ident, EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; /* those three objects do share the same semantics */ case RSVP_OBJ_SENDER_TSPEC: case RSVP_OBJ_ADSPEC: case RSVP_OBJ_FLOWSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_2: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Msg-Version: %u, length: %u", ident, (*obj_tptr & 0xf0) >> 4, EXTRACT_16BITS(obj_tptr + 2) << 2)); obj_tptr+=4; /* get to the start of the service header */ obj_tlen-=4; while (obj_tlen >= 4) { intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2; ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u", ident, tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)), *(obj_tptr), (*(obj_tptr+1)&0x80) ? "" : "not", intserv_serv_tlen)); obj_tptr+=4; /* get to the start of the parameter list */ obj_tlen-=4; while (intserv_serv_tlen>=4) { processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen); if (processed == 0) break; obj_tlen-=processed; intserv_serv_tlen-=processed; obj_tptr+=processed; } } break; default: hexdump=TRUE; } break; case RSVP_OBJ_FILTERSPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_3: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_24BITS(obj_tptr + 17))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_TUNNEL_IPV6: if (obj_tlen < 20) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 18))); obj_tlen-=20; obj_tptr+=20; break; case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ if (obj_tlen < 40) return-1; ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ip6addr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+18), ident, ip6addr_string(ndo, obj_tptr+20), EXTRACT_16BITS(obj_tptr + 38))); obj_tlen-=40; obj_tptr+=40; break; case RSVP_CTYPE_TUNNEL_IPV4: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr + 6))); obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x" "%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x", ident, ipaddr_string(ndo, obj_tptr), EXTRACT_16BITS(obj_tptr+6), ident, ipaddr_string(ndo, obj_tptr+8), EXTRACT_16BITS(obj_tptr + 12))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_FASTREROUTE: /* the differences between c-type 1 and 7 are minor */ obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr; switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: /* new style */ if (obj_tlen < sizeof(struct rsvp_obj_frr_t)) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all))); obj_tlen-=sizeof(struct rsvp_obj_frr_t); obj_tptr+=sizeof(struct rsvp_obj_frr_t); break; case RSVP_CTYPE_TUNNEL_IPV4: /* old style */ if (obj_tlen < 16) return-1; bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps", ident, (int)obj_ptr.rsvp_obj_frr->setup_prio, (int)obj_ptr.rsvp_obj_frr->hold_prio, (int)obj_ptr.rsvp_obj_frr->hop_limit, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; case RSVP_OBJ_DETOUR: switch(rsvp_obj_ctype) { case RSVP_CTYPE_TUNNEL_IPV4: while(obj_tlen >= 8) { ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s", ident, ipaddr_string(ndo, obj_tptr), ipaddr_string(ndo, obj_tptr + 4))); obj_tlen-=8; obj_tptr+=8; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_CLASSTYPE: case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: ND_PRINT((ndo, "%s CT: %u", ident, EXTRACT_32BITS(obj_tptr) & 0x7)); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_ERROR_SPEC: switch(rsvp_obj_ctype) { case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV4: if (obj_tlen < 8) return-1; error_code=*(obj_tptr+5); error_value=EXTRACT_16BITS(obj_tptr+6); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ipaddr_string(ndo, obj_tptr), *(obj_tptr+4), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */ case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value), error_value)); break; default: ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value)); break; } obj_tlen-=8; obj_tptr+=8; break; case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ case RSVP_CTYPE_IPV6: if (obj_tlen < 20) return-1; error_code=*(obj_tptr+17); error_value=EXTRACT_16BITS(obj_tptr+18); ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)", ident, ip6addr_string(ndo, obj_tptr), *(obj_tptr+16), ident, tok2str(rsvp_obj_error_code_values,"unknown",error_code), error_code)); switch (error_code) { case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: ND_PRINT((ndo, ", Error Value: %s (%u)", tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value), error_value)); break; default: break; } obj_tlen-=20; obj_tptr+=20; break; default: hexdump=TRUE; } break; case RSVP_OBJ_PROPERTIES: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; padbytes = EXTRACT_16BITS(obj_tptr+2); ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u", ident, EXTRACT_16BITS(obj_tptr), padbytes)); obj_tlen-=4; obj_tptr+=4; /* loop through as long there is anything longer than the TLV header (2) */ while(obj_tlen >= 2 + padbytes) { ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */ ident, tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr), *obj_tptr, *(obj_tptr + 1))); if (obj_tlen < *(obj_tptr+1)) return-1; if (*(obj_tptr+1) < 2) return -1; print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2); obj_tlen-=*(obj_tptr+1); obj_tptr+=*(obj_tptr+1); } break; default: hexdump=TRUE; } break; case RSVP_OBJ_MESSAGE_ID: /* fall through */ case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */ case RSVP_OBJ_MESSAGE_ID_LIST: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: case RSVP_CTYPE_2: if (obj_tlen < 8) return-1; ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u", ident, *obj_tptr, EXTRACT_24BITS(obj_tptr + 1))); obj_tlen-=4; obj_tptr+=4; /* loop through as long there are no messages left */ while(obj_tlen >= 4) { ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)", ident, EXTRACT_32BITS(obj_tptr), EXTRACT_32BITS(obj_tptr))); obj_tlen-=4; obj_tptr+=4; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_INTEGRITY: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < sizeof(struct rsvp_obj_integrity_t)) return-1; obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr; ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]", ident, EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4), bittok2str(rsvp_obj_integrity_flag_values, "none", obj_ptr.rsvp_obj_integrity->flags))); ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ", ident, EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8), EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12))); sigcheck = signature_verify(ndo, pptr, plen, obj_ptr.rsvp_obj_integrity->digest, rsvp_clear_checksum, rsvp_com_header); ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck))); obj_tlen+=sizeof(struct rsvp_obj_integrity_t); obj_tptr+=sizeof(struct rsvp_obj_integrity_t); break; default: hexdump=TRUE; } break; case RSVP_OBJ_ADMIN_STATUS: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Flags [%s]", ident, bittok2str(rsvp_obj_admin_status_flag_values, "none", EXTRACT_32BITS(obj_tptr)))); obj_tlen-=4; obj_tptr+=4; break; default: hexdump=TRUE; } break; case RSVP_OBJ_LABEL_SET: switch(rsvp_obj_ctype) { case RSVP_CTYPE_1: if (obj_tlen < 4) return-1; action = (EXTRACT_16BITS(obj_tptr)>>8); ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident, tok2str(rsvp_obj_label_set_action_values, "Unknown", action), action, ((EXTRACT_32BITS(obj_tptr) & 0x7F)))); switch (action) { case LABEL_SET_INCLUSIVE_RANGE: case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */ /* only a couple of subchannels are expected */ if (obj_tlen < 12) return -1; ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident, EXTRACT_32BITS(obj_tptr+4), EXTRACT_32BITS(obj_tptr + 8))); obj_tlen-=12; obj_tptr+=12; break; default: obj_tlen-=4; obj_tptr+=4; subchannel = 1; while(obj_tlen >= 4 ) { ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel, EXTRACT_32BITS(obj_tptr))); obj_tptr+=4; obj_tlen-=4; subchannel++; } break; } break; default: hexdump=TRUE; } break; case RSVP_OBJ_S2L: switch (rsvp_obj_ctype) { case RSVP_CTYPE_IPV4: if (obj_tlen < 4) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ipaddr_string(ndo, obj_tptr))); obj_tlen-=4; obj_tptr+=4; break; case RSVP_CTYPE_IPV6: if (obj_tlen < 16) return-1; ND_PRINT((ndo, "%s Sub-LSP destination address: %s", ident, ip6addr_string(ndo, obj_tptr))); obj_tlen-=16; obj_tptr+=16; break; default: hexdump=TRUE; } break; /* * FIXME those are the defined objects that lack a decoder * you are welcome to contribute code ;-) */ case RSVP_OBJ_SCOPE: case RSVP_OBJ_POLICY_DATA: case RSVP_OBJ_ACCEPT_LABEL_SET: case RSVP_OBJ_PROTECTION: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */ break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || hexdump == TRUE) print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */ rsvp_obj_len - sizeof(struct rsvp_object_header)); tptr+=rsvp_obj_len; tlen-=rsvp_obj_len; } return 0; invalid: ND_PRINT((ndo, "%s", istr)); return -1; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return -1; } void rsvp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct rsvp_common_header *rsvp_com_header; const u_char *tptr; u_short plen, tlen; tptr=pptr; rsvp_com_header = (const struct rsvp_common_header *)pptr; ND_TCHECK(*rsvp_com_header); /* * Sanity checking of the header. */ if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) { ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags))); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "RSVPv%u %s Message, length: %u", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags), tok2str(rsvp_msg_type_values, "unknown (%u)",rsvp_com_header->msg_type), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ plen = tlen = EXTRACT_16BITS(rsvp_com_header->length); ND_PRINT((ndo, "\n\tRSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags), tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type), rsvp_com_header->msg_type, bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)), tlen, rsvp_com_header->ttl, EXTRACT_16BITS(rsvp_com_header->checksum))); if (tlen < sizeof(const struct rsvp_common_header)) { ND_PRINT((ndo, "ERROR: common header too short %u < %lu", tlen, (unsigned long)sizeof(const struct rsvp_common_header))); return; } tptr+=sizeof(const struct rsvp_common_header); tlen-=sizeof(const struct rsvp_common_header); switch(rsvp_com_header->msg_type) { case RSVP_MSGTYPE_BUNDLE: /* * Process each submessage in the bundle message. * Bundle messages may not contain bundle submessages, so we don't * need to handle bundle submessages specially. */ while(tlen > 0) { const u_char *subpptr=tptr, *subtptr; u_short subplen, subtlen; subtptr=subpptr; rsvp_com_header = (const struct rsvp_common_header *)subpptr; ND_TCHECK(*rsvp_com_header); /* * Sanity checking of the header. */ if (RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags) != RSVP_VERSION) { ND_PRINT((ndo, "ERROR: RSVP version %u packet not supported", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags))); return; } subplen = subtlen = EXTRACT_16BITS(rsvp_com_header->length); ND_PRINT((ndo, "\n\t RSVPv%u %s Message (%u), Flags: [%s], length: %u, ttl: %u, checksum: 0x%04x", RSVP_EXTRACT_VERSION(rsvp_com_header->version_flags), tok2str(rsvp_msg_type_values, "unknown, type: %u",rsvp_com_header->msg_type), rsvp_com_header->msg_type, bittok2str(rsvp_header_flag_values,"none",RSVP_EXTRACT_FLAGS(rsvp_com_header->version_flags)), subtlen, rsvp_com_header->ttl, EXTRACT_16BITS(rsvp_com_header->checksum))); if (subtlen < sizeof(const struct rsvp_common_header)) { ND_PRINT((ndo, "ERROR: common header too short %u < %lu", subtlen, (unsigned long)sizeof(const struct rsvp_common_header))); return; } if (tlen < subtlen) { ND_PRINT((ndo, "ERROR: common header too large %u > %u", subtlen, tlen)); return; } subtptr+=sizeof(const struct rsvp_common_header); subtlen-=sizeof(const struct rsvp_common_header); /* * Print all objects in the submessage. */ if (rsvp_obj_print(ndo, subpptr, subplen, subtptr, "\n\t ", subtlen, rsvp_com_header) == -1) return; tptr+=subtlen+sizeof(const struct rsvp_common_header); tlen-=subtlen+sizeof(const struct rsvp_common_header); } break; case RSVP_MSGTYPE_PATH: case RSVP_MSGTYPE_RESV: case RSVP_MSGTYPE_PATHERR: case RSVP_MSGTYPE_RESVERR: case RSVP_MSGTYPE_PATHTEAR: case RSVP_MSGTYPE_RESVTEAR: case RSVP_MSGTYPE_RESVCONF: case RSVP_MSGTYPE_HELLO_OLD: case RSVP_MSGTYPE_HELLO: case RSVP_MSGTYPE_ACK: case RSVP_MSGTYPE_SREFRESH: /* * Print all objects in the message. */ if (rsvp_obj_print(ndo, pptr, plen, tptr, "\n\t ", tlen, rsvp_com_header) == -1) return; break; default: print_unknown_data(ndo, tptr, "\n\t ", tlen); break; } return; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2727_0
crossvul-cpp_data_bad_5295_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } CheckNumberCompactPixels; compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels* next_image->columns,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5295_0
crossvul-cpp_data_bad_5201_4
404: Not Found
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5201_4
crossvul-cpp_data_bad_1011_0
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * memcached - memory caching daemon * * https://www.memcached.org/ * * Copyright 2003 Danga Interactive, Inc. All rights reserved. * * Use and distribution licensed under the BSD license. See * the LICENSE file for full text. * * Authors: * Anatoly Vorobey <mellon@pobox.com> * Brad Fitzpatrick <brad@danga.com> */ #include "memcached.h" #ifdef EXTSTORE #include "storage.h" #endif #include "authfile.h" #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <signal.h> #include <sys/param.h> #include <sys/resource.h> #include <sys/uio.h> #include <ctype.h> #include <stdarg.h> /* some POSIX systems need the following definition * to get mlockall flags out of sys/mman.h. */ #ifndef _P1003_1B_VISIBLE #define _P1003_1B_VISIBLE #endif /* need this to get IOV_MAX on some platforms. */ #ifndef __need_IOV_MAX #define __need_IOV_MAX #endif #include <pwd.h> #include <sys/mman.h> #include <fcntl.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <assert.h> #include <limits.h> #include <sysexits.h> #include <stddef.h> #ifdef HAVE_GETOPT_LONG #include <getopt.h> #endif #ifdef TLS #include "tls.h" #endif #if defined(__FreeBSD__) #include <sys/sysctl.h> #endif /* FreeBSD 4.x doesn't have IOV_MAX exposed. */ #ifndef IOV_MAX #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__) # define IOV_MAX 1024 /* GNU/Hurd don't set MAXPATHLEN * http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */ #ifndef MAXPATHLEN #define MAXPATHLEN 4096 #endif #endif #endif /* * forward declarations */ static void drive_machine(conn *c); static int new_socket(struct addrinfo *ai); static ssize_t tcp_read(conn *arg, void *buf, size_t count); static ssize_t tcp_sendmsg(conn *arg, struct msghdr *msg, int flags); static ssize_t tcp_write(conn *arg, void *buf, size_t count); enum try_read_result { READ_DATA_RECEIVED, READ_NO_DATA_RECEIVED, READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */ READ_MEMORY_ERROR /** failed to allocate more memory */ }; static int try_read_command_negotiate(conn *c); static int try_read_command_udp(conn *c); static int try_read_command_binary(conn *c); static int try_read_command_ascii(conn *c); static int try_read_command_asciiauth(conn *c); static enum try_read_result try_read_network(conn *c); static enum try_read_result try_read_udp(conn *c); static void conn_set_state(conn *c, enum conn_states state); static int start_conn_timeout_thread(); /* stats */ static void stats_init(void); static void server_stats(ADD_STAT add_stats, conn *c); static void process_stat_settings(ADD_STAT add_stats, void *c); static void conn_to_str(const conn *c, char *addr, char *svr_addr); /** Return a datum for stats in binary protocol */ static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c); /* defaults */ static void settings_init(void); /* event handling, network IO */ static void event_handler(const int fd, const short which, void *arg); static void conn_close(conn *c); static void conn_init(void); static bool update_event(conn *c, const int new_flags); static void complete_nread(conn *c); static void process_command(conn *c, char *command); static void write_and_free(conn *c, char *buf, int bytes); static int ensure_iov_space(conn *c); static int add_iov(conn *c, const void *buf, int len); static int add_chunked_item_iovs(conn *c, item *it, int len); static int add_msghdr(conn *c); static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow); static void write_bin_miss_response(conn *c, char *key, size_t nkey); #ifdef EXTSTORE static void _get_extstore_cb(void *e, obj_io *io, int ret); static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt); #endif static void conn_free(conn *c); /** exported globals **/ struct stats stats; struct stats_state stats_state; struct settings settings; time_t process_started; /* when the process was started */ conn **conns; struct slab_rebalance slab_rebal; volatile int slab_rebalance_signal; #ifdef EXTSTORE /* hoping this is temporary; I'd prefer to cut globals, but will complete this * battle another day. */ void *ext_storage; #endif /** file scope variables **/ static conn *listen_conn = NULL; static int max_fds; static struct event_base *main_base; enum transmit_result { TRANSMIT_COMPLETE, /** All done writing. */ TRANSMIT_INCOMPLETE, /** More data remaining to write. */ TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */ TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */ }; /* Default methods to read from/ write to a socket */ ssize_t tcp_read(conn *c, void *buf, size_t count) { assert (c != NULL); return read(c->sfd, buf, count); } ssize_t tcp_sendmsg(conn *c, struct msghdr *msg, int flags) { assert (c != NULL); return sendmsg(c->sfd, msg, flags); } ssize_t tcp_write(conn *c, void *buf, size_t count) { assert (c != NULL); return write(c->sfd, buf, count); } static enum transmit_result transmit(conn *c); /* This reduces the latency without adding lots of extra wiring to be able to * notify the listener thread of when to listen again. * Also, the clock timer could be broken out into its own thread and we * can block the listener via a condition. */ static volatile bool allow_new_conns = true; static struct event maxconnsevent; static void maxconns_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 0, .tv_usec = 10000}; if (fd == -42 || allow_new_conns == false) { /* reschedule in 10ms if we need to keep polling */ evtimer_set(&maxconnsevent, maxconns_handler, 0); event_base_set(main_base, &maxconnsevent); evtimer_add(&maxconnsevent, &t); } else { evtimer_del(&maxconnsevent); accept_new_conns(true); } } #define REALTIME_MAXDELTA 60*60*24*30 /* * given time value that's either unix time or delta from current unix time, return * unix time. Use the fact that delta can't exceed one month (and real time value can't * be that low). */ static rel_time_t realtime(const time_t exptime) { /* no. of seconds in 30 days - largest possible delta exptime */ if (exptime == 0) return 0; /* 0 means never expire */ if (exptime > REALTIME_MAXDELTA) { /* if item expiration is at/before the server started, give it an expiration time of 1 second after the server started. (because 0 means don't expire). without this, we'd underflow and wrap around to some large value way in the future, effectively making items expiring in the past really expiring never */ if (exptime <= process_started) return (rel_time_t)1; return (rel_time_t)(exptime - process_started); } else { return (rel_time_t)(exptime + current_time); } } static void stats_init(void) { memset(&stats, 0, sizeof(struct stats)); memset(&stats_state, 0, sizeof(struct stats_state)); stats_state.accepting_conns = true; /* assuming we start in this state. */ /* make the time we started always be 2 seconds before we really did, so time(0) - time.started is never zero. if so, things like 'settings.oldest_live' which act as booleans as well as values are now false in boolean context... */ process_started = time(0) - ITEM_UPDATE_INTERVAL - 2; stats_prefix_init(); } static void stats_reset(void) { STATS_LOCK(); memset(&stats, 0, sizeof(struct stats)); stats_prefix_clear(); STATS_UNLOCK(); threadlocal_stats_reset(); item_stats_reset(); } static void settings_init(void) { settings.use_cas = true; settings.access = 0700; settings.port = 11211; settings.udpport = 0; #ifdef TLS settings.ssl_enabled = false; settings.ssl_ctx = NULL; settings.ssl_chain_cert = NULL; settings.ssl_key = NULL; settings.ssl_verify_mode = SSL_VERIFY_NONE; settings.ssl_keyformat = SSL_FILETYPE_PEM; settings.ssl_ciphers = NULL; settings.ssl_ca_cert = NULL; settings.ssl_last_cert_refresh_time = current_time; settings.ssl_wbuf_size = 16 * 1024; // default is 16KB (SSL max frame size is 17KB) #endif /* By default this string should be NULL for getaddrinfo() */ settings.inter = NULL; settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */ settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */ settings.verbose = 0; settings.oldest_live = 0; settings.oldest_cas = 0; /* supplements accuracy of oldest_live */ settings.evict_to_free = 1; /* push old items out of cache when memory runs out */ settings.socketpath = NULL; /* by default, not using a unix socket */ settings.auth_file = NULL; /* by default, not using ASCII authentication tokens */ settings.factor = 1.25; settings.chunk_size = 48; /* space for a modest key and value */ settings.num_threads = 4; /* N workers */ settings.num_threads_per_udp = 0; settings.prefix_delimiter = ':'; settings.detail_enabled = 0; settings.reqs_per_event = 20; settings.backlog = 1024; settings.binding_protocol = negotiating_prot; settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */ settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */ settings.slab_chunk_size_max = settings.slab_page_size / 2; settings.sasl = false; settings.maxconns_fast = true; settings.lru_crawler = false; settings.lru_crawler_sleep = 100; settings.lru_crawler_tocrawl = 0; settings.lru_maintainer_thread = false; settings.lru_segmented = true; settings.hot_lru_pct = 20; settings.warm_lru_pct = 40; settings.hot_max_factor = 0.2; settings.warm_max_factor = 2.0; settings.temp_lru = false; settings.temporary_ttl = 61; settings.idle_timeout = 0; /* disabled */ settings.hashpower_init = 0; settings.slab_reassign = true; settings.slab_automove = 1; settings.slab_automove_ratio = 0.8; settings.slab_automove_window = 30; settings.shutdown_command = false; settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT; settings.flush_enabled = true; settings.dump_enabled = true; settings.crawls_persleep = 1000; settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE; settings.logger_buf_size = LOGGER_BUF_SIZE; settings.drop_privileges = false; #ifdef MEMCACHED_DEBUG settings.relaxed_privileges = false; #endif } /* * Adds a message header to a connection. * * Returns 0 on success, -1 on out-of-memory. */ static int add_msghdr(conn *c) { struct msghdr *msg; assert(c != NULL); if (c->msgsize == c->msgused) { msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr)); if (! msg) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->msglist = msg; c->msgsize *= 2; } msg = c->msglist + c->msgused; /* this wipes msg_iovlen, msg_control, msg_controllen, and msg_flags, the last 3 of which aren't defined on solaris: */ memset(msg, 0, sizeof(struct msghdr)); msg->msg_iov = &c->iov[c->iovused]; if (IS_UDP(c->transport) && c->request_addr_size > 0) { msg->msg_name = &c->request_addr; msg->msg_namelen = c->request_addr_size; } c->msgbytes = 0; c->msgused++; if (IS_UDP(c->transport)) { /* Leave room for the UDP header, which we'll fill in later. */ return add_iov(c, NULL, UDP_HEADER_SIZE); } return 0; } extern pthread_mutex_t conn_lock; /* Connection timeout thread bits */ static pthread_t conn_timeout_tid; #define CONNS_PER_SLICE 100 #define TIMEOUT_MSG_SIZE (1 + sizeof(int)) static void *conn_timeout_thread(void *arg) { int i; conn *c; char buf[TIMEOUT_MSG_SIZE]; rel_time_t oldest_last_cmd; int sleep_time; useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE); while(1) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread at top of connection list\n"); oldest_last_cmd = current_time; for (i = 0; i < max_fds; i++) { if ((i % CONNS_PER_SLICE) == 0) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread sleeping for %ulus\n", (unsigned int)timeslice); usleep(timeslice); } if (!conns[i]) continue; c = conns[i]; if (!IS_TCP(c->transport)) continue; if (c->state != conn_new_cmd && c->state != conn_read) continue; if ((current_time - c->last_cmd_time) > settings.idle_timeout) { buf[0] = 't'; memcpy(&buf[1], &i, sizeof(int)); if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE) != TIMEOUT_MSG_SIZE) perror("Failed to write timeout to notify pipe"); } else { if (c->last_cmd_time < oldest_last_cmd) oldest_last_cmd = c->last_cmd_time; } } /* This is the soonest we could have another connection time out */ sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1; if (sleep_time <= 0) sleep_time = 1; if (settings.verbose > 2) fprintf(stderr, "idle timeout thread finished pass, sleeping for %ds\n", sleep_time); usleep((useconds_t) sleep_time * 1000000); } return NULL; } static int start_conn_timeout_thread() { int ret; if (settings.idle_timeout == 0) return -1; if ((ret = pthread_create(&conn_timeout_tid, NULL, conn_timeout_thread, NULL)) != 0) { fprintf(stderr, "Can't create idle connection timeout thread: %s\n", strerror(ret)); return -1; } return 0; } /* * Initializes the connections array. We don't actually allocate connection * structures until they're needed, so as to avoid wasting memory when the * maximum connection count is much higher than the actual number of * connections. * * This does end up wasting a few pointers' worth of memory for FDs that are * used for things other than connections, but that's worth it in exchange for * being able to directly index the conns array by FD. */ static void conn_init(void) { /* We're unlikely to see an FD much higher than maxconns. */ int next_fd = dup(1); if (next_fd < 0) { perror("Failed to duplicate file descriptor\n"); exit(1); } int headroom = 10; /* account for extra unexpected open FDs */ struct rlimit rl; max_fds = settings.maxconns + headroom + next_fd; /* But if possible, get the actual highest FD we can possibly ever see. */ if (getrlimit(RLIMIT_NOFILE, &rl) == 0) { max_fds = rl.rlim_max; } else { fprintf(stderr, "Failed to query maximum file descriptor; " "falling back to maxconns\n"); } close(next_fd); if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) { fprintf(stderr, "Failed to allocate connection structures\n"); /* This is unrecoverable so bail out early. */ exit(1); } } static const char *prot_text(enum protocol prot) { char *rv = "unknown"; switch(prot) { case ascii_prot: rv = "ascii"; break; case binary_prot: rv = "binary"; break; case negotiating_prot: rv = "auto-negotiate"; break; } return rv; } void conn_close_idle(conn *c) { if (settings.idle_timeout > 0 && (current_time - c->last_cmd_time) > settings.idle_timeout) { if (c->state != conn_new_cmd && c->state != conn_read) { if (settings.verbose > 1) fprintf(stderr, "fd %d wants to timeout, but isn't in read state", c->sfd); return; } if (settings.verbose > 1) fprintf(stderr, "Closing idle fd %d\n", c->sfd); c->thread->stats.idle_kicks++; conn_set_state(c, conn_closing); drive_machine(c); } } /* bring conn back from a sidethread. could have had its event base moved. */ void conn_worker_readd(conn *c) { c->ev_flags = EV_READ | EV_PERSIST; event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c); event_base_set(c->thread->base, &c->event); c->state = conn_new_cmd; // TODO: call conn_cleanup/fail/etc if (event_add(&c->event, 0) == -1) { perror("event_add"); } #ifdef EXTSTORE // If we had IO objects, process if (c->io_wraplist) { //assert(c->io_wrapleft == 0); // assert no more to process conn_set_state(c, conn_mwrite); drive_machine(c); } #endif } conn *conn_new(const int sfd, enum conn_states init_state, const int event_flags, const int read_buffer_size, enum network_transport transport, struct event_base *base, void *ssl) { conn *c; assert(sfd >= 0 && sfd < max_fds); c = conns[sfd]; if (NULL == c) { if (!(c = (conn *)calloc(1, sizeof(conn)))) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate connection object\n"); return NULL; } MEMCACHED_CONN_CREATE(c); c->read = NULL; c->sendmsg = NULL; c->write = NULL; c->rbuf = c->wbuf = 0; c->ilist = 0; c->suffixlist = 0; c->iov = 0; c->msglist = 0; c->hdrbuf = 0; c->rsize = read_buffer_size; c->wsize = DATA_BUFFER_SIZE; c->isize = ITEM_LIST_INITIAL; c->suffixsize = SUFFIX_LIST_INITIAL; c->iovsize = IOV_LIST_INITIAL; c->msgsize = MSG_LIST_INITIAL; c->hdrsize = 0; c->rbuf = (char *)malloc((size_t)c->rsize); c->wbuf = (char *)malloc((size_t)c->wsize); c->ilist = (item **)malloc(sizeof(item *) * c->isize); c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || c->msglist == 0 || c->suffixlist == 0) { conn_free(c); STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate buffers for connection\n"); return NULL; } STATS_LOCK(); stats_state.conn_structs++; STATS_UNLOCK(); c->sfd = sfd; conns[sfd] = c; } c->transport = transport; c->protocol = settings.binding_protocol; /* unix socket mode doesn't need this, so zeroed out. but why * is this done for every command? presumably for UDP * mode. */ if (!settings.socketpath) { c->request_addr_size = sizeof(c->request_addr); } else { c->request_addr_size = 0; } if (transport == tcp_transport && init_state == conn_new_cmd) { if (getpeername(sfd, (struct sockaddr *) &c->request_addr, &c->request_addr_size)) { perror("getpeername"); memset(&c->request_addr, 0, sizeof(c->request_addr)); } } if (settings.verbose > 1) { if (init_state == conn_listening) { fprintf(stderr, "<%d server listening (%s)\n", sfd, prot_text(c->protocol)); } else if (IS_UDP(transport)) { fprintf(stderr, "<%d server listening (udp)\n", sfd); } else if (c->protocol == negotiating_prot) { fprintf(stderr, "<%d new auto-negotiating client connection\n", sfd); } else if (c->protocol == ascii_prot) { fprintf(stderr, "<%d new ascii client connection.\n", sfd); } else if (c->protocol == binary_prot) { fprintf(stderr, "<%d new binary client connection.\n", sfd); } else { fprintf(stderr, "<%d new unknown (%d) client connection\n", sfd, c->protocol); assert(false); } } #ifdef TLS c->ssl = NULL; c->ssl_wbuf = NULL; c->ssl_enabled = false; #endif c->state = init_state; c->rlbytes = 0; c->cmd = -1; c->rbytes = c->wbytes = 0; c->wcurr = c->wbuf; c->rcurr = c->rbuf; c->ritem = 0; c->icurr = c->ilist; c->suffixcurr = c->suffixlist; c->ileft = 0; c->suffixleft = 0; c->iovused = 0; c->msgcurr = 0; c->msgused = 0; c->sasl_started = false; c->last_cmd_time = current_time; /* initialize for idle kicker */ #ifdef EXTSTORE c->io_wraplist = NULL; c->io_wrapleft = 0; #endif c->write_and_go = init_state; c->write_and_free = 0; c->item = 0; c->noreply = false; #ifdef TLS if (ssl) { c->ssl = (SSL*)ssl; c->read = ssl_read; c->sendmsg = ssl_sendmsg; c->write = ssl_write; c->ssl_enabled = true; SSL_set_info_callback(c->ssl, ssl_callback); } else #else // This must be NULL if TLS is not enabled. assert(ssl == NULL); #endif { c->read = tcp_read; c->sendmsg = tcp_sendmsg; c->write = tcp_write; } if (IS_UDP(transport)) { c->try_read_command = try_read_command_udp; } else { switch (c->protocol) { case ascii_prot: if (settings.auth_file == NULL) { c->authenticated = true; c->try_read_command = try_read_command_ascii; } else { c->authenticated = false; c->try_read_command = try_read_command_asciiauth; } break; case binary_prot: // binprot handles its own authentication via SASL parsing. c->authenticated = false; c->try_read_command = try_read_command_binary; break; case negotiating_prot: c->try_read_command = try_read_command_negotiate; break; } } event_set(&c->event, sfd, event_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = event_flags; if (event_add(&c->event, 0) == -1) { perror("event_add"); return NULL; } STATS_LOCK(); stats_state.curr_conns++; stats.total_conns++; STATS_UNLOCK(); MEMCACHED_CONN_ALLOCATE(c->sfd); return c; } #ifdef EXTSTORE static void recache_or_free(conn *c, io_wrap *wrap) { item *it; it = (item *)wrap->io.buf; bool do_free = true; if (wrap->active) { // If request never dispatched, free the read buffer but leave the // item header alone. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); c->io_wrapleft--; assert(c->io_wrapleft >= 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_aborted_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (wrap->miss) { // If request was ultimately a miss, unlink the header. do_free = false; size_t ntotal = ITEM_ntotal(wrap->hdr_it); item_unlink(wrap->hdr_it); slabs_free(it, ntotal, slabs_clsid(ntotal)); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.miss_from_extstore++; if (wrap->badcrc) c->thread->stats.badcrc_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (settings.ext_recache_rate) { // hashvalue is cuddled during store uint32_t hv = (uint32_t)it->time; // opt to throw away rather than wait on a lock. void *hold_lock = item_trylock(hv); if (hold_lock != NULL) { item *h_it = wrap->hdr_it; uint8_t flags = ITEM_LINKED|ITEM_FETCHED|ITEM_ACTIVE; // Item must be recently hit at least twice to recache. if (((h_it->it_flags & flags) == flags) && h_it->time > current_time - ITEM_UPDATE_INTERVAL && c->recache_counter++ % settings.ext_recache_rate == 0) { do_free = false; // In case it's been updated. it->exptime = h_it->exptime; it->it_flags &= ~ITEM_LINKED; it->refcount = 0; it->h_next = NULL; // might not be necessary. STORAGE_delete(c->thread->storage, h_it); item_replace(h_it, it, hv); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.recache_from_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); } } if (hold_lock) item_trylock_unlock(hold_lock); } if (do_free) slabs_free(it, ITEM_ntotal(it), ITEM_clsid(it)); wrap->io.buf = NULL; // sanity. wrap->io.next = NULL; wrap->next = NULL; wrap->active = false; // TODO: reuse lock and/or hv. item_remove(wrap->hdr_it); } #endif static void conn_release_items(conn *c) { assert(c != NULL); if (c->item) { item_remove(c->item); c->item = 0; } while (c->ileft > 0) { item *it = *(c->icurr); assert((it->it_flags & ITEM_SLABBED) == 0); item_remove(it); c->icurr++; c->ileft--; } if (c->suffixleft != 0) { for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) { do_cache_free(c->thread->suffix_cache, *(c->suffixcurr)); } } #ifdef EXTSTORE if (c->io_wraplist) { io_wrap *tmp = c->io_wraplist; while (tmp) { io_wrap *next = tmp->next; recache_or_free(c, tmp); do_cache_free(c->thread->io_cache, tmp); // lockless tmp = next; } c->io_wraplist = NULL; } #endif c->icurr = c->ilist; c->suffixcurr = c->suffixlist; } static void conn_cleanup(conn *c) { assert(c != NULL); conn_release_items(c); if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } if (c->sasl_conn) { assert(settings.sasl); sasl_dispose(&c->sasl_conn); c->sasl_conn = NULL; } if (IS_UDP(c->transport)) { conn_set_state(c, conn_read); } } /* * Frees a connection. */ void conn_free(conn *c) { if (c) { assert(c != NULL); assert(c->sfd >= 0 && c->sfd < max_fds); MEMCACHED_CONN_DESTROY(c); conns[c->sfd] = NULL; if (c->hdrbuf) free(c->hdrbuf); if (c->msglist) free(c->msglist); if (c->rbuf) free(c->rbuf); if (c->wbuf) free(c->wbuf); if (c->ilist) free(c->ilist); if (c->suffixlist) free(c->suffixlist); if (c->iov) free(c->iov); #ifdef TLS if (c->ssl_wbuf) c->ssl_wbuf = NULL; #endif free(c); } } static void conn_close(conn *c) { assert(c != NULL); /* delete the event, the socket and the conn */ event_del(&c->event); if (settings.verbose > 1) fprintf(stderr, "<%d connection closed.\n", c->sfd); conn_cleanup(c); MEMCACHED_CONN_RELEASE(c->sfd); conn_set_state(c, conn_closed); #ifdef TLS if (c->ssl) { SSL_shutdown(c->ssl); SSL_free(c->ssl); } #endif close(c->sfd); pthread_mutex_lock(&conn_lock); allow_new_conns = true; pthread_mutex_unlock(&conn_lock); STATS_LOCK(); stats_state.curr_conns--; STATS_UNLOCK(); return; } /* * Shrinks a connection's buffers if they're too big. This prevents * periodic large "get" requests from permanently chewing lots of server * memory. * * This should only be called in between requests since it can wipe output * buffers! */ static void conn_shrink(conn *c) { assert(c != NULL); if (IS_UDP(c->transport)) return; if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) { char *newbuf; if (c->rcurr != c->rbuf) memmove(c->rbuf, c->rcurr, (size_t)c->rbytes); newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE); if (newbuf) { c->rbuf = newbuf; c->rsize = DATA_BUFFER_SIZE; } /* TODO check other branch... */ c->rcurr = c->rbuf; } if (c->isize > ITEM_LIST_HIGHWAT) { item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0])); if (newbuf) { c->ilist = newbuf; c->isize = ITEM_LIST_INITIAL; } /* TODO check error condition? */ } if (c->msgsize > MSG_LIST_HIGHWAT) { struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0])); if (newbuf) { c->msglist = newbuf; c->msgsize = MSG_LIST_INITIAL; } /* TODO check error condition? */ } if (c->iovsize > IOV_LIST_HIGHWAT) { struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0])); if (newbuf) { c->iov = newbuf; c->iovsize = IOV_LIST_INITIAL; } /* TODO check return value */ } } /** * Convert a state name to a human readable form. */ static const char *state_text(enum conn_states state) { const char* const statenames[] = { "conn_listening", "conn_new_cmd", "conn_waiting", "conn_read", "conn_parse_cmd", "conn_write", "conn_nread", "conn_swallow", "conn_closing", "conn_mwrite", "conn_closed", "conn_watch" }; return statenames[state]; } /* * Sets a connection's current state in the state machine. Any special * processing that needs to happen on certain state transitions can * happen here. */ static void conn_set_state(conn *c, enum conn_states state) { assert(c != NULL); assert(state >= conn_listening && state < conn_max_state); if (state != c->state) { if (settings.verbose > 2) { fprintf(stderr, "%d: going from %s to %s\n", c->sfd, state_text(c->state), state_text(state)); } if (state == conn_write || state == conn_mwrite) { MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes); } c->state = state; } } /* * Ensures that there is room for another struct iovec in a connection's * iov list. * * Returns 0 on success, -1 on out-of-memory. */ static int ensure_iov_space(conn *c) { assert(c != NULL); if (c->iovused >= c->iovsize) { int i, iovnum; struct iovec *new_iov = (struct iovec *)realloc(c->iov, (c->iovsize * 2) * sizeof(struct iovec)); if (! new_iov) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->iov = new_iov; c->iovsize *= 2; /* Point all the msghdr structures at the new list. */ for (i = 0, iovnum = 0; i < c->msgused; i++) { c->msglist[i].msg_iov = &c->iov[iovnum]; iovnum += c->msglist[i].msg_iovlen; } } return 0; } /* * Adds data to the list of pending data that will be written out to a * connection. * * Returns 0 on success, -1 on out-of-memory. * Note: This is a hot path for at least ASCII protocol. While there is * redundant code in splitting TCP/UDP handling, any reduction in steps has a * large impact for TCP connections. */ static int add_iov(conn *c, const void *buf, int len) { struct msghdr *m; int leftover; assert(c != NULL); if (IS_UDP(c->transport)) { do { m = &c->msglist[c->msgused - 1]; /* * Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes. */ /* We may need to start a new msghdr if this one is full. */ if (m->msg_iovlen == IOV_MAX || (c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; /* If the fragment is too big to fit in the datagram, split it up */ if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) { leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE; len -= leftover; } else { leftover = 0; } m = &c->msglist[c->msgused - 1]; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; buf = ((char *)buf) + len; len = leftover; } while (leftover > 0); } else { /* Optimized path for TCP connections */ m = &c->msglist[c->msgused - 1]; if (m->msg_iovlen == IOV_MAX) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; } return 0; } static int add_chunked_item_iovs(conn *c, item *it, int len) { assert(it->it_flags & ITEM_CHUNKED); item_chunk *ch = (item_chunk *) ITEM_schunk(it); while (ch) { int todo = (len > ch->used) ? ch->used : len; if (add_iov(c, ch->data, todo) != 0) { return -1; } ch = ch->next; len -= todo; } return 0; } /* * Constructs a set of UDP headers and attaches them to the outgoing messages. */ static int build_udp_headers(conn *c) { int i; unsigned char *hdr; assert(c != NULL); if (c->msgused > c->hdrsize) { void *new_hdrbuf; if (c->hdrbuf) { new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE); } else { new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE); } if (! new_hdrbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->hdrbuf = (unsigned char *)new_hdrbuf; c->hdrsize = c->msgused * 2; } hdr = c->hdrbuf; for (i = 0; i < c->msgused; i++) { c->msglist[i].msg_iov[0].iov_base = (void*)hdr; c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE; *hdr++ = c->request_id / 256; *hdr++ = c->request_id % 256; *hdr++ = i / 256; *hdr++ = i % 256; *hdr++ = c->msgused / 256; *hdr++ = c->msgused % 256; *hdr++ = 0; *hdr++ = 0; assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE); } return 0; } static void out_string(conn *c, const char *str) { size_t len; assert(c != NULL); if (c->noreply) { if (settings.verbose > 1) fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str); c->noreply = false; conn_set_state(c, conn_new_cmd); return; } if (settings.verbose > 1) fprintf(stderr, ">%d %s\n", c->sfd, str); /* Nuke a partial output... */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; add_msghdr(c); len = strlen(str); if ((len + 2) > c->wsize) { /* ought to be always enough. just fail for simplicity */ str = "SERVER_ERROR output line too long"; len = strlen(str); } memcpy(c->wbuf, str, len); memcpy(c->wbuf + len, "\r\n", 2); c->wbytes = len + 2; c->wcurr = c->wbuf; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; return; } /* * Outputs a protocol-specific "out of memory" error. For ASCII clients, * this is equivalent to out_string(). */ static void out_of_memory(conn *c, char *ascii_error) { const static char error_prefix[] = "SERVER_ERROR "; const static int error_prefix_len = sizeof(error_prefix) - 1; if (c->protocol == binary_prot) { /* Strip off the generic error prefix; it's irrelevant in binary */ if (!strncmp(ascii_error, error_prefix, error_prefix_len)) { ascii_error += error_prefix_len; } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0); } else { out_string(c, ascii_error); } } /* * we get here after reading the value in set/add/replace commands. The command * has been stored in c->cmd, and the item is ready in c->item. */ static void complete_nread_ascii(conn *c) { assert(c != NULL); item *it = c->item; int comm = c->cmd; enum store_item_type ret; bool is_valid = false; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if ((it->it_flags & ITEM_CHUNKED) == 0) { if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) { is_valid = true; } } else { char buf[2]; /* should point to the final item chunk */ item_chunk *ch = (item_chunk *) c->ritem; assert(ch->used != 0); /* :( We need to look at the last two bytes. This could span two * chunks. */ if (ch->used > 1) { buf[0] = ch->data[ch->used - 2]; buf[1] = ch->data[ch->used - 1]; } else { assert(ch->prev); assert(ch->used == 1); buf[0] = ch->prev->data[ch->prev->used - 1]; buf[1] = ch->data[ch->used - 1]; } if (strncmp(buf, "\r\n", 2) == 0) { is_valid = true; } else { assert(1 == 0); } } if (!is_valid) { out_string(c, "CLIENT_ERROR bad data chunk"); } else { ret = store_item(it, comm, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_CAS: MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes, cas); break; } #endif switch (ret) { case STORED: out_string(c, "STORED"); break; case EXISTS: out_string(c, "EXISTS"); break; case NOT_FOUND: out_string(c, "NOT_FOUND"); break; case NOT_STORED: out_string(c, "NOT_STORED"); break; default: out_string(c, "SERVER_ERROR Unhandled storage type."); } } item_remove(c->item); /* release the c->item reference */ c->item = 0; } /** * get a pointer to the start of the request struct for the current command */ static void* binary_get_request(conn *c) { char *ret = c->rcurr; ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen + c->binary_header.request.extlen); assert(ret >= c->rbuf); return ret; } /** * get a pointer to the key in this request */ static char* binary_get_key(conn *c) { return c->rcurr - (c->binary_header.request.keylen); } static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) { protocol_binary_response_header* header; assert(c); c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { /* This should never run out of memory because iov and msg lists * have minimum sizes big enough to hold an error response. */ out_of_memory(c, "SERVER_ERROR out of memory adding binary header"); return; } header = (protocol_binary_response_header *)c->wbuf; header->response.magic = (uint8_t)PROTOCOL_BINARY_RES; header->response.opcode = c->binary_header.request.opcode; header->response.keylen = (uint16_t)htons(key_len); header->response.extlen = (uint8_t)hdr_len; header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES; header->response.status = (uint16_t)htons(err); header->response.bodylen = htonl(body_len); header->response.opaque = c->opaque; header->response.cas = htonll(c->cas); if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d Writing bin response:", c->sfd); for (ii = 0; ii < sizeof(header->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n>%d ", c->sfd); } fprintf(stderr, " 0x%02x", header->bytes[ii]); } fprintf(stderr, "\n"); } add_iov(c, c->wbuf, sizeof(header->response)); } /** * Writes a binary error response. If errstr is supplied, it is used as the * error text; otherwise a generic description of the error status code is * included. */ static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow) { size_t len; if (!errstr) { switch (err) { case PROTOCOL_BINARY_RESPONSE_ENOMEM: errstr = "Out of memory"; break; case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND: errstr = "Unknown command"; break; case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT: errstr = "Not found"; break; case PROTOCOL_BINARY_RESPONSE_EINVAL: errstr = "Invalid arguments"; break; case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS: errstr = "Data exists for key."; break; case PROTOCOL_BINARY_RESPONSE_E2BIG: errstr = "Too large."; break; case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL: errstr = "Non-numeric server-side value for incr or decr"; break; case PROTOCOL_BINARY_RESPONSE_NOT_STORED: errstr = "Not stored."; break; case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR: errstr = "Auth failure."; break; default: assert(false); errstr = "UNHANDLED ERROR"; fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err); } } if (settings.verbose > 1) { fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr); } len = strlen(errstr); add_bin_header(c, err, 0, 0, len); if (len > 0) { add_iov(c, errstr, len); } conn_set_state(c, conn_mwrite); if(swallow > 0) { c->sbytes = swallow; c->write_and_go = conn_swallow; } else { c->write_and_go = conn_new_cmd; } } /* Form and send a response to a command over the binary protocol */ static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) { if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET || c->cmd == PROTOCOL_BINARY_CMD_GETK) { add_bin_header(c, 0, hlen, keylen, dlen); if(dlen > 0) { add_iov(c, d, dlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { conn_set_state(c, conn_new_cmd); } } static void complete_incr_bin(conn *c) { item *it; char *key; size_t nkey; /* Weird magic in add_delta forces me to pad here */ char tmpbuf[INCR_MAX_STORAGE_LEN]; uint64_t cas = 0; protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf; protocol_binary_request_incr* req = binary_get_request(c); assert(c != NULL); assert(c->wsize >= sizeof(*rsp)); /* fix byteorder in the request */ req->message.body.delta = ntohll(req->message.body.delta); req->message.body.initial = ntohll(req->message.body.initial); req->message.body.expiration = ntohl(req->message.body.expiration); key = binary_get_key(c); nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int i; fprintf(stderr, "incr "); for (i = 0; i < nkey; i++) { fprintf(stderr, "%c", key[i]); } fprintf(stderr, " %lld, %llu, %d\n", (long long)req->message.body.delta, (long long)req->message.body.initial, req->message.body.expiration); } if (c->binary_header.request.cas != 0) { cas = c->binary_header.request.cas; } switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT, req->message.body.delta, tmpbuf, &cas)) { case OK: rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10)); if (cas) { c->cas = cas; } write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); break; case NON_NUMERIC: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0); break; case EOM: out_of_memory(c, "SERVER_ERROR Out of memory incrementing value"); break; case DELTA_ITEM_NOT_FOUND: if (req->message.body.expiration != 0xffffffff) { /* Save some room for the response */ rsp->message.body.value = htonll(req->message.body.initial); snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)req->message.body.initial); int res = strlen(tmpbuf); it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration), res + 2); if (it != NULL) { memcpy(ITEM_data(it), tmpbuf, res); memcpy(ITEM_data(it) + res, "\r\n", 2); if (store_item(it, NREAD_ADD, c)) { c->cas = ITEM_get_cas(it); write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, NULL, 0); } item_remove(it); /* release our reference */ } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating new item"); } } else { pthread_mutex_lock(&c->thread->stats.mutex); if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } break; case DELTA_ITEM_CAS_MISMATCH: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; } } static void complete_update_bin(conn *c) { protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL; enum store_item_type ret = NOT_STORED; assert(c != NULL); item *it = c->item; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); /* We don't actually receive the trailing two characters in the bin * protocol, so we're going to just set them here */ if ((it->it_flags & ITEM_CHUNKED) == 0) { *(ITEM_data(it) + it->nbytes - 2) = '\r'; *(ITEM_data(it) + it->nbytes - 1) = '\n'; } else { assert(c->ritem); item_chunk *ch = (item_chunk *) c->ritem; if (ch->size == ch->used) ch = ch->next; assert(ch->size - ch->used >= 2); ch->data[ch->used] = '\r'; ch->data[ch->used + 1] = '\n'; ch->used += 2; } ret = store_item(it, c->cmd, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; } #endif switch (ret) { case STORED: /* Stored */ write_bin_response(c, NULL, 0, 0, 0); break; case EXISTS: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; case NOT_FOUND: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); break; case NOT_STORED: case TOO_LARGE: case NO_MEMORY: if (c->cmd == NREAD_ADD) { eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS; } else if(c->cmd == NREAD_REPLACE) { eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT; } else { eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED; } write_bin_error(c, eno, NULL, 0); } item_remove(c->item); /* release the c->item reference */ c->item = 0; } static void write_bin_miss_response(conn *c, char *key, size_t nkey) { if (nkey) { char *ofs = c->wbuf + sizeof(protocol_binary_response_header); add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0, nkey, nkey); memcpy(ofs, key, nkey); add_iov(c, ofs, nkey); conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } } static void process_bin_get_or_touch(conn *c) { item *it; protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf; char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH || c->cmd == PROTOCOL_BINARY_CMD_GAT || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH); bool failed = false; if (settings.verbose > 1) { fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET"); if (fwrite(key, 1, nkey, stderr)) {} fputc('\n', stderr); } if (should_touch) { protocol_binary_request_touch *t = binary_get_request(c); time_t exptime = ntohl(t->message.body.expiration); it = item_touch(key, nkey, realtime(exptime), c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it) { /* the length has two unnecessary bytes ("\r\n") */ uint16_t keylen = 0; uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2); pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.get_cmds++; c->thread->stats.lru_hits[it->slabs_clsid]++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) { bodylen -= it->nbytes - 2; } else if (should_return_key) { bodylen += nkey; keylen = nkey; } add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen); rsp->message.header.response.cas = htonll(ITEM_get_cas(it)); // add the flags FLAGS_CONV(it, rsp->message.body.flags); rsp->message.body.flags = htonl(rsp->message.body.flags); add_iov(c, &rsp->message.body, sizeof(rsp->message.body)); if (should_return_key) { add_iov(c, ITEM_key(it), nkey); } if (should_return_value) { /* Add the data minus the CRLF */ #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { int iovcnt = 4; int iovst = c->iovused - 3; if (!should_return_key) { iovcnt = 3; iovst = c->iovused - 2; } if (_get_extstore(c, it, iovst, iovcnt) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); failed = true; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #else if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } #endif } if (!failed) { conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; /* Remember this command so we can garbage collect it later */ #ifdef EXTSTORE if ((it->it_flags & ITEM_HDR) != 0 && should_return_value) { // Only have extstore clean if header and returning value. c->item = NULL; } else { c->item = it; } #else c->item = it; #endif } else { item_remove(it); } } else { failed = true; } if (failed) { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_cmds++; c->thread->stats.get_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0); } else { MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } if (c->noreply) { conn_set_state(c, conn_new_cmd); } else { if (should_return_key) { write_bin_miss_response(c, key, nkey); } else { write_bin_miss_response(c, NULL, 0); } } } if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } } static void append_bin_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *buf = c->stats.buffer + c->stats.offset; uint32_t bodylen = klen + vlen; protocol_binary_response_header header = { .response.magic = (uint8_t)PROTOCOL_BINARY_RES, .response.opcode = PROTOCOL_BINARY_CMD_STAT, .response.keylen = (uint16_t)htons(klen), .response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES, .response.bodylen = htonl(bodylen), .response.opaque = c->opaque }; memcpy(buf, header.bytes, sizeof(header.response)); buf += sizeof(header.response); if (klen > 0) { memcpy(buf, key, klen); buf += klen; if (vlen > 0) { memcpy(buf, val, vlen); } } c->stats.offset += sizeof(header.response) + bodylen; } static void append_ascii_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *pos = c->stats.buffer + c->stats.offset; uint32_t nbytes = 0; int remaining = c->stats.size - c->stats.offset; int room = remaining - 1; if (klen == 0 && vlen == 0) { nbytes = snprintf(pos, room, "END\r\n"); } else if (vlen == 0) { nbytes = snprintf(pos, room, "STAT %s\r\n", key); } else { nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val); } c->stats.offset += nbytes; } static bool grow_stats_buf(conn *c, size_t needed) { size_t nsize = c->stats.size; size_t available = nsize - c->stats.offset; bool rv = true; /* Special case: No buffer -- need to allocate fresh */ if (c->stats.buffer == NULL) { nsize = 1024; available = c->stats.size = c->stats.offset = 0; } while (needed > available) { assert(nsize > 0); nsize = nsize << 1; available = nsize - c->stats.offset; } if (nsize != c->stats.size) { char *ptr = realloc(c->stats.buffer, nsize); if (ptr) { c->stats.buffer = ptr; c->stats.size = nsize; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); rv = false; } } return rv; } static void append_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, const void *cookie) { /* value without a key is invalid */ if (klen == 0 && vlen > 0) { return ; } conn *c = (conn*)cookie; if (c->protocol == binary_prot) { size_t needed = vlen + klen + sizeof(protocol_binary_response_header); if (!grow_stats_buf(c, needed)) { return ; } append_bin_stats(key, klen, val, vlen, c); } else { size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n" if (!grow_stats_buf(c, needed)) { return ; } append_ascii_stats(key, klen, val, vlen, c); } assert(c->stats.offset <= c->stats.size); } static void process_bin_stat(conn *c) { char *subcommand = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int ii; fprintf(stderr, "<%d STATS ", c->sfd); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", subcommand[ii]); } fprintf(stderr, "\n"); } if (nkey == 0) { /* request all statistics */ server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strncmp(subcommand, "reset", 5) == 0) { stats_reset(); } else if (strncmp(subcommand, "settings", 8) == 0) { process_stat_settings(&append_stats, c); } else if (strncmp(subcommand, "detail", 6) == 0) { char *subcmd_pos = subcommand + 6; if (strncmp(subcmd_pos, " dump", 5) == 0) { int len; char *dump_buf = stats_prefix_dump(&len); if (dump_buf == NULL || len <= 0) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); if (dump_buf != NULL) free(dump_buf); return; } else { append_stats("detailed", strlen("detailed"), dump_buf, len, c); free(dump_buf); } } else if (strncmp(subcmd_pos, " on", 3) == 0) { settings.detail_enabled = 1; } else if (strncmp(subcmd_pos, " off", 4) == 0) { settings.detail_enabled = 0; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); return; } } else { if (get_stats(subcommand, nkey, &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } return; } /* Append termination package and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) { assert(c); c->substate = next_substate; c->rlbytes = c->keylen + extra; /* Ok... do we have room for the extras and the key in the input buffer? */ ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf; if (c->rlbytes > c->rsize - offset) { size_t nsize = c->rsize; size_t size = c->rlbytes + sizeof(protocol_binary_request_header); while (size > nsize) { nsize *= 2; } if (nsize != c->rsize) { if (settings.verbose > 1) { fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n", c->sfd, (unsigned long)c->rsize, (unsigned long)nsize); } char *newm = realloc(c->rbuf, nsize); if (newm == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose) { fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n", c->sfd); } conn_set_state(c, conn_closing); return; } c->rbuf= newm; /* rcurr should point to the same offset in the packet */ c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header); c->rsize = nsize; } if (c->rbuf != c->rcurr) { memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Repack input buffer\n", c->sfd); } } } /* preserve the header in the buffer.. */ c->ritem = c->rcurr + sizeof(protocol_binary_request_header); conn_set_state(c, conn_nread); } /* Just write an error message and disconnect the client */ static void handle_binary_protocol_error(conn *c) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0); if (settings.verbose) { fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n", c->binary_header.request.opcode, c->sfd); } c->write_and_go = conn_closing; } static void init_sasl_conn(conn *c) { assert(c); /* should something else be returned? */ if (!settings.sasl) return; c->authenticated = false; if (!c->sasl_conn) { int result=sasl_server_new("memcached", NULL, my_sasl_hostname[0] ? my_sasl_hostname : NULL, NULL, NULL, NULL, 0, &c->sasl_conn); if (result != SASL_OK) { if (settings.verbose) { fprintf(stderr, "Failed to initialize SASL conn.\n"); } c->sasl_conn = NULL; } } } static void bin_list_sasl_mechs(conn *c) { // Guard against a disabled SASL. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } init_sasl_conn(c); const char *result_string = NULL; unsigned int string_length = 0; int result=sasl_listmech(c->sasl_conn, NULL, "", /* What to prepend the string with */ " ", /* What to separate mechanisms with */ "", /* What to append to the string */ &result_string, &string_length, NULL); if (result != SASL_OK) { /* Perhaps there's a better error for this... */ if (settings.verbose) { fprintf(stderr, "Failed to list SASL mechanisms.\n"); } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } write_bin_response(c, (char*)result_string, 0, 0, string_length); } static void process_bin_sasl_auth(conn *c) { // Guard for handling disabled SASL on the server. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } assert(c->binary_header.request.extlen == 0); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > MAX_SASL_MECH_LEN) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; return; } char *key = binary_get_key(c); assert(key); item *it = item_alloc(key, nkey, 0, 0, vlen+2); /* Can't use a chunked item for SASL authentication. */ if (it == 0 || (it->it_flags & ITEM_CHUNKED)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen); c->write_and_go = conn_swallow; return; } c->item = it; c->ritem = ITEM_data(it); c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_reading_sasl_auth_data; } static void process_bin_complete_sasl_auth(conn *c) { assert(settings.sasl); const char *out = NULL; unsigned int outlen = 0; assert(c->item); init_sasl_conn(c); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > ((item*) c->item)->nkey) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } char mech[nkey+1]; memcpy(mech, ITEM_key((item*)c->item), nkey); mech[nkey] = 0x00; if (settings.verbose) fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen); const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item); if (vlen > ((item*) c->item)->nbytes) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } int result=-1; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_AUTH: result = sasl_server_start(c->sasl_conn, mech, challenge, vlen, &out, &outlen); c->sasl_started = (result == SASL_OK || result == SASL_CONTINUE); break; case PROTOCOL_BINARY_CMD_SASL_STEP: if (!c->sasl_started) { if (settings.verbose) { fprintf(stderr, "%d: SASL_STEP called but sasl_server_start " "not called for this connection!\n", c->sfd); } break; } result = sasl_server_step(c->sasl_conn, challenge, vlen, &out, &outlen); break; default: assert(false); /* CMD should be one of the above */ /* This code is pretty much impossible, but makes the compiler happier */ if (settings.verbose) { fprintf(stderr, "Unhandled command %d with challenge %s\n", c->cmd, challenge); } break; } item_unlink(c->item); if (settings.verbose) { fprintf(stderr, "sasl result code: %d\n", result); } switch(result) { case SASL_OK: c->authenticated = true; write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated")); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); break; case SASL_CONTINUE: add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen); if(outlen > 0) { add_iov(c, out, outlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; break; default: if (settings.verbose) fprintf(stderr, "Unknown sasl response: %d\n", result); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } } static bool authenticated(conn *c) { assert(settings.sasl); bool rv = false; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */ rv = true; break; default: rv = c->authenticated; } if (settings.verbose > 1) { fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n", c->cmd, rv ? "true" : "false"); } return rv; } static void dispatch_bin_command(conn *c) { int protocol_error = 0; uint8_t extlen = c->binary_header.request.extlen; uint16_t keylen = c->binary_header.request.keylen; uint32_t bodylen = c->binary_header.request.bodylen; if (keylen > bodylen || keylen + extlen > bodylen) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0); c->write_and_go = conn_closing; return; } if (settings.sasl && !authenticated(c)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); c->write_and_go = conn_closing; return; } MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); c->noreply = true; /* binprot supports 16bit keys, but internals are still 8bit */ if (keylen > KEY_MAX_LENGTH) { handle_binary_protocol_error(c); return; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_SETQ: c->cmd = PROTOCOL_BINARY_CMD_SET; break; case PROTOCOL_BINARY_CMD_ADDQ: c->cmd = PROTOCOL_BINARY_CMD_ADD; break; case PROTOCOL_BINARY_CMD_REPLACEQ: c->cmd = PROTOCOL_BINARY_CMD_REPLACE; break; case PROTOCOL_BINARY_CMD_DELETEQ: c->cmd = PROTOCOL_BINARY_CMD_DELETE; break; case PROTOCOL_BINARY_CMD_INCREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_INCREMENT; break; case PROTOCOL_BINARY_CMD_DECREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_DECREMENT; break; case PROTOCOL_BINARY_CMD_QUITQ: c->cmd = PROTOCOL_BINARY_CMD_QUIT; break; case PROTOCOL_BINARY_CMD_FLUSHQ: c->cmd = PROTOCOL_BINARY_CMD_FLUSH; break; case PROTOCOL_BINARY_CMD_APPENDQ: c->cmd = PROTOCOL_BINARY_CMD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPENDQ: c->cmd = PROTOCOL_BINARY_CMD_PREPEND; break; case PROTOCOL_BINARY_CMD_GETQ: c->cmd = PROTOCOL_BINARY_CMD_GET; break; case PROTOCOL_BINARY_CMD_GETKQ: c->cmd = PROTOCOL_BINARY_CMD_GETK; break; case PROTOCOL_BINARY_CMD_GATQ: c->cmd = PROTOCOL_BINARY_CMD_GAT; break; case PROTOCOL_BINARY_CMD_GATKQ: c->cmd = PROTOCOL_BINARY_CMD_GATK; break; default: c->noreply = false; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_VERSION: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, VERSION, 0, 0, strlen(VERSION)); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_FLUSH: if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) { bin_read_key(c, bin_read_flush_exptime, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_NOOP: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_REPLACE: if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) { bin_read_key(c, bin_reading_set_header, 8); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETK: if (extlen == 0 && bodylen == keylen && keylen > 0) { bin_read_key(c, bin_reading_get_key, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_DELETE: if (keylen > 0 && extlen == 0 && bodylen == keylen) { bin_read_key(c, bin_reading_del_header, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_INCREMENT: case PROTOCOL_BINARY_CMD_DECREMENT: if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) { bin_read_key(c, bin_reading_incr_header, 20); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_APPEND: case PROTOCOL_BINARY_CMD_PREPEND: if (keylen > 0 && extlen == 0) { bin_read_key(c, bin_reading_set_header, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_STAT: if (extlen == 0) { bin_read_key(c, bin_reading_stat, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_QUIT: if (keylen == 0 && extlen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); c->write_and_go = conn_closing; if (c->noreply) { conn_set_state(c, conn_closing); } } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: if (extlen == 0 && keylen == 0 && bodylen == 0) { bin_list_sasl_mechs(c); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_AUTH: case PROTOCOL_BINARY_CMD_SASL_STEP: if (extlen == 0 && keylen != 0) { bin_read_key(c, bin_reading_sasl_auth, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_TOUCH: case PROTOCOL_BINARY_CMD_GAT: case PROTOCOL_BINARY_CMD_GATQ: case PROTOCOL_BINARY_CMD_GATK: case PROTOCOL_BINARY_CMD_GATKQ: if (extlen == 4 && keylen != 0) { bin_read_key(c, bin_reading_touch_key, 4); } else { protocol_error = 1; } break; default: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, bodylen); } if (protocol_error) handle_binary_protocol_error(c); } static void process_bin_update(conn *c) { char *key; int nkey; int vlen; item *it; protocol_binary_request_set* req = binary_get_request(c); assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; /* fix byteorder in the request */ req->message.body.flags = ntohl(req->message.body.flags); req->message.body.expiration = ntohl(req->message.body.expiration); vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen); if (settings.verbose > 1) { int ii; if (c->cmd == PROTOCOL_BINARY_CMD_ADD) { fprintf(stderr, "<%d ADD ", c->sfd); } else if (c->cmd == PROTOCOL_BINARY_CMD_SET) { fprintf(stderr, "<%d SET ", c->sfd); } else { fprintf(stderr, "<%d REPLACE ", c->sfd); } for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, " Value len is %d", vlen); fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, req->message.body.flags, realtime(req->message.body.expiration), vlen+2); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* This error generating method eats the swallow value. Add here. */ c->sbytes = vlen; status = NO_MEMORY; } /* FIXME: losing c->cmd since it's translated below. refactor? */ LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, 0, key, nkey, req->message.body.expiration, ITEM_clsid(it), c->sfd); /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (c->cmd == PROTOCOL_BINARY_CMD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_ADD: c->cmd = NREAD_ADD; break; case PROTOCOL_BINARY_CMD_SET: c->cmd = NREAD_SET; break; case PROTOCOL_BINARY_CMD_REPLACE: c->cmd = NREAD_REPLACE; break; default: assert(0); } if (ITEM_get_cas(it) != 0) { c->cmd = NREAD_CAS; } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_append_prepend(conn *c) { char *key; int nkey; int vlen; item *it; assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; vlen = c->binary_header.request.bodylen - nkey; if (settings.verbose > 1) { fprintf(stderr, "Value len is %d\n", vlen); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, 0, 0, vlen+2); if (it == 0) { if (! item_size_ok(nkey, 0, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* OOM calls eat the swallow value. Add here. */ c->sbytes = vlen; } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_APPEND: c->cmd = NREAD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPEND: c->cmd = NREAD_PREPEND; break; default: assert(0); } c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_flush(conn *c) { time_t exptime = 0; protocol_binary_request_flush* req = binary_get_request(c); rel_time_t new_oldest = 0; if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } if (c->binary_header.request.extlen == sizeof(req->message.body)) { exptime = ntohl(req->message.body.expiration); } if (exptime > 0) { new_oldest = realtime(exptime); } else { new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_response(c, NULL, 0, 0, 0); } static void process_bin_delete(conn *c) { item *it; uint32_t hv; protocol_binary_request_delete* req = binary_get_request(c); char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; assert(c != NULL); if (settings.verbose > 1) { int ii; fprintf(stderr, "Deleting "); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { uint64_t cas = ntohll(req->message.header.request.cas); if (cas == 0 || cas == ITEM_get_cas(it)) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); write_bin_response(c, NULL, 0, 0, 0); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); } do_item_remove(it); /* release our reference */ } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } item_unlock(hv); } static void complete_nread_binary(conn *c) { assert(c != NULL); assert(c->cmd >= 0); switch(c->substate) { case bin_reading_set_header: if (c->cmd == PROTOCOL_BINARY_CMD_APPEND || c->cmd == PROTOCOL_BINARY_CMD_PREPEND) { process_bin_append_prepend(c); } else { process_bin_update(c); } break; case bin_read_set_value: complete_update_bin(c); break; case bin_reading_get_key: case bin_reading_touch_key: process_bin_get_or_touch(c); break; case bin_reading_stat: process_bin_stat(c); break; case bin_reading_del_header: process_bin_delete(c); break; case bin_reading_incr_header: complete_incr_bin(c); break; case bin_read_flush_exptime: process_bin_flush(c); break; case bin_reading_sasl_auth: process_bin_sasl_auth(c); break; case bin_reading_sasl_auth_data: process_bin_complete_sasl_auth(c); break; default: fprintf(stderr, "Not handling substate %d\n", c->substate); assert(0); } } static void reset_cmd_handler(conn *c) { c->cmd = -1; c->substate = bin_no_state; if(c->item != NULL) { item_remove(c->item); c->item = NULL; } conn_shrink(c); if (c->rbytes > 0) { conn_set_state(c, conn_parse_cmd); } else { conn_set_state(c, conn_waiting); } } static void complete_nread(conn *c) { assert(c != NULL); assert(c->protocol == ascii_prot || c->protocol == binary_prot); if (c->protocol == ascii_prot) { complete_nread_ascii(c); } else if (c->protocol == binary_prot) { complete_nread_binary(c); } } /* Destination must always be chunked */ /* This should be part of item.c */ static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) { item_chunk *dch = (item_chunk *) ITEM_schunk(d_it); /* Advance dch until we find free space */ while (dch->size == dch->used) { if (dch->next) { dch = dch->next; } else { break; } } if (s_it->it_flags & ITEM_CHUNKED) { int remain = len; item_chunk *sch = (item_chunk *) ITEM_schunk(s_it); int copied = 0; /* Fills dch's to capacity, not straight copy sch in case data is * being added or removed (ie append/prepend) */ while (sch && dch && remain) { assert(dch->used <= dch->size); int todo = (dch->size - dch->used < sch->used - copied) ? dch->size - dch->used : sch->used - copied; if (remain < todo) todo = remain; memcpy(dch->data + dch->used, sch->data + copied, todo); dch->used += todo; copied += todo; remain -= todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, remain); if (tch) { dch = tch; } else { return -1; } } assert(copied <= sch->used); if (copied == sch->used) { copied = 0; sch = sch->next; } } /* assert that the destination had enough space for the source */ assert(remain == 0); } else { int done = 0; /* Fill dch's via a non-chunked item. */ while (len > done && dch) { int todo = (dch->size - dch->used < len - done) ? dch->size - dch->used : len - done; //assert(dch->size - dch->used != 0); memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo); done += todo; dch->used += todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, len - done); if (tch) { dch = tch; } else { return -1; } } } assert(len == done); } return 0; } static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) { if (comm == NREAD_APPEND) { if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes); memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes); } } else { /* NREAD_PREPEND */ if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes); memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes); } } return 0; } /* * Stores an item in the cache according to the semantics of one of the set * commands. In threaded mode, this is protected by the cache lock. * * Returns the state of storage. */ enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) { char *key = ITEM_key(it); item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE); enum store_item_type stored = NOT_STORED; item *new_it = NULL; uint32_t flags; if (old_it != NULL && comm == NREAD_ADD) { /* add only adds a nonexistent item, but promote to head of LRU */ do_item_update(old_it); } else if (!old_it && (comm == NREAD_REPLACE || comm == NREAD_APPEND || comm == NREAD_PREPEND)) { /* replace only replaces an existing value; don't store */ } else if (comm == NREAD_CAS) { /* validate cas operation */ if(old_it == NULL) { // LRU expired stored = NOT_FOUND; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.cas_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) { // cas validates // it and old_it may belong to different classes. // I'm updating the stats for the one that's getting pushed out pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); stored = STORED; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++; pthread_mutex_unlock(&c->thread->stats.mutex); if(settings.verbose > 1) { fprintf(stderr, "CAS: failure: expected %llu, got %llu\n", (unsigned long long)ITEM_get_cas(old_it), (unsigned long long)ITEM_get_cas(it)); } stored = EXISTS; } } else { int failed_alloc = 0; /* * Append - combine new and old record into single one. Here it's * atomic and thread-safe. */ if (comm == NREAD_APPEND || comm == NREAD_PREPEND) { /* * Validate CAS */ if (ITEM_get_cas(it) != 0) { // CAS much be equal if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) { stored = EXISTS; } } #ifdef EXTSTORE if ((old_it->it_flags & ITEM_HDR) != 0) { /* block append/prepend from working with extstore-d items. * also don't replace the header with the append chunk * accidentally, so mark as a failed_alloc. */ failed_alloc = 1; } else #endif if (stored == NOT_STORED) { /* we have it and old_it here - alloc memory to hold both */ /* flags was already lost - so recover them from ITEM_suffix(it) */ FLAGS_CONV(old_it, flags); new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */); /* copy data from it and old_it to new_it */ if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) { failed_alloc = 1; stored = NOT_STORED; // failed data copy, free up. if (new_it != NULL) item_remove(new_it); } else { it = new_it; } } } if (stored == NOT_STORED && failed_alloc == 0) { if (old_it != NULL) { STORAGE_delete(c->thread->storage, old_it); item_replace(old_it, it, hv); } else { do_item_link(it, hv); } c->cas = ITEM_get_cas(it); stored = STORED; } } if (old_it != NULL) do_item_remove(old_it); /* release our reference */ if (new_it != NULL) do_item_remove(new_it); if (stored == STORED) { c->cas = ITEM_get_cas(it); } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it), c->sfd); return stored; } typedef struct token_s { char *value; size_t length; } token_t; #define COMMAND_TOKEN 0 #define SUBCOMMAND_TOKEN 1 #define KEY_TOKEN 1 #define MAX_TOKENS 8 /* * Tokenize the command string by replacing whitespace with '\0' and update * the token array tokens with pointer to start of each token and length. * Returns total number of tokens. The last valid token is the terminal * token (value points to the first unprocessed character of the string and * length zero). * * Usage example: * * while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) { * for(int ix = 0; tokens[ix].length != 0; ix++) { * ... * } * ncommand = tokens[ix].value - command; * command = tokens[ix].value; * } */ static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) { char *s, *e; size_t ntokens = 0; size_t len = strlen(command); unsigned int i = 0; assert(command != NULL && tokens != NULL && max_tokens > 1); s = e = command; for (i = 0; i < len; i++) { if (*e == ' ') { if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; *e = '\0'; if (ntokens == max_tokens - 1) { e++; s = e; /* so we don't add an extra token */ break; } } s = e + 1; } e++; } if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; } /* * If we scanned the whole string, the terminal value pointer is null, * otherwise it is the first unprocessed character. */ tokens[ntokens].value = *e == '\0' ? NULL : e; tokens[ntokens].length = 0; ntokens++; return ntokens; } /* set up a connection to write a buffer then free it, used for stats */ static void write_and_free(conn *c, char *buf, int bytes) { if (buf) { c->write_and_free = buf; c->wcurr = buf; c->wbytes = bytes; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; } else { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } } static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens) { int noreply_index = ntokens - 2; /* NOTE: this function is not the first place where we are going to send the reply. We could send it instead from process_command() if the request line has wrong number of tokens. However parsing malformed line for "noreply" option is not reliable anyway, so it can't be helped. */ if (tokens[noreply_index].value && strcmp(tokens[noreply_index].value, "noreply") == 0) { c->noreply = true; } return c->noreply; } void append_stat(const char *name, ADD_STAT add_stats, conn *c, const char *fmt, ...) { char val_str[STAT_VAL_LEN]; int vlen; va_list ap; assert(name); assert(add_stats); assert(c); assert(fmt); va_start(ap, fmt); vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap); va_end(ap); add_stats(name, strlen(name), val_str, vlen, c); } inline static void process_stats_detail(conn *c, const char *command) { assert(c != NULL); if (strcmp(command, "on") == 0) { settings.detail_enabled = 1; out_string(c, "OK"); } else if (strcmp(command, "off") == 0) { settings.detail_enabled = 0; out_string(c, "OK"); } else if (strcmp(command, "dump") == 0) { int len; char *stats = stats_prefix_dump(&len); write_and_free(c, stats, len); } else { out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump"); } } /* return server specific stats only */ static void server_stats(ADD_STAT add_stats, conn *c) { pid_t pid = getpid(); rel_time_t now = current_time; struct thread_stats thread_stats; threadlocal_stats_aggregate(&thread_stats); struct slab_stats slab_stats; slab_stats_aggregate(&thread_stats, &slab_stats); #ifdef EXTSTORE struct extstore_stats st; #endif #ifndef WIN32 struct rusage usage; getrusage(RUSAGE_SELF, &usage); #endif /* !WIN32 */ STATS_LOCK(); APPEND_STAT("pid", "%lu", (long)pid); APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL); APPEND_STAT("time", "%ld", now + (long)process_started); APPEND_STAT("version", "%s", VERSION); APPEND_STAT("libevent", "%s", event_get_version()); APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *))); #ifndef WIN32 append_stat("rusage_user", add_stats, c, "%ld.%06ld", (long)usage.ru_utime.tv_sec, (long)usage.ru_utime.tv_usec); append_stat("rusage_system", add_stats, c, "%ld.%06ld", (long)usage.ru_stime.tv_sec, (long)usage.ru_stime.tv_usec); #endif /* !WIN32 */ APPEND_STAT("max_connections", "%d", settings.maxconns); APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1); APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns); if (settings.maxconns_fast) { APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns); } APPEND_STAT("connection_structures", "%u", stats_state.conn_structs); APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds); APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds); APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds); APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds); APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds); APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits); APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses); APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired); APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed); #ifdef EXTSTORE if (c->thread->storage) { APPEND_STAT("get_extstore", "%llu", (unsigned long long)thread_stats.get_extstore); APPEND_STAT("get_aborted_extstore", "%llu", (unsigned long long)thread_stats.get_aborted_extstore); APPEND_STAT("get_oom_extstore", "%llu", (unsigned long long)thread_stats.get_oom_extstore); APPEND_STAT("recache_from_extstore", "%llu", (unsigned long long)thread_stats.recache_from_extstore); APPEND_STAT("miss_from_extstore", "%llu", (unsigned long long)thread_stats.miss_from_extstore); APPEND_STAT("badcrc_from_extstore", "%llu", (unsigned long long)thread_stats.badcrc_from_extstore); } #endif APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses); APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits); APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses); APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits); APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses); APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits); APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses); APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits); APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval); APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits); APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses); APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds); APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors); if (settings.idle_timeout) { APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks); } APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read); APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written); APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns); APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num); APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us); APPEND_STAT("threads", "%d", settings.num_threads); APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields); APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level); APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes); APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding); if (settings.slab_reassign) { APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues); APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues); APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem); APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim); APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items); APPEND_STAT("slab_reassign_busy_deletes", "%llu", stats.slab_reassign_busy_deletes); APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running); APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved); } if (settings.lru_crawler) { APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running); APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts); } if (settings.lru_maintainer_thread) { APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles); } APPEND_STAT("malloc_fails", "%llu", (unsigned long long)stats.malloc_fails); APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped); APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written); APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped); APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent); STATS_UNLOCK(); #ifdef EXTSTORE if (c->thread->storage) { STATS_LOCK(); APPEND_STAT("extstore_compact_lost", "%llu", (unsigned long long)stats.extstore_compact_lost); APPEND_STAT("extstore_compact_rescues", "%llu", (unsigned long long)stats.extstore_compact_rescues); APPEND_STAT("extstore_compact_skipped", "%llu", (unsigned long long)stats.extstore_compact_skipped); STATS_UNLOCK(); extstore_get_stats(c->thread->storage, &st); APPEND_STAT("extstore_page_allocs", "%llu", (unsigned long long)st.page_allocs); APPEND_STAT("extstore_page_evictions", "%llu", (unsigned long long)st.page_evictions); APPEND_STAT("extstore_page_reclaims", "%llu", (unsigned long long)st.page_reclaims); APPEND_STAT("extstore_pages_free", "%llu", (unsigned long long)st.pages_free); APPEND_STAT("extstore_pages_used", "%llu", (unsigned long long)st.pages_used); APPEND_STAT("extstore_objects_evicted", "%llu", (unsigned long long)st.objects_evicted); APPEND_STAT("extstore_objects_read", "%llu", (unsigned long long)st.objects_read); APPEND_STAT("extstore_objects_written", "%llu", (unsigned long long)st.objects_written); APPEND_STAT("extstore_objects_used", "%llu", (unsigned long long)st.objects_used); APPEND_STAT("extstore_bytes_evicted", "%llu", (unsigned long long)st.bytes_evicted); APPEND_STAT("extstore_bytes_written", "%llu", (unsigned long long)st.bytes_written); APPEND_STAT("extstore_bytes_read", "%llu", (unsigned long long)st.bytes_read); APPEND_STAT("extstore_bytes_used", "%llu", (unsigned long long)st.bytes_used); APPEND_STAT("extstore_bytes_fragmented", "%llu", (unsigned long long)st.bytes_fragmented); APPEND_STAT("extstore_limit_maxbytes", "%llu", (unsigned long long)(st.page_count * st.page_size)); APPEND_STAT("extstore_io_queue", "%llu", (unsigned long long)(st.io_queue)); } #endif #ifdef TLS if (settings.ssl_enabled) { SSL_LOCK(); APPEND_STAT("time_since_server_cert_refresh", "%u", now - settings.ssl_last_cert_refresh_time); SSL_UNLOCK(); } #endif } static void process_stat_settings(ADD_STAT add_stats, void *c) { assert(add_stats); APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("maxconns", "%d", settings.maxconns); APPEND_STAT("tcpport", "%d", settings.port); APPEND_STAT("udpport", "%d", settings.udpport); APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL"); APPEND_STAT("verbosity", "%d", settings.verbose); APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live); APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off"); APPEND_STAT("domain_socket", "%s", settings.socketpath ? settings.socketpath : "NULL"); APPEND_STAT("umask", "%o", settings.access); APPEND_STAT("growth_factor", "%.2f", settings.factor); APPEND_STAT("chunk_size", "%d", settings.chunk_size); APPEND_STAT("num_threads", "%d", settings.num_threads); APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp); APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter); APPEND_STAT("detail_enabled", "%s", settings.detail_enabled ? "yes" : "no"); APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event); APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no"); APPEND_STAT("tcp_backlog", "%d", settings.backlog); APPEND_STAT("binding_protocol", "%s", prot_text(settings.binding_protocol)); APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no"); APPEND_STAT("auth_enabled_ascii", "%s", settings.auth_file ? settings.auth_file : "no"); APPEND_STAT("item_size_max", "%d", settings.item_size_max); APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no"); APPEND_STAT("hashpower_init", "%d", settings.hashpower_init); APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no"); APPEND_STAT("slab_automove", "%d", settings.slab_automove); APPEND_STAT("slab_automove_ratio", "%.2f", settings.slab_automove_ratio); APPEND_STAT("slab_automove_window", "%u", settings.slab_automove_window); APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max); APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no"); APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep); APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl); APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time); APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no"); APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no"); APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm); APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no"); APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no"); APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct); APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct); APPEND_STAT("hot_max_factor", "%.2f", settings.hot_max_factor); APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor); APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no"); APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl); APPEND_STAT("idle_timeout", "%d", settings.idle_timeout); APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size); APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size); APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no"); APPEND_STAT("inline_ascii_response", "%s", "no"); // setting is dead, cannot be yes. #ifdef HAVE_DROP_PRIVILEGES APPEND_STAT("drop_privileges", "%s", settings.drop_privileges ? "yes" : "no"); #endif #ifdef EXTSTORE APPEND_STAT("ext_item_size", "%u", settings.ext_item_size); APPEND_STAT("ext_item_age", "%u", settings.ext_item_age); APPEND_STAT("ext_low_ttl", "%u", settings.ext_low_ttl); APPEND_STAT("ext_recache_rate", "%u", settings.ext_recache_rate); APPEND_STAT("ext_wbuf_size", "%u", settings.ext_wbuf_size); APPEND_STAT("ext_compact_under", "%u", settings.ext_compact_under); APPEND_STAT("ext_drop_under", "%u", settings.ext_drop_under); APPEND_STAT("ext_max_frag", "%.2f", settings.ext_max_frag); APPEND_STAT("slab_automove_freeratio", "%.3f", settings.slab_automove_freeratio); APPEND_STAT("ext_drop_unread", "%s", settings.ext_drop_unread ? "yes" : "no"); #endif #ifdef TLS APPEND_STAT("ssl_enabled", "%s", settings.ssl_enabled ? "yes" : "no"); APPEND_STAT("ssl_chain_cert", "%s", settings.ssl_chain_cert); APPEND_STAT("ssl_key", "%s", settings.ssl_key); APPEND_STAT("ssl_verify_mode", "%d", settings.ssl_verify_mode); APPEND_STAT("ssl_keyformat", "%d", settings.ssl_keyformat); APPEND_STAT("ssl_ciphers", "%s", settings.ssl_ciphers ? settings.ssl_ciphers : "NULL"); APPEND_STAT("ssl_ca_cert", "%s", settings.ssl_ca_cert ? settings.ssl_ca_cert : "NULL"); APPEND_STAT("ssl_wbuf_size", "%u", settings.ssl_wbuf_size); #endif } static int nz_strcmp(int nzlength, const char *nz, const char *z) { int zlength=strlen(z); return (zlength == nzlength) && (strncmp(nz, z, zlength) == 0) ? 0 : -1; } static bool get_stats(const char *stat_type, int nkey, ADD_STAT add_stats, void *c) { bool ret = true; if (add_stats != NULL) { if (!stat_type) { /* prepare general statistics for the engine */ STATS_LOCK(); APPEND_STAT("bytes", "%llu", (unsigned long long)stats_state.curr_bytes); APPEND_STAT("curr_items", "%llu", (unsigned long long)stats_state.curr_items); APPEND_STAT("total_items", "%llu", (unsigned long long)stats.total_items); STATS_UNLOCK(); APPEND_STAT("slab_global_page_pool", "%u", global_page_pool_size(NULL)); item_stats_totals(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "items") == 0) { item_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "slabs") == 0) { slabs_stats(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes") == 0) { item_stats_sizes(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_enable") == 0) { item_stats_sizes_enable(add_stats, c); } else if (nz_strcmp(nkey, stat_type, "sizes_disable") == 0) { item_stats_sizes_disable(add_stats, c); } else { ret = false; } } else { ret = false; } return ret; } static inline void get_conn_text(const conn *c, const int af, char* addr, struct sockaddr *sock_addr) { char addr_text[MAXPATHLEN]; addr_text[0] = '\0'; const char *protoname = "?"; unsigned short port = 0; switch (af) { case AF_INET: (void) inet_ntop(af, &((struct sockaddr_in *)sock_addr)->sin_addr, addr_text, sizeof(addr_text) - 1); port = ntohs(((struct sockaddr_in *)sock_addr)->sin_port); protoname = IS_UDP(c->transport) ? "udp" : "tcp"; break; case AF_INET6: addr_text[0] = '['; addr_text[1] = '\0'; if (inet_ntop(af, &((struct sockaddr_in6 *)sock_addr)->sin6_addr, addr_text + 1, sizeof(addr_text) - 2)) { strcat(addr_text, "]"); } port = ntohs(((struct sockaddr_in6 *)sock_addr)->sin6_port); protoname = IS_UDP(c->transport) ? "udp6" : "tcp6"; break; case AF_UNIX: strncpy(addr_text, ((struct sockaddr_un *)sock_addr)->sun_path, sizeof(addr_text) - 1); addr_text[sizeof(addr_text)-1] = '\0'; protoname = "unix"; break; } if (strlen(addr_text) < 2) { /* Most likely this is a connected UNIX-domain client which * has no peer socket address, but there's no portable way * to tell for sure. */ sprintf(addr_text, "<AF %d>", af); } if (port) { sprintf(addr, "%s:%s:%u", protoname, addr_text, port); } else { sprintf(addr, "%s:%s", protoname, addr_text); } } static void conn_to_str(const conn *c, char *addr, char *svr_addr) { if (!c) { strcpy(addr, "<null>"); } else if (c->state == conn_closed) { strcpy(addr, "<closed>"); } else { struct sockaddr_in6 local_addr; struct sockaddr *sock_addr = (void *)&c->request_addr; /* For listen ports and idle UDP ports, show listen address */ if (c->state == conn_listening || (IS_UDP(c->transport) && c->state == conn_read)) { socklen_t local_addr_len = sizeof(local_addr); if (getsockname(c->sfd, (struct sockaddr *)&local_addr, &local_addr_len) == 0) { sock_addr = (struct sockaddr *)&local_addr; } } get_conn_text(c, sock_addr->sa_family, addr, sock_addr); if (c->state != conn_listening && !(IS_UDP(c->transport) && c->state == conn_read)) { struct sockaddr_storage svr_sock_addr; socklen_t svr_addr_len = sizeof(svr_sock_addr); getsockname(c->sfd, (struct sockaddr *)&svr_sock_addr, &svr_addr_len); get_conn_text(c, svr_sock_addr.ss_family, svr_addr, (struct sockaddr *)&svr_sock_addr); } } } static void process_stats_conns(ADD_STAT add_stats, void *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; size_t extras_len = sizeof("unix:") + sizeof("65535"); char addr[MAXPATHLEN + extras_len]; char svr_addr[MAXPATHLEN + extras_len]; int klen = 0, vlen = 0; assert(add_stats); for (i = 0; i < max_fds; i++) { if (conns[i]) { /* This is safe to do unlocked because conns are never freed; the * worst that'll happen will be a minor inconsistency in the * output -- not worth the complexity of the locking that'd be * required to prevent it. */ if (IS_UDP(conns[i]->transport)) { APPEND_NUM_STAT(i, "UDP", "%s", "UDP"); } if (conns[i]->state != conn_closed) { conn_to_str(conns[i], addr, svr_addr); APPEND_NUM_STAT(i, "addr", "%s", addr); if (conns[i]->state != conn_listening && !(IS_UDP(conns[i]->transport) && conns[i]->state == conn_read)) { APPEND_NUM_STAT(i, "listen_addr", "%s", svr_addr); } APPEND_NUM_STAT(i, "state", "%s", state_text(conns[i]->state)); APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d", current_time - conns[i]->last_cmd_time); } } } } #ifdef EXTSTORE static void process_extstore_stats(ADD_STAT add_stats, conn *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; int klen = 0, vlen = 0; struct extstore_stats st; assert(add_stats); void *storage = c->thread->storage; extstore_get_stats(storage, &st); st.page_data = calloc(st.page_count, sizeof(struct extstore_page_data)); extstore_get_page_data(storage, &st); for (i = 0; i < st.page_count; i++) { APPEND_NUM_STAT(i, "version", "%llu", (unsigned long long) st.page_data[i].version); APPEND_NUM_STAT(i, "bytes", "%llu", (unsigned long long) st.page_data[i].bytes_used); APPEND_NUM_STAT(i, "bucket", "%u", st.page_data[i].bucket); APPEND_NUM_STAT(i, "free_bucket", "%u", st.page_data[i].free_bucket); } } #endif static void process_stat(conn *c, token_t *tokens, const size_t ntokens) { const char *subcommand = tokens[SUBCOMMAND_TOKEN].value; assert(c != NULL); if (ntokens < 2) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (ntokens == 2) { server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strcmp(subcommand, "reset") == 0) { stats_reset(); out_string(c, "RESET"); return ; } else if (strcmp(subcommand, "detail") == 0) { /* NOTE: how to tackle detail with binary? */ if (ntokens < 4) process_stats_detail(c, ""); /* outputs the error message */ else process_stats_detail(c, tokens[2].value); /* Output already generated */ return ; } else if (strcmp(subcommand, "settings") == 0) { process_stat_settings(&append_stats, c); } else if (strcmp(subcommand, "cachedump") == 0) { char *buf; unsigned int bytes, id, limit = 0; if (!settings.dump_enabled) { out_string(c, "CLIENT_ERROR stats cachedump not allowed"); return; } if (ntokens < 5) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (!safe_strtoul(tokens[2].value, &id) || !safe_strtoul(tokens[3].value, &limit)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (id >= MAX_NUMBER_OF_SLAB_CLASSES) { out_string(c, "CLIENT_ERROR Illegal slab id"); return; } buf = item_cachedump(id, limit, &bytes); write_and_free(c, buf, bytes); return ; } else if (strcmp(subcommand, "conns") == 0) { process_stats_conns(&append_stats, c); #ifdef EXTSTORE } else if (strcmp(subcommand, "extstore") == 0) { process_extstore_stats(&append_stats, c); #endif } else { /* getting here means that the subcommand is either engine specific or is invalid. query the engine and see. */ if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { out_string(c, "ERROR"); } return ; } /* append terminator and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } /* client flags == 0 means use no storage for client flags */ static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas, int nbytes) { char *p = suffix; *p = ' '; p++; if (FLAGS_SIZE(it) == 0) { *p = '0'; p++; } else { p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), p); } *p = ' '; p = itoa_u32(nbytes-2, p+1); if (return_cas) { *p = ' '; p = itoa_u64(ITEM_get_cas(it), p+1); } *p = '\r'; *(p+1) = '\n'; *(p+2) = '\0'; return (p - suffix) + 2; } #define IT_REFCOUNT_LIMIT 60000 static inline item* limited_get(char *key, size_t nkey, conn *c, uint32_t exptime, bool should_touch) { item *it; if (should_touch) { it = item_touch(key, nkey, exptime, c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it && it->refcount > IT_REFCOUNT_LIMIT) { item_remove(it); it = NULL; } return it; } static inline int _ascii_get_expand_ilist(conn *c, int i) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } } return 0; } static inline char *_ascii_get_suffix_buf(conn *c, int i) { char *suffix; /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return NULL; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix"); return NULL; } *(c->suffixlist + i) = suffix; return suffix; } #ifdef EXTSTORE // FIXME: This runs in the IO thread. to get better IO performance this should // simply mark the io wrapper with the return value and decrement wrapleft, if // zero redispatching. Still a bit of work being done in the side thread but // minimized at least. static void _get_extstore_cb(void *e, obj_io *io, int ret) { // FIXME: assumes success io_wrap *wrap = (io_wrap *)io->data; conn *c = wrap->c; assert(wrap->active == true); item *read_it = (item *)io->buf; bool miss = false; // TODO: How to do counters for hit/misses? if (ret < 1) { miss = true; } else { uint32_t crc2; uint32_t crc = (uint32_t) read_it->exptime; int x; // item is chunked, crc the iov's if (io->iov != NULL) { // first iov is the header, which we don't use beyond crc crc2 = crc32c(0, (char *)io->iov[0].iov_base+STORE_OFFSET, io->iov[0].iov_len-STORE_OFFSET); // make sure it's not sent. hack :( io->iov[0].iov_len = 0; for (x = 1; x < io->iovcnt; x++) { crc2 = crc32c(crc2, (char *)io->iov[x].iov_base, io->iov[x].iov_len); } } else { crc2 = crc32c(0, (char *)read_it+STORE_OFFSET, io->len-STORE_OFFSET); } if (crc != crc2) { miss = true; wrap->badcrc = true; } } if (miss) { int i; struct iovec *v; // TODO: This should be movable to the worker thread. if (c->protocol == binary_prot) { protocol_binary_response_header *header = (protocol_binary_response_header *)c->wbuf; // this zeroes out the iovecs since binprot never stacks them. if (header->response.keylen) { write_bin_miss_response(c, ITEM_key(wrap->hdr_it), wrap->hdr_it->nkey); } else { write_bin_miss_response(c, 0, 0); } } else { for (i = 0; i < wrap->iovec_count; i++) { v = &c->iov[wrap->iovec_start + i]; v->iov_len = 0; v->iov_base = NULL; } } wrap->miss = true; } else { assert(read_it->slabs_clsid != 0); // kill \r\n for binprot if (io->iov == NULL) { c->iov[wrap->iovec_data].iov_base = ITEM_data(read_it); if (c->protocol == binary_prot) c->iov[wrap->iovec_data].iov_len -= 2; } else { // FIXME: Might need to go back and ensure chunked binprots don't // ever span two chunks for the final \r\n if (c->protocol == binary_prot) { if (io->iov[io->iovcnt-1].iov_len >= 2) { io->iov[io->iovcnt-1].iov_len -= 2; } else { io->iov[io->iovcnt-1].iov_len = 0; io->iov[io->iovcnt-2].iov_len -= 1; } } } wrap->miss = false; // iov_len is already set // TODO: Should do that here instead and cuddle in the wrap object } c->io_wrapleft--; wrap->active = false; //assert(c->io_wrapleft >= 0); // All IO's have returned, lets re-attach this connection to our original // thread. if (c->io_wrapleft == 0) { assert(c->io_queued == true); c->io_queued = false; redispatch_conn(c); } } // FIXME: This completely breaks UDP support. static inline int _get_extstore(conn *c, item *it, int iovst, int iovcnt) { #ifdef NEED_ALIGN item_hdr hdr; memcpy(&hdr, ITEM_data(it), sizeof(hdr)); #else item_hdr *hdr = (item_hdr *)ITEM_data(it); #endif size_t ntotal = ITEM_ntotal(it); unsigned int clsid = slabs_clsid(ntotal); item *new_it; bool chunked = false; if (ntotal > settings.slab_chunk_size_max) { // Pull a chunked item header. uint32_t flags; FLAGS_CONV(it, flags); new_it = item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, it->nbytes); assert(new_it == NULL || (new_it->it_flags & ITEM_CHUNKED)); chunked = true; } else { new_it = do_item_alloc_pull(ntotal, clsid); } if (new_it == NULL) return -1; assert(!c->io_queued); // FIXME: debugging. // so we can free the chunk on a miss new_it->slabs_clsid = clsid; io_wrap *io = do_cache_alloc(c->thread->io_cache); io->active = true; io->miss = false; io->badcrc = false; // io_wrap owns the reference for this object now. io->hdr_it = it; // FIXME: error handling. // The offsets we'll wipe on a miss. io->iovec_start = iovst; io->iovec_count = iovcnt; // This is probably super dangerous. keep it at 0 and fill into wrap // object? if (chunked) { unsigned int ciovcnt = 1; size_t remain = new_it->nbytes; item_chunk *chunk = (item_chunk *) ITEM_schunk(new_it); io->io.iov = &c->iov[c->iovused]; // fill the header so we can get the full data + crc back. add_iov(c, new_it, ITEM_ntotal(new_it) - new_it->nbytes); while (remain > 0) { chunk = do_item_alloc_chunk(chunk, remain); if (chunk == NULL) { item_remove(new_it); do_cache_free(c->thread->io_cache, io); return -1; } add_iov(c, chunk->data, (remain < chunk->size) ? remain : chunk->size); chunk->used = (remain < chunk->size) ? remain : chunk->size; remain -= chunk->size; ciovcnt++; } io->io.iovcnt = ciovcnt; // header object was already accounted for, remove one from total io->iovec_count += ciovcnt-1; } else { io->io.iov = NULL; io->iovec_data = c->iovused; add_iov(c, "", it->nbytes); } io->io.buf = (void *)new_it; // The offset we'll fill in on a hit. io->c = c; // We need to stack the sub-struct IO's together as well. if (c->io_wraplist) { io->io.next = &c->io_wraplist->io; } else { io->io.next = NULL; } // IO queue for this connection. io->next = c->io_wraplist; c->io_wraplist = io; assert(c->io_wrapleft >= 0); c->io_wrapleft++; // reference ourselves for the callback. io->io.data = (void *)io; // Now, fill in io->io based on what was in our header. #ifdef NEED_ALIGN io->io.page_version = hdr.page_version; io->io.page_id = hdr.page_id; io->io.offset = hdr.offset; #else io->io.page_version = hdr->page_version; io->io.page_id = hdr->page_id; io->io.offset = hdr->offset; #endif io->io.len = ntotal; io->io.mode = OBJ_IO_READ; io->io.cb = _get_extstore_cb; //fprintf(stderr, "EXTSTORE: IO stacked %u\n", io->iovec_data); // FIXME: This stat needs to move to reflect # of flash hits vs misses // for now it's a good gauge on how often we request out to flash at // least. pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); return 0; } #endif /* ntokens is overwritten here... shrug.. */ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas, bool should_touch) { char *key; size_t nkey; int i = 0; int si = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; int32_t exptime_int = 0; rel_time_t exptime = 0; bool fail_length = false; assert(c != NULL); if (should_touch) { // For get and touch commands, use first token as exptime if (!safe_strtol(tokens[1].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } key_token++; exptime = realtime(exptime_int); } do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if (nkey > KEY_MAX_LENGTH) { fail_length = true; goto stop; } it = limited_get(key, nkey, c, exptime, should_touch); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (_ascii_get_expand_ilist(c, i) != 0) { item_remove(it); goto stop; } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * "VALUE " * key * " " + flags + " " + data length + "\r\n" + data (with \r\n) */ { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); int nbytes; suffix = _ascii_get_suffix_buf(c, si); if (suffix == NULL) { item_remove(it); goto stop; } si++; nbytes = it->nbytes; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas, nbytes); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); goto stop; } #ifdef EXTSTORE if (it->it_flags & ITEM_HDR) { if (_get_extstore(c, it, c->iovused-3, 4) != 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_oom_extstore++; pthread_mutex_unlock(&c->thread->stats.mutex); item_remove(it); goto stop; } } else if ((it->it_flags & ITEM_CHUNKED) == 0) { #else if ((it->it_flags & ITEM_CHUNKED) == 0) { #endif add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); goto stop; } } if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d sending key ", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.lru_hits[it->slabs_clsid]++; c->thread->stats.get_cmds++; } pthread_mutex_unlock(&c->thread->stats.mutex); #ifdef EXTSTORE /* If ITEM_HDR, an io_wrap owns the reference. */ if ((it->it_flags & ITEM_HDR) == 0) { *(c->ilist + i) = it; i++; } #else *(c->ilist + i) = it; i++; #endif } else { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_misses++; c->thread->stats.get_cmds++; } MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); pthread_mutex_unlock(&c->thread->stats.mutex); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); stop: c->icurr = c->ilist; c->ileft = i; c->suffixcurr = c->suffixlist; c->suffixleft = si; if (settings.verbose > 1) fprintf(stderr, ">%d END\n", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { if (fail_length) { out_string(c, "CLIENT_ERROR bad command line format"); } else { out_of_memory(c, "SERVER_ERROR out of memory writing get response"); } conn_release_items(c); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } } static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) { char *key; size_t nkey; unsigned int flags; int32_t exptime_int = 0; time_t exptime; int vlen; uint64_t req_cas_id=0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags) && safe_strtol(tokens[3].value, &exptime_int) && safe_strtol(tokens[4].value, (int32_t *)&vlen))) { out_string(c, "CLIENT_ERROR bad command line format"); return; } /* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */ exptime = exptime_int; /* Negative exptimes can underflow and end up immortal. realtime() will immediately expire values that are greater than REALTIME_MAXDELTA, but less than process_started, so lets aim for that. */ if (exptime < 0) exptime = REALTIME_MAXDELTA + 1; // does cas value exist? if (handle_cas) { if (!safe_strtoull(tokens[5].value, &req_cas_id)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } if (vlen < 0 || vlen > (INT_MAX - 2)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } vlen += 2; if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, flags, realtime(exptime), vlen); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, flags, vlen)) { out_string(c, "SERVER_ERROR object too large for cache"); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR out of memory storing object"); status = NO_MEMORY; } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, comm, key, nkey, 0, 0, c->sfd); /* swallow the data line */ c->write_and_go = conn_swallow; c->sbytes = vlen; /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (comm == NREAD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); STORAGE_delete(c->thread->storage, it); item_remove(it); } } return; } ITEM_set_cas(it, req_cas_id); c->item = it; #ifdef NEED_ALIGN if (it->it_flags & ITEM_CHUNKED) { c->ritem = ITEM_schunk(it); } else { c->ritem = ITEM_data(it); } #else c->ritem = ITEM_data(it); #endif c->rlbytes = it->nbytes; c->cmd = comm; conn_set_state(c, conn_nread); } static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; int32_t exptime_int = 0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtol(tokens[2].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } it = item_touch(key, nkey, realtime(exptime_int), c); if (it) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "TOUCHED"); item_remove(it); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } } static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) { char temp[INCR_MAX_STORAGE_LEN]; uint64_t delta; char *key; size_t nkey; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtoull(tokens[2].value, &delta)) { out_string(c, "CLIENT_ERROR invalid numeric delta argument"); return; } switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) { case OK: out_string(c, temp); break; case NON_NUMERIC: out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value"); break; case EOM: out_of_memory(c, "SERVER_ERROR out of memory"); break; case DELTA_ITEM_NOT_FOUND: pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); break; case DELTA_ITEM_CAS_MISMATCH: break; /* Should never get here */ } } /* * adds a delta value to a numeric item. * * c connection requesting the operation * it item to adjust * incr true to increment value, false to decrement * delta amount to adjust value by * buf buffer for response string * * returns a response string to send back to the client. */ enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey, const bool incr, const int64_t delta, char *buf, uint64_t *cas, const uint32_t hv) { char *ptr; uint64_t value; int res; item *it; it = do_item_get(key, nkey, hv, c, DONT_UPDATE); if (!it) { return DELTA_ITEM_NOT_FOUND; } /* Can't delta zero byte values. 2-byte are the "\r\n" */ /* Also can't delta for chunked items. Too large to be a number */ #ifdef EXTSTORE if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED|ITEM_HDR)) != 0) { #else if (it->nbytes <= 2 || (it->it_flags & (ITEM_CHUNKED)) != 0) { #endif do_item_remove(it); return NON_NUMERIC; } if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) { do_item_remove(it); return DELTA_ITEM_CAS_MISMATCH; } ptr = ITEM_data(it); if (!safe_strtoull(ptr, &value)) { do_item_remove(it); return NON_NUMERIC; } if (incr) { value += delta; MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value); } else { if(delta > value) { value = 0; } else { value -= delta; } MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value); } pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++; } else { c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++; } pthread_mutex_unlock(&c->thread->stats.mutex); itoa_u64(value, buf); res = strlen(buf); /* refcount == 2 means we are the only ones holding the item, and it is * linked. We hold the item's lock in this function, so refcount cannot * increase. */ if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */ /* When changing the value without replacing the item, we need to update the CAS on the existing item. */ /* We also need to fiddle it in the sizes tracker in case the tracking * was enabled at runtime, since it relies on the CAS value to know * whether to remove an item or not. */ item_stats_sizes_remove(it); ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); item_stats_sizes_add(it); memcpy(ITEM_data(it), buf, res); memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2); do_item_update(it); } else if (it->refcount > 1) { item *new_it; uint32_t flags; FLAGS_CONV(it, flags); new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2); if (new_it == 0) { do_item_remove(it); return EOM; } memcpy(ITEM_data(new_it), buf, res); memcpy(ITEM_data(new_it) + res, "\r\n", 2); item_replace(it, new_it, hv); // Overwrite the older item's CAS with our new CAS since we're // returning the CAS of the old item below. ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0); do_item_remove(new_it); /* release our reference */ } else { /* Should never get here. This means we somehow fetched an unlinked * item. TODO: Add a counter? */ if (settings.verbose) { fprintf(stderr, "Tried to do incr/decr on invalid item\n"); } if (it->refcount == 1) do_item_remove(it); return DELTA_ITEM_NOT_FOUND; } if (cas) { *cas = ITEM_get_cas(it); /* swap the incoming CAS value */ } do_item_remove(it); /* release our reference */ return OK; } static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; item *it; uint32_t hv; assert(c != NULL); if (ntokens > 3) { bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0; bool sets_noreply = set_noreply_maybe(c, tokens, ntokens); bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply)) || (ntokens == 5 && hold_is_zero && sets_noreply); if (!valid) { out_string(c, "CLIENT_ERROR bad command line format. " "Usage: delete <key> [noreply]"); return; } } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get_locked(key, nkey, c, DONT_UPDATE, &hv); if (it) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); do_item_unlink(it, hv); STORAGE_delete(c->thread->storage, it); do_item_remove(it); /* release our reference */ out_string(c, "DELETED"); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } item_unlock(hv); } static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); level = strtoul(tokens[1].value, NULL, 10); settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level; out_string(c, "OK"); return; } #ifdef MEMCACHED_DEBUG static void process_misbehave_command(conn *c) { int allowed = 0; // try opening new TCP socket int i = socket(AF_INET, SOCK_STREAM, 0); if (i != -1) { allowed++; close(i); } // try executing new commands i = system("sleep 0"); if (i != -1) { allowed++; } if (allowed) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; double ratio; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[2].value, "ratio") == 0) { if (ntokens < 5 || !safe_strtod(tokens[3].value, &ratio)) { out_string(c, "ERROR"); return; } settings.slab_automove_ratio = ratio; } else { level = strtoul(tokens[2].value, NULL, 10); if (level == 0) { settings.slab_automove = 0; } else if (level == 1 || level == 2) { settings.slab_automove = level; } else { out_string(c, "ERROR"); return; } } out_string(c, "OK"); return; } /* TODO: decide on syntax for sampling? */ static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) { uint16_t f = 0; int x; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (ntokens > 2) { for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) { if ((strcmp(tokens[x].value, "rawcmds") == 0)) { f |= LOG_RAWCMDS; } else if ((strcmp(tokens[x].value, "evictions") == 0)) { f |= LOG_EVICTIONS; } else if ((strcmp(tokens[x].value, "fetchers") == 0)) { f |= LOG_FETCHERS; } else if ((strcmp(tokens[x].value, "mutations") == 0)) { f |= LOG_MUTATIONS; } else if ((strcmp(tokens[x].value, "sysevents") == 0)) { f |= LOG_SYSEVENTS; } else { out_string(c, "ERROR"); return; } } } else { f |= LOG_FETCHERS; } switch(logger_add_watcher(c, c->sfd, f)) { case LOGGER_ADD_WATCHER_TOO_MANY: out_string(c, "WATCHER_TOO_MANY log watcher limit reached"); break; case LOGGER_ADD_WATCHER_FAILED: out_string(c, "WATCHER_FAILED failed to add log watcher"); break; case LOGGER_ADD_WATCHER_OK: conn_set_state(c, conn_watch); event_del(&c->event); break; } } static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t memlimit; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (!safe_strtoul(tokens[1].value, &memlimit)) { out_string(c, "ERROR"); } else { if (memlimit < 8) { out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m"); } else { if (memlimit > 1000000000) { out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes"); } else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) { if (settings.verbose > 0) { fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit); } out_string(c, "OK"); } else { out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust"); } } } } static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t pct_hot; uint32_t pct_warm; double hot_factor; int32_t ttl; double factor; set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) { if (!safe_strtoul(tokens[2].value, &pct_hot) || !safe_strtoul(tokens[3].value, &pct_warm) || !safe_strtod(tokens[4].value, &hot_factor) || !safe_strtod(tokens[5].value, &factor)) { out_string(c, "ERROR"); } else { if (pct_hot + pct_warm > 80) { out_string(c, "ERROR hot and warm pcts must not exceed 80"); } else if (factor <= 0 || hot_factor <= 0) { out_string(c, "ERROR hot/warm age factors must be greater than 0"); } else { settings.hot_lru_pct = pct_hot; settings.warm_lru_pct = pct_warm; settings.hot_max_factor = hot_factor; settings.warm_max_factor = factor; out_string(c, "OK"); } } } else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (strcmp(tokens[2].value, "flat") == 0) { settings.lru_segmented = false; out_string(c, "OK"); } else if (strcmp(tokens[2].value, "segmented") == 0) { settings.lru_segmented = true; out_string(c, "OK"); } else { out_string(c, "ERROR"); } } else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 4 && settings.lru_maintainer_thread) { if (!safe_strtol(tokens[2].value, &ttl)) { out_string(c, "ERROR"); } else { if (ttl < 0) { settings.temp_lru = false; } else { settings.temp_lru = true; settings.temporary_ttl = ttl; } out_string(c, "OK"); } } else { out_string(c, "ERROR"); } } #ifdef EXTSTORE static void process_extstore_command(conn *c, token_t *tokens, const size_t ntokens) { set_noreply_maybe(c, tokens, ntokens); bool ok = true; if (ntokens < 4) { ok = false; } else if (strcmp(tokens[1].value, "free_memchunks") == 0 && ntokens > 4) { /* per-slab-class free chunk setting. */ unsigned int clsid = 0; unsigned int limit = 0; if (!safe_strtoul(tokens[2].value, &clsid) || !safe_strtoul(tokens[3].value, &limit)) { ok = false; } else { if (clsid < MAX_NUMBER_OF_SLAB_CLASSES) { settings.ext_free_memchunks[clsid] = limit; } else { ok = false; } } } else if (strcmp(tokens[1].value, "item_size") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_size)) ok = false; } else if (strcmp(tokens[1].value, "item_age") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_item_age)) ok = false; } else if (strcmp(tokens[1].value, "low_ttl") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_low_ttl)) ok = false; } else if (strcmp(tokens[1].value, "recache_rate") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_recache_rate)) ok = false; } else if (strcmp(tokens[1].value, "compact_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_compact_under)) ok = false; } else if (strcmp(tokens[1].value, "drop_under") == 0) { if (!safe_strtoul(tokens[2].value, &settings.ext_drop_under)) ok = false; } else if (strcmp(tokens[1].value, "max_frag") == 0) { if (!safe_strtod(tokens[2].value, &settings.ext_max_frag)) ok = false; } else if (strcmp(tokens[1].value, "drop_unread") == 0) { unsigned int v; if (!safe_strtoul(tokens[2].value, &v)) { ok = false; } else { settings.ext_drop_unread = v == 0 ? false : true; } } else { ok = false; } if (!ok) { out_string(c, "ERROR"); } else { out_string(c, "OK"); } } #endif static void process_command(conn *c, char *command) { token_t tokens[MAX_TOKENS]; size_t ntokens; int comm; assert(c != NULL); MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); if (settings.verbose > 1) fprintf(stderr, "<%d %s\n", c->sfd, command); /* * for commands set/add/replace, we build an item and read the data * directly into it, then continue in nread_complete(). */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR out of memory preparing response"); return; } ntokens = tokenize_command(command, tokens, MAX_TOKENS); if (ntokens >= 3 && ((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) || (strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) { process_get_command(c, tokens, ntokens, false, false); } else if ((ntokens == 6 || ntokens == 7) && ((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) || (strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) || (strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) || (strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) || (strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) { process_update_command(c, tokens, ntokens, comm, false); } else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) { process_update_command(c, tokens, ntokens, comm, true); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 1); } else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) { process_get_command(c, tokens, ntokens, true, false); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 0); } else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) { process_delete_command(c, tokens, ntokens); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) { process_touch_command(c, tokens, ntokens); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gat") == 0)) { process_get_command(c, tokens, ntokens, false, true); } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "gats") == 0)) { process_get_command(c, tokens, ntokens, true, true); } else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) { process_stat(c, tokens, ntokens); } else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) { time_t exptime = 0; rel_time_t new_oldest = 0; set_noreply_maybe(c, tokens, ntokens); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats out_string(c, "CLIENT_ERROR flush_all not allowed"); return; } if (ntokens != (c->noreply ? 3 : 2)) { exptime = strtol(tokens[1].value, NULL, 10); if(errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } /* If exptime is zero realtime() would return zero too, and realtime(exptime) - 1 would overflow to the max unsigned value. So we process exptime == 0 the same way we do when no delay is given at all. */ if (exptime > 0) { new_oldest = realtime(exptime); } else { /* exptime == 0 */ new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } out_string(c, "OK"); return; } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) { out_string(c, "VERSION " VERSION); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) { conn_set_state(c, conn_closing); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) { if (settings.shutdown_command) { conn_set_state(c, conn_closing); raise(SIGINT); } else { out_string(c, "ERROR: shutdown not enabled"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) { if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) { int src, dst, rv; if (settings.slab_reassign == false) { out_string(c, "CLIENT_ERROR slab reassignment disabled"); return; } src = strtol(tokens[2].value, NULL, 10); dst = strtol(tokens[3].value, NULL, 10); if (errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } rv = slabs_reassign(src, dst); switch (rv) { case REASSIGN_OK: out_string(c, "OK"); break; case REASSIGN_RUNNING: out_string(c, "BUSY currently processing reassign request"); break; case REASSIGN_BADCLASS: out_string(c, "BADCLASS invalid src or dst class id"); break; case REASSIGN_NOSPARE: out_string(c, "NOSPARE source class has no spare pages"); break; case REASSIGN_SRC_DST_SAME: out_string(c, "SAME src and dst class are identical"); break; } return; } else if (ntokens >= 4 && (strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) { process_slabs_automove_command(c, tokens, ntokens); } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) { if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) { int rv; if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0, settings.lru_crawler_tocrawl); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) { if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } if (!settings.dump_enabled) { out_string(c, "ERROR metadump not allowed"); return; } int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP, c, c->sfd, LRU_CRAWLER_CAP_REMAINING); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); // TODO: Don't reuse conn_watch here. conn_set_state(c, conn_watch); event_del(&c->event); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) { uint32_t tocrawl; if (!safe_strtoul(tokens[2].value, &tocrawl)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } settings.lru_crawler_tocrawl = tocrawl; out_string(c, "OK"); return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) { uint32_t tosleep; if (!safe_strtoul(tokens[2].value, &tosleep)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (tosleep > 1000000) { out_string(c, "CLIENT_ERROR sleep must be one second or less"); return; } settings.lru_crawler_sleep = tosleep; out_string(c, "OK"); return; } else if (ntokens == 3) { if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) { if (start_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to start lru crawler thread"); } } else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) { if (stop_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to stop lru crawler thread"); } } else { out_string(c, "ERROR"); } return; } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) { process_watch_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) { process_memlimit_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) { process_verbosity_command(c, tokens, ntokens); } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) { process_lru_command(c, tokens, ntokens); #ifdef MEMCACHED_DEBUG // commands which exist only for testing the memcached's security protection } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "misbehave") == 0)) { process_misbehave_command(c); #endif #ifdef EXTSTORE } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "extstore") == 0) { process_extstore_command(c, tokens, ntokens); #endif #ifdef TLS } else if (ntokens == 2 && strcmp(tokens[COMMAND_TOKEN].value, "refresh_certs") == 0) { set_noreply_maybe(c, tokens, ntokens); char *errmsg = NULL; if (refresh_certs(&errmsg)) { out_string(c, "OK"); } else { write_and_free(c, errmsg, strlen(errmsg)); } return; #endif } else { if (ntokens >= 2 && strncmp(tokens[ntokens - 2].value, "HTTP/", 5) == 0) { conn_set_state(c, conn_closing); } else { out_string(c, "ERROR"); } } return; } static int try_read_command_negotiate(conn *c) { assert(c->protocol == negotiating_prot); assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; c->try_read_command = try_read_command_binary; } else { // authentication doesn't work with negotiated protocol. c->protocol = ascii_prot; c->try_read_command = try_read_command_ascii; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } return c->try_read_command(c); } static int try_read_command_udp(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; return try_read_command_binary(c); } else { c->protocol = ascii_prot; return try_read_command_ascii(c); } } static int try_read_command_binary(conn *c) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR Out of memory allocating headers"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; c->last_cmd_time = current_time; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } return 1; } static int try_read_command_asciiauth(conn *c) { token_t tokens[MAX_TOKENS]; size_t ntokens; char *cont = NULL; // TODO: move to another function. if (!c->sasl_started) { char *el; uint32_t size = 0; // impossible for the auth command to be this short. if (c->rbytes < 2) return 0; el = memchr(c->rcurr, '\n', c->rbytes); // If no newline after 1k, getting junk data, close out. if (!el) { if (c->rbytes > 1024) { conn_set_state(c, conn_closing); return 1; } return 0; } // Looking for: "set foo 0 0 N\r\nuser pass\r\n" // key, flags, and ttl are ignored. N is used to see if we have the rest. // so tokenize doesn't walk past into the value. // it's fine to leave the \r in, as strtoul will stop at it. *el = '\0'; ntokens = tokenize_command(c->rcurr, tokens, MAX_TOKENS); // ensure the buffer is consumed. c->rbytes -= (el - c->rcurr) + 1; c->rcurr += (el - c->rcurr) + 1; // final token is a NULL ender, so we have one more than expected. if (ntokens < 6 || strcmp(tokens[0].value, "set") != 0 || !safe_strtoul(tokens[4].value, &size)) { out_string(c, "CLIENT_ERROR unauthenticated"); return 1; } // we don't actually care about the key at all; it can be anything. // we do care about the size of the remaining read. c->rlbytes = size + 2; c->sasl_started = true; // reuse from binprot sasl, but not sasl :) } if (c->rbytes < c->rlbytes) { // need more bytes. return 0; } cont = c->rcurr; // advance buffer. no matter what we're stopping. c->rbytes -= c->rlbytes; c->rcurr += c->rlbytes; c->sasl_started = false; // must end with \r\n // NB: I thought ASCII sets also worked with just \n, but according to // complete_nread_ascii only \r\n is valid. if (strncmp(cont + c->rlbytes - 2, "\r\n", 2) != 0) { out_string(c, "CLIENT_ERROR bad command line termination"); return 1; } // payload should be "user pass", so we can use the tokenizer. cont[c->rlbytes - 2] = '\0'; ntokens = tokenize_command(cont, tokens, MAX_TOKENS); if (ntokens < 3) { out_string(c, "CLIENT_ERROR bad authentication token format"); return 1; } if (authfile_check(tokens[0].value, tokens[1].value) == 1) { out_string(c, "STORED"); c->authenticated = true; c->try_read_command = try_read_command_ascii; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); } else { out_string(c, "CLIENT_ERROR authentication failure"); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } return 1; } static int try_read_command_ascii(conn *c) { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (ptr - c->rcurr > 100 || (strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) { conn_set_state(c, conn_closing); return 1; } } return 0; } cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); c->last_cmd_time = current_time; process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); return 1; } /* * read a UDP request. */ static enum try_read_result try_read_udp(conn *c) { int res; assert(c != NULL); c->request_addr_size = sizeof(c->request_addr); res = recvfrom(c->sfd, c->rbuf, c->rsize, 0, (struct sockaddr *)&c->request_addr, &c->request_addr_size); if (res > 8) { unsigned char *buf = (unsigned char *)c->rbuf; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* Beginning of UDP packet is the request ID; save it. */ c->request_id = buf[0] * 256 + buf[1]; /* If this is a multi-packet request, drop it. */ if (buf[4] != 0 || buf[5] != 1) { out_string(c, "SERVER_ERROR multi-packet request not supported"); return READ_NO_DATA_RECEIVED; } /* Don't care about any of the rest of the header. */ res -= 8; memmove(c->rbuf, c->rbuf + 8, res); c->rbytes = res; c->rcurr = c->rbuf; return READ_DATA_RECEIVED; } return READ_NO_DATA_RECEIVED; } /* * read from network as much as we can, handle buffer overflow and connection * close. * before reading, move the remaining incomplete fragment of a command * (if any) to the beginning of the buffer. * * To protect us from someone flooding a connection with bogus data causing * the connection to eat up all available memory, break out and start looking * at the data I've got after a number of reallocs... * * @return enum try_read_result */ static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose > 0) { fprintf(stderr, "Couldn't realloc input buffer\n"); } c->rbytes = 0; /* ignore what we read */ out_of_memory(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = c->read(c, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } static bool update_event(conn *c, const int new_flags) { assert(c != NULL); struct event_base *base = c->event.ev_base; if (c->ev_flags == new_flags) return true; if (event_del(&c->event) == -1) return false; event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = new_flags; if (event_add(&c->event, 0) == -1) return false; return true; } /* * Sets whether we are listening for new connections or not. */ void do_accept_new_conns(const bool do_accept) { conn *next; for (next = listen_conn; next; next = next->next) { if (do_accept) { update_event(next, EV_READ | EV_PERSIST); if (listen(next->sfd, settings.backlog) != 0) { perror("listen"); } } else { update_event(next, 0); if (listen(next->sfd, 0) != 0) { perror("listen"); } } } if (do_accept) { struct timeval maxconns_exited; uint64_t elapsed_us; gettimeofday(&maxconns_exited,NULL); STATS_LOCK(); elapsed_us = (maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000 + (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec); stats.time_in_listen_disabled_us += elapsed_us; stats_state.accepting_conns = true; STATS_UNLOCK(); } else { STATS_LOCK(); stats_state.accepting_conns = false; gettimeofday(&stats.maxconns_entered,NULL); stats.listen_disabled_num++; STATS_UNLOCK(); allow_new_conns = false; maxconns_handler(-42, 0, 0); } } /* * Transmit the next chunk of data from our list of msgbuf structures. * * Returns: * TRANSMIT_COMPLETE All done writing. * TRANSMIT_INCOMPLETE More data remaining to write. * TRANSMIT_SOFT_ERROR Can't write any more right now. * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing) */ static enum transmit_result transmit(conn *c) { assert(c != NULL); if (c->msgcurr < c->msgused && c->msglist[c->msgcurr].msg_iovlen == 0) { /* Finished writing the current msg; advance to the next. */ c->msgcurr++; } if (c->msgcurr < c->msgused) { ssize_t res; struct msghdr *m = &c->msglist[c->msgcurr]; res = c->sendmsg(c, m, 0); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_written += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* We've written some of the data. Remove the completed iovec entries from the list of pending writes. */ while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) { res -= m->msg_iov->iov_len; m->msg_iovlen--; m->msg_iov++; } /* Might have written just part of the last iovec entry; adjust it so the next write will do the rest. */ if (res > 0) { m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res; m->msg_iov->iov_len -= res; } return TRANSMIT_INCOMPLETE; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } return TRANSMIT_SOFT_ERROR; } /* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK, we have a real error, on which we close the connection */ if (settings.verbose > 0) perror("Failed to write, and not due to blocking"); if (IS_UDP(c->transport)) conn_set_state(c, conn_read); else conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } else { return TRANSMIT_COMPLETE; } } /* Does a looped read to fill data chunks */ /* TODO: restrict number of times this can loop. * Also, benchmark using readv's. */ static int read_into_chunked_item(conn *c) { int total = 0; int res; assert(c->rcurr != c->ritem); while (c->rlbytes > 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size == ch->used) { // FIXME: ch->next is currently always 0. remove this? if (ch->next) { c->ritem = (char *) ch->next; } else { /* Allocate next chunk. Binary protocol needs 2b for \r\n */ c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes + ((c->protocol == binary_prot) ? 2 : 0)); if (!c->ritem) { // We failed an allocation. Let caller handle cleanup. total = -2; break; } // ritem has new chunk, restart the loop. continue; //assert(c->rlbytes == 0); } } int unused = ch->size - ch->used; /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { total = 0; int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; tocopy = tocopy > unused ? unused : tocopy; if (c->ritem != c->rcurr) { memmove(ch->data + ch->used, c->rcurr, tocopy); } total += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; ch->used += tocopy; if (c->rlbytes == 0) { break; } } else { /* now try reading from the socket */ res = c->read(c, ch->data + ch->used, (unused > c->rlbytes ? c->rlbytes : unused)); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); ch->used += res; total += res; c->rlbytes -= res; } else { /* Reset total to the latest result so caller can handle it */ total = res; break; } } } /* At some point I will be able to ditch the \r\n from item storage and remove all of these kludges. The above binprot check ensures inline space for \r\n, but if we do exactly enough allocs there will be no additional chunk for \r\n. */ if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size - ch->used < 2) { c->ritem = (char *) do_item_alloc_chunk(ch, 2); if (!c->ritem) { total = -2; } } } return total; } static void drive_machine(conn *c) { bool stop = false; int sfd; socklen_t addrlen; struct sockaddr_storage addr; int nreqs = settings.reqs_per_event; int res; const char *str; #ifdef HAVE_ACCEPT4 static int use_accept4 = 1; #else static int use_accept4 = 0; #endif assert(c != NULL); while (!stop) { switch(c->state) { case conn_listening: addrlen = sizeof(addr); #ifdef HAVE_ACCEPT4 if (use_accept4) { sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK); } else { sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); } #else sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); #endif if (sfd == -1) { if (use_accept4 && errno == ENOSYS) { use_accept4 = 0; continue; } perror(use_accept4 ? "accept4()" : "accept()"); if (errno == EAGAIN || errno == EWOULDBLOCK) { /* these are transient, so don't log anything */ stop = true; } else if (errno == EMFILE) { if (settings.verbose > 0) fprintf(stderr, "Too many open connections\n"); accept_new_conns(false); stop = true; } else { perror("accept()"); stop = true; } break; } if (!use_accept4) { if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); break; } } if (settings.maxconns_fast && stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { str = "ERROR Too many open connections\r\n"; res = write(sfd, str, strlen(str)); close(sfd); STATS_LOCK(); stats.rejected_conns++; STATS_UNLOCK(); } else { void *ssl_v = NULL; #ifdef TLS SSL *ssl = NULL; if (c->ssl_enabled) { assert(IS_TCP(c->transport) && settings.ssl_enabled); if (settings.ssl_ctx == NULL) { if (settings.verbose) { fprintf(stderr, "SSL context is not initialized\n"); } close(sfd); break; } SSL_LOCK(); ssl = SSL_new(settings.ssl_ctx); SSL_UNLOCK(); if (ssl == NULL) { if (settings.verbose) { fprintf(stderr, "Failed to created the SSL object\n"); } close(sfd); break; } SSL_set_fd(ssl, sfd); int ret = SSL_accept(ssl); if (ret < 0) { int err = SSL_get_error(ssl, ret); if (err == SSL_ERROR_SYSCALL || err == SSL_ERROR_SSL) { if (settings.verbose) { fprintf(stderr, "SSL connection failed with error code : %d : %s\n", err, strerror(errno)); } close(sfd); break; } } } ssl_v = (void*) ssl; #endif dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST, DATA_BUFFER_SIZE, c->transport, ssl_v); } stop = true; break; case conn_waiting: if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } conn_set_state(c, conn_read); stop = true; break; case conn_read: res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c); switch (res) { case READ_NO_DATA_RECEIVED: conn_set_state(c, conn_waiting); break; case READ_DATA_RECEIVED: conn_set_state(c, conn_parse_cmd); break; case READ_ERROR: conn_set_state(c, conn_closing); break; case READ_MEMORY_ERROR: /* Failed to allocate more memory */ /* State already set by try_read_network */ break; } break; case conn_parse_cmd : if (c->try_read_command(c) == 0) { /* wee need more data! */ conn_set_state(c, conn_waiting); } break; case conn_new_cmd: /* Only process nreqs at a time to avoid starving other connections */ --nreqs; if (nreqs >= 0) { reset_cmd_handler(c); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.conn_yields++; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rbytes > 0) { /* We have already read in data into the input buffer, so libevent will most likely not signal read events on the socket (unless more data is available. As a hack we should just put in a request to write data, because that should be possible ;-) */ if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } } stop = true; } break; case conn_nread: if (c->rlbytes == 0) { complete_nread(c); break; } /* Check if rbytes < 0, to prevent crash */ if (c->rlbytes < 0) { if (settings.verbose) { fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes); } conn_set_state(c, conn_closing); break; } if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) { /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; if (c->ritem != c->rcurr) { memmove(c->ritem, c->rcurr, tocopy); } c->ritem += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; if (c->rlbytes == 0) { break; } } /* now try reading from the socket */ res = c->read(c, c->ritem, c->rlbytes); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rcurr == c->ritem) { c->rcurr += res; } c->ritem += res; c->rlbytes -= res; break; } } else { res = read_into_chunked_item(c); if (res > 0) break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* Memory allocation failure */ if (res == -2) { out_of_memory(c, "SERVER_ERROR Out of memory during read"); c->sbytes = c->rlbytes; c->write_and_go = conn_swallow; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) { fprintf(stderr, "Failed to read, and not due to blocking:\n" "errno: %d %s \n" "rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n", errno, strerror(errno), (long)c->rcurr, (long)c->ritem, (long)c->rbuf, (int)c->rlbytes, (int)c->rsize); } conn_set_state(c, conn_closing); break; case conn_swallow: /* we are reading sbytes and throwing them away */ if (c->sbytes <= 0) { conn_set_state(c, conn_new_cmd); break; } /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes; c->sbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; break; } /* now try reading from the socket */ res = c->read(c, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); c->sbytes -= res; break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) fprintf(stderr, "Failed to read, and not due to blocking\n"); conn_set_state(c, conn_closing); break; case conn_write: /* * We want to write out a simple response. If we haven't already, * assemble it into a msgbuf list (this will be a single-entry * list for TCP or a two-entry list for UDP). */ if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) { if (add_iov(c, c->wcurr, c->wbytes) != 0) { if (settings.verbose > 0) fprintf(stderr, "Couldn't build response\n"); conn_set_state(c, conn_closing); break; } } /* fall through... */ case conn_mwrite: #ifdef EXTSTORE /* have side IO's that must process before transmit() can run. * remove the connection from the worker thread and dispatch the * IO queue */ if (c->io_wrapleft) { assert(c->io_queued == false); assert(c->io_wraplist != NULL); // TODO: create proper state for this condition conn_set_state(c, conn_watch); event_del(&c->event); c->io_queued = true; extstore_submit(c->thread->storage, &c->io_wraplist->io); stop = true; break; } #endif if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) { if (settings.verbose > 0) fprintf(stderr, "Failed to build UDP headers\n"); conn_set_state(c, conn_closing); break; } switch (transmit(c)) { case TRANSMIT_COMPLETE: if (c->state == conn_mwrite) { conn_release_items(c); /* XXX: I don't know why this wasn't the general case */ if(c->protocol == binary_prot) { conn_set_state(c, c->write_and_go); } else { conn_set_state(c, conn_new_cmd); } } else if (c->state == conn_write) { if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } conn_set_state(c, c->write_and_go); } else { if (settings.verbose > 0) fprintf(stderr, "Unexpected state %d\n", c->state); conn_set_state(c, conn_closing); } break; case TRANSMIT_INCOMPLETE: case TRANSMIT_HARD_ERROR: break; /* Continue in state machine. */ case TRANSMIT_SOFT_ERROR: stop = true; break; } break; case conn_closing: if (IS_UDP(c->transport)) conn_cleanup(c); else conn_close(c); stop = true; break; case conn_closed: /* This only happens if dormando is an idiot. */ abort(); break; case conn_watch: /* We handed off our connection to the logger thread. */ stop = true; break; case conn_max_state: assert(false); break; } } return; } void event_handler(const int fd, const short which, void *arg) { conn *c; c = (conn *)arg; assert(c != NULL); c->which = which; /* sanity */ if (fd != c->sfd) { if (settings.verbose > 0) fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n"); conn_close(c); return; } drive_machine(c); /* wait for next event */ return; } static int new_socket(struct addrinfo *ai) { int sfd; int flags; if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } /* * Sets a socket's send buffer size to the maximum allowed by the system. */ static void maximize_sndbuf(const int sfd) { socklen_t intsize = sizeof(int); int last_good = 0; int min, max, avg; int old_size; /* Start with the default size. */ if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) { if (settings.verbose > 0) perror("getsockopt(SO_SNDBUF)"); return; } /* Binary-search for the real maximum. */ min = old_size; max = MAX_SENDBUF_SIZE; while (min <= max) { avg = ((unsigned int)(min + max)) / 2; if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) { last_good = avg; min = avg + 1; } else { max = avg - 1; } } if (settings.verbose > 1) fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good); } /** * Create a socket and bind it to a specific port number * @param interface the interface to bind to * @param port the port number to bind to * @param transport the transport protocol (TCP / UDP) * @param portnumber_file A filepointer to write the port numbers to * when they are successfully added to the list of ports we * listen on. */ static int server_socket(const char *interface, int port, enum network_transport transport, FILE *portnumber_file, bool ssl_enabled) { int sfd; struct linger ling = {0, 0}; struct addrinfo *ai; struct addrinfo *next; struct addrinfo hints = { .ai_flags = AI_PASSIVE, .ai_family = AF_UNSPEC }; char port_buf[NI_MAXSERV]; int error; int success = 0; int flags =1; hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM; if (port == -1) { port = 0; } snprintf(port_buf, sizeof(port_buf), "%d", port); error= getaddrinfo(interface, port_buf, &hints, &ai); if (error != 0) { if (error != EAI_SYSTEM) fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error)); else perror("getaddrinfo()"); return 1; } for (next= ai; next; next= next->ai_next) { conn *listen_conn_add; if ((sfd = new_socket(next)) == -1) { /* getaddrinfo can return "junk" addresses, * we make sure at least one works before erroring. */ if (errno == EMFILE) { /* ...unless we're out of fds */ perror("server_socket"); exit(EX_OSERR); } continue; } #ifdef IPV6_V6ONLY if (next->ai_family == AF_INET6) { error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags)); if (error != 0) { perror("setsockopt"); close(sfd); continue; } } #endif setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); if (IS_UDP(transport)) { maximize_sndbuf(sfd); } else { error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); } if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) { if (errno != EADDRINUSE) { perror("bind()"); close(sfd); freeaddrinfo(ai); return 1; } close(sfd); continue; } else { success++; if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); freeaddrinfo(ai); return 1; } if (portnumber_file != NULL && (next->ai_addr->sa_family == AF_INET || next->ai_addr->sa_family == AF_INET6)) { union { struct sockaddr_in in; struct sockaddr_in6 in6; } my_sockaddr; socklen_t len = sizeof(my_sockaddr); if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) { if (next->ai_addr->sa_family == AF_INET) { fprintf(portnumber_file, "%s INET: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in.sin_port)); } else { fprintf(portnumber_file, "%s INET6: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in6.sin6_port)); } } } } if (IS_UDP(transport)) { int c; for (c = 0; c < settings.num_threads_per_udp; c++) { /* Allocate one UDP file descriptor per worker thread; * this allows "stats conns" to separately list multiple * parallel UDP requests in progress. * * The dispatch code round-robins new connection requests * among threads, so this is guaranteed to assign one * FD to each thread. */ int per_thread_fd; if (c == 0) { per_thread_fd = sfd; } else { per_thread_fd = dup(sfd); if (per_thread_fd < 0) { perror("Failed to duplicate file descriptor"); exit(EXIT_FAILURE); } } dispatch_conn_new(per_thread_fd, conn_read, EV_READ | EV_PERSIST, UDP_READ_BUFFER_SIZE, transport, NULL); } } else { if (!(listen_conn_add = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } #ifdef TLS listen_conn_add->ssl_enabled = ssl_enabled; #else assert(ssl_enabled == false); #endif listen_conn_add->next = listen_conn; listen_conn = listen_conn_add; } } freeaddrinfo(ai); /* Return zero iff we detected no errors in starting up connections */ return success == 0; } static int server_sockets(int port, enum network_transport transport, FILE *portnumber_file) { bool ssl_enabled = false; #ifdef TLS const char *notls = "notls"; ssl_enabled = settings.ssl_enabled; #endif if (settings.inter == NULL) { return server_socket(settings.inter, port, transport, portnumber_file, ssl_enabled); } else { // tokenize them and bind to each one of them.. char *b; int ret = 0; char *list = strdup(settings.inter); if (list == NULL) { fprintf(stderr, "Failed to allocate memory for parsing server interface string\n"); return 1; } for (char *p = strtok_r(list, ";,", &b); p != NULL; p = strtok_r(NULL, ";,", &b)) { int the_port = port; #ifdef TLS ssl_enabled = settings.ssl_enabled; // "notls" option is valid only when memcached is run with SSL enabled. if (strncmp(p, notls, strlen(notls)) == 0) { if (!settings.ssl_enabled) { fprintf(stderr, "'notls' option is valid only when SSL is enabled\n"); return 1; } ssl_enabled = false; p += strlen(notls) + 1; } #endif char *h = NULL; if (*p == '[') { // expecting it to be an IPv6 address enclosed in [] // i.e. RFC3986 style recommended by RFC5952 char *e = strchr(p, ']'); if (e == NULL) { fprintf(stderr, "Invalid IPV6 address: \"%s\"", p); free(list); return 1; } h = ++p; // skip the opening '[' *e = '\0'; p = ++e; // skip the closing ']' } char *s = strchr(p, ':'); if (s != NULL) { // If no more semicolons - attempt to treat as port number. // Otherwise the only valid option is an unenclosed IPv6 without port, until // of course there was an RFC3986 IPv6 address previously specified - // in such a case there is no good option, will just send it to fail as port number. if (strchr(s + 1, ':') == NULL || h != NULL) { *s = '\0'; ++s; if (!safe_strtol(s, &the_port)) { fprintf(stderr, "Invalid port number: \"%s\"", s); free(list); return 1; } } } if (h != NULL) p = h; if (strcmp(p, "*") == 0) { p = NULL; } ret |= server_socket(p, the_port, transport, portnumber_file, ssl_enabled); } free(list); return ret; } } static int new_socket_unix(void) { int sfd; int flags; if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket()"); return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } static int server_socket_unix(const char *path, int access_mask) { int sfd; struct linger ling = {0, 0}; struct sockaddr_un addr; struct stat tstat; int flags =1; int old_umask; if (!path) { return 1; } if ((sfd = new_socket_unix()) == -1) { return 1; } /* * Clean up a previous socket file if we left it around */ if (lstat(path, &tstat) == 0) { if (S_ISSOCK(tstat.st_mode)) unlink(path); } setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); /* * the memset call clears nonstandard fields in some implementations * that otherwise mess things up. */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); assert(strcmp(addr.sun_path, path) == 0); old_umask = umask( ~(access_mask&0777)); if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("bind()"); close(sfd); umask(old_umask); return 1; } umask(old_umask); if (listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); return 1; } if (!(listen_conn = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, local_transport, main_base, NULL))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } return 0; } /* * We keep the current time of day in a global variable that's updated by a * timer event. This saves us a bunch of time() system calls (we really only * need to get the time once a second, whereas there can be tens of thousands * of requests a second) and allows us to use server-start-relative timestamps * rather than absolute UNIX timestamps, a space savings on systems where * sizeof(time_t) > sizeof(unsigned int). */ volatile rel_time_t current_time; static struct event clockevent; /* libevent uses a monotonic clock when available for event scheduling. Aside * from jitter, simply ticking our internal timer here is accurate enough. * Note that users who are setting explicit dates for expiration times *must* * ensure their clocks are correct before starting memcached. */ static void clock_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; static bool initialized = false; #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) static bool monotonic = false; static time_t monotonic_start; #endif if (initialized) { /* only delete the event if it's actually there. */ evtimer_del(&clockevent); } else { initialized = true; /* process_started is initialized to time() - 2. We initialize to 1 so * flush_all won't underflow during tests. */ #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { monotonic = true; monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2; } #endif } // While we're here, check for hash table expansion. // This function should be quick to avoid delaying the timer. assoc_start_expand(stats_state.curr_items); // also, if HUP'ed we need to do some maintenance. // for now that's just the authfile reload. if (settings.sig_hup) { settings.sig_hup = false; authfile_load(settings.auth_file); } evtimer_set(&clockevent, clock_handler, 0); event_base_set(main_base, &clockevent); evtimer_add(&clockevent, &t); #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) if (monotonic) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) return; current_time = (rel_time_t) (ts.tv_sec - monotonic_start); return; } #endif { struct timeval tv; gettimeofday(&tv, NULL); current_time = (rel_time_t) (tv.tv_sec - process_started); } } static void usage(void) { printf(PACKAGE " " VERSION "\n"); printf("-p, --port=<num> TCP port to listen on (default: 11211)\n" "-U, --udp-port=<num> UDP port to listen on (default: 0, off)\n" "-s, --unix-socket=<file> UNIX socket to listen on (disables network support)\n" "-A, --enable-shutdown enable ascii \"shutdown\" command\n" "-a, --unix-mask=<mask> access mask for UNIX socket, in octal (default: 0700)\n" "-l, --listen=<addr> interface to listen on (default: INADDR_ANY)\n" #ifdef TLS " if TLS/SSL is enabled, 'notls' prefix can be used to\n" " disable for specific listeners (-l notls:<ip>:<port>) \n" #endif "-d, --daemon run as a daemon\n" "-r, --enable-coredumps maximize core file limit\n" "-u, --user=<user> assume identity of <username> (only when run as root)\n" "-m, --memory-limit=<num> item memory in megabytes (default: 64 MB)\n" "-M, --disable-evictions return error on memory exhausted instead of evicting\n" "-c, --conn-limit=<num> max simultaneous connections (default: 1024)\n" "-k, --lock-memory lock down all paged memory\n" "-v, --verbose verbose (print errors/warnings while in event loop)\n" "-vv very verbose (also print client commands/responses)\n" "-vvv extremely verbose (internal state transitions)\n" "-h, --help print this help and exit\n" "-i, --license print memcached and libevent license\n" "-V, --version print version and exit\n" "-P, --pidfile=<file> save PID in <file>, only used with -d option\n" "-f, --slab-growth-factor=<num> chunk size growth factor (default: 1.25)\n" "-n, --slab-min-size=<bytes> min space used for key+value+flags (default: 48)\n"); printf("-L, --enable-largepages try to use large memory pages (if available)\n"); printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n" " This is used for per-prefix stats reporting. The default is\n" " \":\" (colon). If this option is specified, stats collection\n" " is turned on automatically; if not, then it may be turned on\n" " by sending the \"stats detail on\" command to the server.\n"); printf("-t, --threads=<num> number of threads to use (default: 4)\n"); printf("-R, --max-reqs-per-event maximum number of requests per event, limits the\n" " requests processed per connection to prevent \n" " starvation (default: 20)\n"); printf("-C, --disable-cas disable use of CAS\n"); printf("-b, --listen-backlog=<num> set the backlog queue limit (default: 1024)\n"); printf("-B, --protocol=<name> protocol - one of ascii, binary, or auto (default)\n"); printf("-I, --max-item-size=<num> adjusts max item size\n" " (default: 1mb, min: 1k, max: 1024m)\n"); #ifdef ENABLE_SASL printf("-S, --enable-sasl turn on Sasl authentication\n"); #endif printf("-F, --disable-flush-all disable flush_all command\n"); printf("-X, --disable-dumping disable stats cachedump and lru_crawler metadump\n"); printf("-Y, --auth-file=<file> (EXPERIMENTAL) enable ASCII protocol authentication. format:\n" " user:pass\\nuser2:pass2\\n\n"); #ifdef TLS printf("-Z, --enable-ssl enable TLS/SSL\n"); #endif printf("-o, --extended comma separated list of extended options\n" " most options have a 'no_' prefix to disable\n" " - maxconns_fast: immediately close new connections after limit\n" " - hashpower: an integer multiplier for how large the hash\n" " table should be. normally grows at runtime.\n" " set based on \"STAT hash_power_level\"\n" " - tail_repair_time: time in seconds for how long to wait before\n" " forcefully killing LRU tail item.\n" " disabled by default; very dangerous option.\n" " - hash_algorithm: the hash table algorithm\n" " default is murmur3 hash. options: jenkins, murmur3\n" " - lru_crawler: enable LRU Crawler background thread\n" " - lru_crawler_sleep: microseconds to sleep between items\n" " default is 100.\n" " - lru_crawler_tocrawl: max items to crawl per slab per run\n" " default is 0 (unlimited)\n" " - lru_maintainer: enable new LRU system + background thread\n" " - hot_lru_pct: pct of slab memory to reserve for hot lru.\n" " (requires lru_maintainer)\n" " - warm_lru_pct: pct of slab memory to reserve for warm lru.\n" " (requires lru_maintainer)\n" " - hot_max_factor: items idle > cold lru age * drop from hot lru.\n" " - warm_max_factor: items idle > cold lru age * this drop from warm.\n" " - temporary_ttl: TTL's below get separate LRU, can't be evicted.\n" " (requires lru_maintainer)\n" " - idle_timeout: timeout for idle connections\n" " - slab_chunk_max: (EXPERIMENTAL) maximum slab size. use extreme care.\n" " - watcher_logbuf_size: size in kilobytes of per-watcher write buffer.\n" " - worker_logbuf_size: size in kilobytes of per-worker-thread buffer\n" " read by background thread, then written to watchers.\n" " - track_sizes: enable dynamic reports for 'stats sizes' command.\n" " - no_hashexpand: disables hash table expansion (dangerous)\n" " - modern: enables options which will be default in future.\n" " currently: nothing\n" " - no_modern: uses defaults of previous major version (1.4.x)\n" #ifdef HAVE_DROP_PRIVILEGES " - drop_privileges: enable dropping extra syscall privileges\n" " - no_drop_privileges: disable drop_privileges in case it causes issues with\n" " some customisation.\n" #ifdef MEMCACHED_DEBUG " - relaxed_privileges: Running tests requires extra privileges.\n" #endif #endif #ifdef EXTSTORE " - ext_path: file to write to for external storage.\n" " ie: ext_path=/mnt/d1/extstore:1G\n" " - ext_page_size: size in megabytes of storage pages.\n" " - ext_wbuf_size: size in megabytes of page write buffers.\n" " - ext_threads: number of IO threads to run.\n" " - ext_item_size: store items larger than this (bytes)\n" " - ext_item_age: store items idle at least this long\n" " - ext_low_ttl: consider TTLs lower than this specially\n" " - ext_drop_unread: don't re-write unread values during compaction\n" " - ext_recache_rate: recache an item every N accesses\n" " - ext_compact_under: compact when fewer than this many free pages\n" " - ext_drop_under: drop COLD items when fewer than this many free pages\n" " - ext_max_frag: max page fragmentation to tolerage\n" " - slab_automove_freeratio: ratio of memory to hold free as buffer.\n" " (see doc/storage.txt for more info)\n" #endif #ifdef TLS " - ssl_chain_cert: certificate chain file in PEM format\n" " - ssl_key: private key, if not part of the -ssl_chain_cert\n" " - ssl_keyformat: private key format (PEM, DER or ENGINE) PEM default\n" " - ssl_verify_mode: peer certificate verification mode, default is 0(None).\n" " valid values are 0(None), 1(Request), 2(Require)\n" " or 3(Once)\n" " - ssl_ciphers: specify cipher list to be used\n" " - ssl_ca_cert: PEM format file of acceptable client CA's\n" " - ssl_wbuf_size: size in kilobytes of per-connection SSL output buffer\n" #endif ); return; } static void usage_license(void) { printf(PACKAGE " " VERSION "\n\n"); printf( "Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are\n" "met:\n" "\n" " * Redistributions of source code must retain the above copyright\n" "notice, this list of conditions and the following disclaimer.\n" "\n" " * Redistributions in binary form must reproduce the above\n" "copyright notice, this list of conditions and the following disclaimer\n" "in the documentation and/or other materials provided with the\n" "distribution.\n" "\n" " * Neither the name of the Danga Interactive nor the names of its\n" "contributors may be used to endorse or promote products derived from\n" "this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" "\n" "\n" "This product includes software developed by Niels Provos.\n" "\n" "[ libevent ]\n" "\n" "Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions\n" "are met:\n" "1. Redistributions of source code must retain the above copyright\n" " notice, this list of conditions and the following disclaimer.\n" "2. Redistributions in binary form must reproduce the above copyright\n" " notice, this list of conditions and the following disclaimer in the\n" " documentation and/or other materials provided with the distribution.\n" "3. All advertising materials mentioning features or use of this software\n" " must display the following acknowledgement:\n" " This product includes software developed by Niels Provos.\n" "4. The name of the author may not be used to endorse or promote products\n" " derived from this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n" "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" ); return; } static void save_pid(const char *pid_file) { FILE *fp; if (access(pid_file, F_OK) == 0) { if ((fp = fopen(pid_file, "r")) != NULL) { char buffer[1024]; if (fgets(buffer, sizeof(buffer), fp) != NULL) { unsigned int pid; if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) { fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid); } } fclose(fp); } } /* Create the pid file first with a temporary name, then * atomically move the file to the real name to avoid a race with * another process opening the file to read the pid, but finding * it empty. */ char tmp_pid_file[1024]; snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file); if ((fp = fopen(tmp_pid_file, "w")) == NULL) { vperror("Could not open the pid file %s for writing", tmp_pid_file); return; } fprintf(fp,"%ld\n", (long)getpid()); if (fclose(fp) == -1) { vperror("Could not close the pid file %s", tmp_pid_file); } if (rename(tmp_pid_file, pid_file) != 0) { vperror("Could not rename the pid file from %s to %s", tmp_pid_file, pid_file); } } static void remove_pidfile(const char *pid_file) { if (pid_file == NULL) return; if (unlink(pid_file) != 0) { vperror("Could not remove the pid file %s", pid_file); } } static void sig_handler(const int sig) { printf("Signal handled: %s.\n", strsignal(sig)); exit(EXIT_SUCCESS); } static void sighup_handler(const int sig) { settings.sig_hup = true; } #ifndef HAVE_SIGIGNORE static int sigignore(int sig) { struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 }; if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) { return -1; } return 0; } #endif /* * On systems that supports multiple page sizes we may reduce the * number of TLB-misses by using the biggest available page size */ static int enable_large_pages(void) { #if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL) int ret = -1; size_t sizes[32]; int avail = getpagesizes(sizes, 32); if (avail != -1) { size_t max = sizes[0]; struct memcntl_mha arg = {0}; int ii; for (ii = 1; ii < avail; ++ii) { if (max < sizes[ii]) { max = sizes[ii]; } } arg.mha_flags = 0; arg.mha_pagesize = max; arg.mha_cmd = MHA_MAPSIZE_BSSBRK; if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) { fprintf(stderr, "Failed to set large pages: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } else { ret = 0; } } else { fprintf(stderr, "Failed to get supported pagesizes: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } return ret; #elif defined(__linux__) && defined(MADV_HUGEPAGE) /* check if transparent hugepages is compiled into the kernel */ struct stat st; int ret = stat("/sys/kernel/mm/transparent_hugepage/enabled", &st); if (ret || !(st.st_mode & S_IFREG)) { fprintf(stderr, "Transparent huge pages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #elif defined(__FreeBSD__) int spages; size_t spagesl = sizeof(spages); if (sysctlbyname("vm.pmap.pg_ps_enabled", &spages, &spagesl, NULL, 0) != 0) { fprintf(stderr, "Could not evaluate the presence of superpages features."); return -1; } if (spages != 1) { fprintf(stderr, "Superpages support not detected.\n"); fprintf(stderr, "Will use default page size.\n"); return -1; } return 0; #else return -1; #endif } /** * Do basic sanity check of the runtime environment * @return true if no errors found, false if we can't use this env */ static bool sanitycheck(void) { /* One of our biggest problems is old and bogus libevents */ const char *ever = event_get_version(); if (ever != NULL) { if (strncmp(ever, "1.", 2) == 0) { /* Require at least 1.3 (that's still a couple of years old) */ if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) { fprintf(stderr, "You are using libevent %s.\nPlease upgrade to" " a more recent version (1.3 or newer)\n", event_get_version()); return false; } } } return true; } static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) { char *b = NULL; uint32_t size = 0; int i = 0; uint32_t last_size = 0; if (strlen(s) < 1) return false; for (char *p = strtok_r(s, "-", &b); p != NULL; p = strtok_r(NULL, "-", &b)) { if (!safe_strtoul(p, &size) || size < settings.chunk_size || size > settings.slab_chunk_size_max) { fprintf(stderr, "slab size %u is out of valid range\n", size); return false; } if (last_size >= size) { fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size); return false; } if (size <= last_size + CHUNK_ALIGN_BYTES) { fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n", size, CHUNK_ALIGN_BYTES); return false; } slab_sizes[i++] = size; last_size = size; if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) { fprintf(stderr, "too many slab classes specified\n"); return false; } } slab_sizes[i] = 0; return true; } int main (int argc, char **argv) { int c; bool lock_memory = false; bool do_daemonize = false; bool preallocate = false; int maxcore = 0; char *username = NULL; char *pid_file = NULL; struct passwd *pw; struct rlimit rlim; char *buf; char unit = '\0'; int size_max = 0; int retval = EXIT_SUCCESS; bool protocol_specified = false; bool tcp_specified = false; bool udp_specified = false; bool start_lru_maintainer = true; bool start_lru_crawler = true; bool start_assoc_maint = true; enum hashfunc_type hash_type = MURMUR3_HASH; uint32_t tocrawl; uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES]; bool use_slab_sizes = false; char *slab_sizes_unparsed = NULL; bool slab_chunk_size_changed = false; #ifdef EXTSTORE void *storage = NULL; struct extstore_conf_file *storage_file = NULL; struct extstore_conf ext_cf; #endif char *subopts, *subopts_orig; char *subopts_value; enum { MAXCONNS_FAST = 0, HASHPOWER_INIT, NO_HASHEXPAND, SLAB_REASSIGN, SLAB_AUTOMOVE, SLAB_AUTOMOVE_RATIO, SLAB_AUTOMOVE_WINDOW, TAIL_REPAIR_TIME, HASH_ALGORITHM, LRU_CRAWLER, LRU_CRAWLER_SLEEP, LRU_CRAWLER_TOCRAWL, LRU_MAINTAINER, HOT_LRU_PCT, WARM_LRU_PCT, HOT_MAX_FACTOR, WARM_MAX_FACTOR, TEMPORARY_TTL, IDLE_TIMEOUT, WATCHER_LOGBUF_SIZE, WORKER_LOGBUF_SIZE, SLAB_SIZES, SLAB_CHUNK_MAX, TRACK_SIZES, NO_INLINE_ASCII_RESP, MODERN, NO_MODERN, NO_CHUNKED_ITEMS, NO_SLAB_REASSIGN, NO_SLAB_AUTOMOVE, NO_MAXCONNS_FAST, INLINE_ASCII_RESP, NO_LRU_CRAWLER, NO_LRU_MAINTAINER, NO_DROP_PRIVILEGES, DROP_PRIVILEGES, #ifdef TLS SSL_CERT, SSL_KEY, SSL_VERIFY_MODE, SSL_KEYFORM, SSL_CIPHERS, SSL_CA_CERT, SSL_WBUF_SIZE, #endif #ifdef MEMCACHED_DEBUG RELAXED_PRIVILEGES, #endif #ifdef EXTSTORE EXT_PAGE_SIZE, EXT_WBUF_SIZE, EXT_THREADS, EXT_IO_DEPTH, EXT_PATH, EXT_ITEM_SIZE, EXT_ITEM_AGE, EXT_LOW_TTL, EXT_RECACHE_RATE, EXT_COMPACT_UNDER, EXT_DROP_UNDER, EXT_MAX_FRAG, EXT_DROP_UNREAD, SLAB_AUTOMOVE_FREERATIO, #endif }; char *const subopts_tokens[] = { [MAXCONNS_FAST] = "maxconns_fast", [HASHPOWER_INIT] = "hashpower", [NO_HASHEXPAND] = "no_hashexpand", [SLAB_REASSIGN] = "slab_reassign", [SLAB_AUTOMOVE] = "slab_automove", [SLAB_AUTOMOVE_RATIO] = "slab_automove_ratio", [SLAB_AUTOMOVE_WINDOW] = "slab_automove_window", [TAIL_REPAIR_TIME] = "tail_repair_time", [HASH_ALGORITHM] = "hash_algorithm", [LRU_CRAWLER] = "lru_crawler", [LRU_CRAWLER_SLEEP] = "lru_crawler_sleep", [LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl", [LRU_MAINTAINER] = "lru_maintainer", [HOT_LRU_PCT] = "hot_lru_pct", [WARM_LRU_PCT] = "warm_lru_pct", [HOT_MAX_FACTOR] = "hot_max_factor", [WARM_MAX_FACTOR] = "warm_max_factor", [TEMPORARY_TTL] = "temporary_ttl", [IDLE_TIMEOUT] = "idle_timeout", [WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size", [WORKER_LOGBUF_SIZE] = "worker_logbuf_size", [SLAB_SIZES] = "slab_sizes", [SLAB_CHUNK_MAX] = "slab_chunk_max", [TRACK_SIZES] = "track_sizes", [NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp", [MODERN] = "modern", [NO_MODERN] = "no_modern", [NO_CHUNKED_ITEMS] = "no_chunked_items", [NO_SLAB_REASSIGN] = "no_slab_reassign", [NO_SLAB_AUTOMOVE] = "no_slab_automove", [NO_MAXCONNS_FAST] = "no_maxconns_fast", [INLINE_ASCII_RESP] = "inline_ascii_resp", [NO_LRU_CRAWLER] = "no_lru_crawler", [NO_LRU_MAINTAINER] = "no_lru_maintainer", [NO_DROP_PRIVILEGES] = "no_drop_privileges", [DROP_PRIVILEGES] = "drop_privileges", #ifdef TLS [SSL_CERT] = "ssl_chain_cert", [SSL_KEY] = "ssl_key", [SSL_VERIFY_MODE] = "ssl_verify_mode", [SSL_KEYFORM] = "ssl_keyformat", [SSL_CIPHERS] = "ssl_ciphers", [SSL_CA_CERT] = "ssl_ca_cert", [SSL_WBUF_SIZE] = "ssl_wbuf_size", #endif #ifdef MEMCACHED_DEBUG [RELAXED_PRIVILEGES] = "relaxed_privileges", #endif #ifdef EXTSTORE [EXT_PAGE_SIZE] = "ext_page_size", [EXT_WBUF_SIZE] = "ext_wbuf_size", [EXT_THREADS] = "ext_threads", [EXT_IO_DEPTH] = "ext_io_depth", [EXT_PATH] = "ext_path", [EXT_ITEM_SIZE] = "ext_item_size", [EXT_ITEM_AGE] = "ext_item_age", [EXT_LOW_TTL] = "ext_low_ttl", [EXT_RECACHE_RATE] = "ext_recache_rate", [EXT_COMPACT_UNDER] = "ext_compact_under", [EXT_DROP_UNDER] = "ext_drop_under", [EXT_MAX_FRAG] = "ext_max_frag", [EXT_DROP_UNREAD] = "ext_drop_unread", [SLAB_AUTOMOVE_FREERATIO] = "slab_automove_freeratio", #endif NULL }; if (!sanitycheck()) { return EX_OSERR; } /* handle SIGINT, SIGTERM */ signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGHUP, sighup_handler); /* init settings */ settings_init(); #ifdef EXTSTORE settings.ext_item_size = 512; settings.ext_item_age = UINT_MAX; settings.ext_low_ttl = 0; settings.ext_recache_rate = 2000; settings.ext_max_frag = 0.8; settings.ext_drop_unread = false; settings.ext_wbuf_size = 1024 * 1024 * 4; settings.ext_compact_under = 0; settings.ext_drop_under = 0; settings.slab_automove_freeratio = 0.01; ext_cf.page_size = 1024 * 1024 * 64; ext_cf.wbuf_size = settings.ext_wbuf_size; ext_cf.io_threadcount = 1; ext_cf.io_depth = 1; ext_cf.page_buckets = 4; ext_cf.wbuf_count = ext_cf.page_buckets; #endif /* Run regardless of initializing it later */ init_lru_maintainer(); /* set stderr non-buffering (for running under, say, daemontools) */ setbuf(stderr, NULL); char *shortopts = "a:" /* access mask for unix socket */ "A" /* enable admin shutdown command */ "Z" /* enable SSL */ "p:" /* TCP port number to listen on */ "s:" /* unix socket path to listen on */ "U:" /* UDP port number to listen on */ "m:" /* max memory to use for items in megabytes */ "M" /* return error on memory exhausted */ "c:" /* max simultaneous connections */ "k" /* lock down all paged memory */ "hiV" /* help, licence info, version */ "r" /* maximize core file limit */ "v" /* verbose */ "d" /* daemon mode */ "l:" /* interface to listen on */ "u:" /* user identity to run as */ "P:" /* save PID in file */ "f:" /* factor? */ "n:" /* minimum space allocated for key+value+flags */ "t:" /* threads */ "D:" /* prefix delimiter? */ "L" /* Large memory pages */ "R:" /* max requests per event */ "C" /* Disable use of CAS */ "b:" /* backlog queue limit */ "B:" /* Binding protocol */ "I:" /* Max item size */ "S" /* Sasl ON */ "F" /* Disable flush_all */ "X" /* Disable dump commands */ "Y:" /* Enable token auth */ "o:" /* Extended generic options */ ; /* process arguments */ #ifdef HAVE_GETOPT_LONG const struct option longopts[] = { {"unix-mask", required_argument, 0, 'a'}, {"enable-shutdown", no_argument, 0, 'A'}, {"enable-ssl", no_argument, 0, 'Z'}, {"port", required_argument, 0, 'p'}, {"unix-socket", required_argument, 0, 's'}, {"udp-port", required_argument, 0, 'U'}, {"memory-limit", required_argument, 0, 'm'}, {"disable-evictions", no_argument, 0, 'M'}, {"conn-limit", required_argument, 0, 'c'}, {"lock-memory", no_argument, 0, 'k'}, {"help", no_argument, 0, 'h'}, {"license", no_argument, 0, 'i'}, {"version", no_argument, 0, 'V'}, {"enable-coredumps", no_argument, 0, 'r'}, {"verbose", optional_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"listen", required_argument, 0, 'l'}, {"user", required_argument, 0, 'u'}, {"pidfile", required_argument, 0, 'P'}, {"slab-growth-factor", required_argument, 0, 'f'}, {"slab-min-size", required_argument, 0, 'n'}, {"threads", required_argument, 0, 't'}, {"enable-largepages", no_argument, 0, 'L'}, {"max-reqs-per-event", required_argument, 0, 'R'}, {"disable-cas", no_argument, 0, 'C'}, {"listen-backlog", required_argument, 0, 'b'}, {"protocol", required_argument, 0, 'B'}, {"max-item-size", required_argument, 0, 'I'}, {"enable-sasl", no_argument, 0, 'S'}, {"disable-flush-all", no_argument, 0, 'F'}, {"disable-dumping", no_argument, 0, 'X'}, {"auth-file", required_argument, 0, 'Y'}, {"extended", required_argument, 0, 'o'}, {0, 0, 0, 0} }; int optindex; while (-1 != (c = getopt_long(argc, argv, shortopts, longopts, &optindex))) { #else while (-1 != (c = getopt(argc, argv, shortopts))) { #endif switch (c) { case 'A': /* enables "shutdown" command */ settings.shutdown_command = true; break; case 'Z': /* enable secure communication*/ #ifdef TLS settings.ssl_enabled = true; #else fprintf(stderr, "This server is not built with TLS support.\n"); exit(EX_USAGE); #endif break; case 'a': /* access for unix domain socket, as octal mask (like chmod)*/ settings.access= strtol(optarg,NULL,8); break; case 'U': settings.udpport = atoi(optarg); udp_specified = true; break; case 'p': settings.port = atoi(optarg); tcp_specified = true; break; case 's': settings.socketpath = optarg; break; case 'm': settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024; break; case 'M': settings.evict_to_free = 0; break; case 'c': settings.maxconns = atoi(optarg); if (settings.maxconns <= 0) { fprintf(stderr, "Maximum connections must be greater than 0\n"); return 1; } break; case 'h': usage(); exit(EXIT_SUCCESS); case 'i': usage_license(); exit(EXIT_SUCCESS); case 'V': printf(PACKAGE " " VERSION "\n"); exit(EXIT_SUCCESS); case 'k': lock_memory = true; break; case 'v': settings.verbose++; break; case 'l': if (settings.inter != NULL) { if (strstr(settings.inter, optarg) != NULL) { break; } size_t len = strlen(settings.inter) + strlen(optarg) + 2; char *p = malloc(len); if (p == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return 1; } snprintf(p, len, "%s,%s", settings.inter, optarg); free(settings.inter); settings.inter = p; } else { settings.inter= strdup(optarg); } break; case 'd': do_daemonize = true; break; case 'r': maxcore = 1; break; case 'R': settings.reqs_per_event = atoi(optarg); if (settings.reqs_per_event == 0) { fprintf(stderr, "Number of requests per event must be greater than 0\n"); return 1; } break; case 'u': username = optarg; break; case 'P': pid_file = optarg; break; case 'f': settings.factor = atof(optarg); if (settings.factor <= 1.0) { fprintf(stderr, "Factor must be greater than 1\n"); return 1; } break; case 'n': settings.chunk_size = atoi(optarg); if (settings.chunk_size == 0) { fprintf(stderr, "Chunk size must be greater than 0\n"); return 1; } break; case 't': settings.num_threads = atoi(optarg); if (settings.num_threads <= 0) { fprintf(stderr, "Number of threads must be greater than 0\n"); return 1; } /* There're other problems when you get above 64 threads. * In the future we should portably detect # of cores for the * default. */ if (settings.num_threads > 64) { fprintf(stderr, "WARNING: Setting a high number of worker" "threads is not recommended.\n" " Set this value to the number of cores in" " your machine or less.\n"); } break; case 'D': if (! optarg || ! optarg[0]) { fprintf(stderr, "No delimiter specified\n"); return 1; } settings.prefix_delimiter = optarg[0]; settings.detail_enabled = 1; break; case 'L' : if (enable_large_pages() == 0) { preallocate = true; } else { fprintf(stderr, "Cannot enable large pages on this system\n" "(There is no support as of this version)\n"); return 1; } break; case 'C' : settings.use_cas = false; break; case 'b' : settings.backlog = atoi(optarg); break; case 'B': protocol_specified = true; if (strcmp(optarg, "auto") == 0) { settings.binding_protocol = negotiating_prot; } else if (strcmp(optarg, "binary") == 0) { settings.binding_protocol = binary_prot; } else if (strcmp(optarg, "ascii") == 0) { settings.binding_protocol = ascii_prot; } else { fprintf(stderr, "Invalid value for binding protocol: %s\n" " -- should be one of auto, binary, or ascii\n", optarg); exit(EX_USAGE); } break; case 'I': buf = strdup(optarg); unit = buf[strlen(buf)-1]; if (unit == 'k' || unit == 'm' || unit == 'K' || unit == 'M') { buf[strlen(buf)-1] = '\0'; size_max = atoi(buf); if (unit == 'k' || unit == 'K') size_max *= 1024; if (unit == 'm' || unit == 'M') size_max *= 1024 * 1024; settings.item_size_max = size_max; } else { settings.item_size_max = atoi(buf); } free(buf); break; case 'S': /* set Sasl authentication to true. Default is false */ #ifndef ENABLE_SASL fprintf(stderr, "This server is not built with SASL support.\n"); exit(EX_USAGE); #endif settings.sasl = true; break; case 'F' : settings.flush_enabled = false; break; case 'X' : settings.dump_enabled = false; break; case 'Y' : // dupe the file path now just in case the options get mangled. settings.auth_file = strdup(optarg); break; case 'o': /* It's sub-opts time! */ subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */ while (*subopts != '\0') { switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) { case MAXCONNS_FAST: settings.maxconns_fast = true; break; case HASHPOWER_INIT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for hashpower\n"); return 1; } settings.hashpower_init = atoi(subopts_value); if (settings.hashpower_init < 12) { fprintf(stderr, "Initial hashtable multiplier of %d is too low\n", settings.hashpower_init); return 1; } else if (settings.hashpower_init > 32) { fprintf(stderr, "Initial hashtable multiplier of %d is too high\n" "Choose a value based on \"STAT hash_power_level\" from a running instance\n", settings.hashpower_init); return 1; } break; case NO_HASHEXPAND: start_assoc_maint = false; break; case SLAB_REASSIGN: settings.slab_reassign = true; break; case SLAB_AUTOMOVE: if (subopts_value == NULL) { settings.slab_automove = 1; break; } settings.slab_automove = atoi(subopts_value); if (settings.slab_automove < 0 || settings.slab_automove > 2) { fprintf(stderr, "slab_automove must be between 0 and 2\n"); return 1; } break; case SLAB_AUTOMOVE_RATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_ratio argument\n"); return 1; } settings.slab_automove_ratio = atof(subopts_value); if (settings.slab_automove_ratio <= 0 || settings.slab_automove_ratio > 1) { fprintf(stderr, "slab_automove_ratio must be > 0 and < 1\n"); return 1; } break; case SLAB_AUTOMOVE_WINDOW: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_window argument\n"); return 1; } settings.slab_automove_window = atoi(subopts_value); if (settings.slab_automove_window < 3) { fprintf(stderr, "slab_automove_window must be > 2\n"); return 1; } break; case TAIL_REPAIR_TIME: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for tail_repair_time\n"); return 1; } settings.tail_repair_time = atoi(subopts_value); if (settings.tail_repair_time < 10) { fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n"); return 1; } break; case HASH_ALGORITHM: if (subopts_value == NULL) { fprintf(stderr, "Missing hash_algorithm argument\n"); return 1; }; if (strcmp(subopts_value, "jenkins") == 0) { hash_type = JENKINS_HASH; } else if (strcmp(subopts_value, "murmur3") == 0) { hash_type = MURMUR3_HASH; } else { fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n"); return 1; } break; case LRU_CRAWLER: start_lru_crawler = true; break; case LRU_CRAWLER_SLEEP: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_sleep value\n"); return 1; } settings.lru_crawler_sleep = atoi(subopts_value); if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) { fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n"); return 1; } break; case LRU_CRAWLER_TOCRAWL: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_tocrawl value\n"); return 1; } if (!safe_strtoul(subopts_value, &tocrawl)) { fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n"); return 1; } settings.lru_crawler_tocrawl = tocrawl; break; case LRU_MAINTAINER: start_lru_maintainer = true; settings.lru_segmented = true; break; case HOT_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_lru_pct argument\n"); return 1; } settings.hot_lru_pct = atoi(subopts_value); if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) { fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n"); return 1; } break; case WARM_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_lru_pct argument\n"); return 1; } settings.warm_lru_pct = atoi(subopts_value); if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) { fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n"); return 1; } break; case HOT_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_max_factor argument\n"); return 1; } settings.hot_max_factor = atof(subopts_value); if (settings.hot_max_factor <= 0) { fprintf(stderr, "hot_max_factor must be > 0\n"); return 1; } break; case WARM_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_max_factor argument\n"); return 1; } settings.warm_max_factor = atof(subopts_value); if (settings.warm_max_factor <= 0) { fprintf(stderr, "warm_max_factor must be > 0\n"); return 1; } break; case TEMPORARY_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing temporary_ttl argument\n"); return 1; } settings.temp_lru = true; settings.temporary_ttl = atoi(subopts_value); break; case IDLE_TIMEOUT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for idle_timeout\n"); return 1; } settings.idle_timeout = atoi(subopts_value); break; case WATCHER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing watcher_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) { fprintf(stderr, "could not parse argument to watcher_logbuf_size\n"); return 1; } settings.logger_watcher_buf_size *= 1024; /* kilobytes */ break; case WORKER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing worker_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) { fprintf(stderr, "could not parse argument to worker_logbuf_size\n"); return 1; } settings.logger_buf_size *= 1024; /* kilobytes */ case SLAB_SIZES: slab_sizes_unparsed = strdup(subopts_value); break; case SLAB_CHUNK_MAX: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_chunk_max argument\n"); } if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) { fprintf(stderr, "could not parse argument to slab_chunk_max\n"); } slab_chunk_size_changed = true; break; case TRACK_SIZES: item_stats_sizes_init(); break; case NO_INLINE_ASCII_RESP: break; case INLINE_ASCII_RESP: break; case NO_CHUNKED_ITEMS: settings.slab_chunk_size_max = settings.slab_page_size; break; case NO_SLAB_REASSIGN: settings.slab_reassign = false; break; case NO_SLAB_AUTOMOVE: settings.slab_automove = 0; break; case NO_MAXCONNS_FAST: settings.maxconns_fast = false; break; case NO_LRU_CRAWLER: settings.lru_crawler = false; start_lru_crawler = false; break; case NO_LRU_MAINTAINER: start_lru_maintainer = false; settings.lru_segmented = false; break; #ifdef TLS case SSL_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_chain_cert argument\n"); return 1; } settings.ssl_chain_cert = strdup(subopts_value); break; case SSL_KEY: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_key argument\n"); return 1; } settings.ssl_key = strdup(subopts_value); break; case SSL_VERIFY_MODE: { if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_verify_mode argument\n"); return 1; } int verify = 0; if (!safe_strtol(subopts_value, &verify)) { fprintf(stderr, "could not parse argument to ssl_verify_mode\n"); return 1; } switch(verify) { case 0: settings.ssl_verify_mode = SSL_VERIFY_NONE; break; case 1: settings.ssl_verify_mode = SSL_VERIFY_PEER; break; case 2: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; break; case 3: settings.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; break; default: fprintf(stderr, "Invalid ssl_verify_mode. Use help to see valid options.\n"); return 1; } break; } case SSL_KEYFORM: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_keyformat argument\n"); return 1; } if (!safe_strtol(subopts_value, &settings.ssl_keyformat)) { fprintf(stderr, "could not parse argument to ssl_keyformat\n"); return 1; } break; case SSL_CIPHERS: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ciphers argument\n"); return 1; } settings.ssl_ciphers = strdup(subopts_value); break; case SSL_CA_CERT: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_ca_cert argument\n"); return 1; } settings.ssl_ca_cert = strdup(subopts_value); break; case SSL_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ssl_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ssl_wbuf_size)) { fprintf(stderr, "could not parse argument to ssl_wbuf_size\n"); return 1; } settings.ssl_wbuf_size *= 1024; /* kilobytes */ break; #endif #ifdef EXTSTORE case EXT_PAGE_SIZE: if (storage_file) { fprintf(stderr, "Must specify ext_page_size before any ext_path arguments\n"); return 1; } if (subopts_value == NULL) { fprintf(stderr, "Missing ext_page_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.page_size)) { fprintf(stderr, "could not parse argument to ext_page_size\n"); return 1; } ext_cf.page_size *= 1024 * 1024; /* megabytes */ break; case EXT_WBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_wbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.wbuf_size)) { fprintf(stderr, "could not parse argument to ext_wbuf_size\n"); return 1; } ext_cf.wbuf_size *= 1024 * 1024; /* megabytes */ settings.ext_wbuf_size = ext_cf.wbuf_size; break; case EXT_THREADS: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_threads argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_threadcount)) { fprintf(stderr, "could not parse argument to ext_threads\n"); return 1; } break; case EXT_IO_DEPTH: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_io_depth argument\n"); return 1; } if (!safe_strtoul(subopts_value, &ext_cf.io_depth)) { fprintf(stderr, "could not parse argument to ext_io_depth\n"); return 1; } break; case EXT_ITEM_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_size)) { fprintf(stderr, "could not parse argument to ext_item_size\n"); return 1; } break; case EXT_ITEM_AGE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_item_age argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_item_age)) { fprintf(stderr, "could not parse argument to ext_item_age\n"); return 1; } break; case EXT_LOW_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_low_ttl argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_low_ttl)) { fprintf(stderr, "could not parse argument to ext_low_ttl\n"); return 1; } break; case EXT_RECACHE_RATE: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_recache_rate argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_recache_rate)) { fprintf(stderr, "could not parse argument to ext_recache_rate\n"); return 1; } break; case EXT_COMPACT_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_compact_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_compact_under)) { fprintf(stderr, "could not parse argument to ext_compact_under\n"); return 1; } break; case EXT_DROP_UNDER: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_drop_under argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.ext_drop_under)) { fprintf(stderr, "could not parse argument to ext_drop_under\n"); return 1; } break; case EXT_MAX_FRAG: if (subopts_value == NULL) { fprintf(stderr, "Missing ext_max_frag argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.ext_max_frag)) { fprintf(stderr, "could not parse argument to ext_max_frag\n"); return 1; } break; case SLAB_AUTOMOVE_FREERATIO: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_automove_freeratio argument\n"); return 1; } if (!safe_strtod(subopts_value, &settings.slab_automove_freeratio)) { fprintf(stderr, "could not parse argument to slab_automove_freeratio\n"); return 1; } break; case EXT_DROP_UNREAD: settings.ext_drop_unread = true; break; case EXT_PATH: if (subopts_value) { struct extstore_conf_file *tmp = storage_conf_parse(subopts_value, ext_cf.page_size); if (tmp == NULL) { fprintf(stderr, "failed to parse ext_path argument\n"); return 1; } if (storage_file != NULL) { tmp->next = storage_file; } storage_file = tmp; } else { fprintf(stderr, "missing argument to ext_path, ie: ext_path=/d/file:5G\n"); return 1; } break; #endif case MODERN: /* currently no new defaults */ break; case NO_MODERN: if (!slab_chunk_size_changed) { settings.slab_chunk_size_max = settings.slab_page_size; } settings.slab_reassign = false; settings.slab_automove = 0; settings.maxconns_fast = false; settings.lru_segmented = false; hash_type = JENKINS_HASH; start_lru_crawler = false; start_lru_maintainer = false; break; case NO_DROP_PRIVILEGES: settings.drop_privileges = false; break; case DROP_PRIVILEGES: settings.drop_privileges = true; break; #ifdef MEMCACHED_DEBUG case RELAXED_PRIVILEGES: settings.relaxed_privileges = true; break; #endif default: printf("Illegal suboption \"%s\"\n", subopts_value); return 1; } } free(subopts_orig); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } if (settings.item_size_max < 1024) { fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n"); exit(EX_USAGE); } if (settings.item_size_max > (settings.maxbytes / 2)) { fprintf(stderr, "Cannot set item size limit higher than 1/2 of memory max.\n"); exit(EX_USAGE); } if (settings.item_size_max > (1024 * 1024 * 1024)) { fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n"); exit(EX_USAGE); } if (settings.item_size_max > 1024 * 1024) { if (!slab_chunk_size_changed) { // Ideal new default is 16k, but needs stitching. settings.slab_chunk_size_max = settings.slab_page_size / 2; } } if (settings.slab_chunk_size_max > settings.item_size_max) { fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n", settings.slab_chunk_size_max, settings.item_size_max); exit(EX_USAGE); } if (settings.item_size_max % settings.slab_chunk_size_max != 0) { fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n", settings.item_size_max, settings.slab_chunk_size_max); exit(EX_USAGE); } if (settings.slab_page_size % settings.slab_chunk_size_max != 0) { fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n", settings.slab_chunk_size_max, settings.slab_page_size); exit(EX_USAGE); } #ifdef EXTSTORE if (storage_file) { if (settings.item_size_max > ext_cf.wbuf_size) { fprintf(stderr, "-I (item_size_max: %d) cannot be larger than ext_wbuf_size: %d\n", settings.item_size_max, ext_cf.wbuf_size); exit(EX_USAGE); } if (settings.udpport) { fprintf(stderr, "Cannot use UDP with extstore enabled (-U 0 to disable)\n"); exit(EX_USAGE); } } #endif // Reserve this for the new default. If factor size hasn't changed, use // new default. /*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) { settings.factor = 1.08; }*/ if (slab_sizes_unparsed != NULL) { if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) { use_slab_sizes = true; } else { exit(EX_USAGE); } } if (settings.hot_lru_pct + settings.warm_lru_pct > 80) { fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n"); exit(EX_USAGE); } if (settings.temp_lru && !start_lru_maintainer) { fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n"); exit(EX_USAGE); } if (hash_init(hash_type) != 0) { fprintf(stderr, "Failed to initialize hash_algorithm!\n"); exit(EX_USAGE); } /* * Use one workerthread to serve each UDP port if the user specified * multiple ports */ if (settings.inter != NULL && strchr(settings.inter, ',')) { settings.num_threads_per_udp = 1; } else { settings.num_threads_per_udp = settings.num_threads; } if (settings.sasl) { if (!protocol_specified) { settings.binding_protocol = binary_prot; } else { if (settings.binding_protocol != binary_prot) { fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n"); exit(EX_USAGE); } } } if (settings.auth_file) { if (!protocol_specified) { settings.binding_protocol = ascii_prot; } else { if (settings.binding_protocol != ascii_prot) { fprintf(stderr, "ERROR: You cannot allow the BINARY protocol while using ascii authentication tokens.\n"); exit(EX_USAGE); } } } if (udp_specified && settings.udpport != 0 && !tcp_specified) { settings.port = settings.udpport; } #ifdef TLS /* * Setup SSL if enabled */ if (settings.ssl_enabled) { if (!settings.port) { fprintf(stderr, "ERROR: You cannot enable SSL without a TCP port.\n"); exit(EX_USAGE); } // openssl init methods. SSL_load_error_strings(); SSLeay_add_ssl_algorithms(); // Initiate the SSL context. ssl_init(); } #endif if (maxcore != 0) { struct rlimit rlim_new; /* * First try raising to infinity; if that fails, try bringing * the soft limit to the hard. */ if (getrlimit(RLIMIT_CORE, &rlim) == 0) { rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) { /* failed. try raising just to the old max */ rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max; (void)setrlimit(RLIMIT_CORE, &rlim_new); } } /* * getrlimit again to see what we ended up with. Only fail if * the soft limit ends up 0, because then no core files will be * created at all. */ if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) { fprintf(stderr, "failed to ensure corefile creation\n"); exit(EX_OSERR); } } /* * If needed, increase rlimits to allow as many connections * as needed. */ if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to getrlimit number of files\n"); exit(EX_OSERR); } else { rlim.rlim_cur = settings.maxconns; rlim.rlim_max = settings.maxconns; if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n"); exit(EX_OSERR); } } /* lose root privileges if we have them */ if (getuid() == 0 || geteuid() == 0) { if (username == 0 || *username == '\0') { fprintf(stderr, "can't run as root without the -u switch\n"); exit(EX_USAGE); } if ((pw = getpwnam(username)) == 0) { fprintf(stderr, "can't find the user %s to switch to\n", username); exit(EX_NOUSER); } if (setgroups(0, NULL) < 0) { fprintf(stderr, "failed to drop supplementary groups\n"); exit(EX_OSERR); } if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { fprintf(stderr, "failed to assume identity of user %s\n", username); exit(EX_OSERR); } } /* Initialize Sasl if -S was specified */ if (settings.sasl) { init_sasl(); } /* daemonize if requested */ /* if we want to ensure our ability to dump core, don't chdir to / */ if (do_daemonize) { if (sigignore(SIGHUP) == -1) { perror("Failed to ignore SIGHUP"); } if (daemonize(maxcore, settings.verbose) == -1) { fprintf(stderr, "failed to daemon() in order to daemonize\n"); exit(EXIT_FAILURE); } } /* lock paged memory if needed */ if (lock_memory) { #ifdef HAVE_MLOCKALL int res = mlockall(MCL_CURRENT | MCL_FUTURE); if (res != 0) { fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n", strerror(errno)); } #else fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n"); #endif } /* initialize main thread libevent instance */ #if defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER >= 0x02000101 /* If libevent version is larger/equal to 2.0.2-alpha, use newer version */ struct event_config *ev_config; ev_config = event_config_new(); event_config_set_flag(ev_config, EVENT_BASE_FLAG_NOLOCK); main_base = event_base_new_with_config(ev_config); event_config_free(ev_config); #else /* Otherwise, use older API */ main_base = event_init(); #endif /* Load initial auth file if required */ if (settings.auth_file) { if (settings.udpport) { fprintf(stderr, "Cannot use UDP with ascii authentication enabled (-U 0 to disable)\n"); exit(EX_USAGE); } switch (authfile_load(settings.auth_file)) { case AUTHFILE_MISSING: // fall through. case AUTHFILE_OPENFAIL: vperror("Could not open authfile [%s] for reading", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OOM: fprintf(stderr, "Out of memory reading password file: %s", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_MALFORMED: fprintf(stderr, "Authfile [%s] has a malformed entry. Should be 'user:password'", settings.auth_file); exit(EXIT_FAILURE); break; case AUTHFILE_OK: break; } } /* initialize other stuff */ logger_init(); stats_init(); assoc_init(settings.hashpower_init); conn_init(); slabs_init(settings.maxbytes, settings.factor, preallocate, use_slab_sizes ? slab_sizes : NULL); #ifdef EXTSTORE if (storage_file) { enum extstore_res eres; if (settings.ext_compact_under == 0) { settings.ext_compact_under = storage_file->page_count / 4; /* Only rescues non-COLD items if below this threshold */ settings.ext_drop_under = storage_file->page_count / 4; } crc32c_init(); /* Init free chunks to zero. */ for (int x = 0; x < MAX_NUMBER_OF_SLAB_CLASSES; x++) { settings.ext_free_memchunks[x] = 0; } storage = extstore_init(storage_file, &ext_cf, &eres); if (storage == NULL) { fprintf(stderr, "Failed to initialize external storage: %s\n", extstore_err(eres)); if (eres == EXTSTORE_INIT_OPEN_FAIL) { perror("extstore open"); } exit(EXIT_FAILURE); } ext_storage = storage; /* page mover algorithm for extstore needs memory prefilled */ slabs_prefill_global(); } #endif if (settings.drop_privileges) { setup_privilege_violations_handler(); } /* * ignore SIGPIPE signals; we can use errno == EPIPE if we * need that information */ if (sigignore(SIGPIPE) == -1) { perror("failed to ignore SIGPIPE; sigaction"); exit(EX_OSERR); } /* start up worker threads if MT mode */ #ifdef EXTSTORE slabs_set_storage(storage); memcached_thread_init(settings.num_threads, storage); init_lru_crawler(storage); #else memcached_thread_init(settings.num_threads, NULL); init_lru_crawler(NULL); #endif if (start_assoc_maint && start_assoc_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (start_lru_crawler && start_item_crawler_thread() != 0) { fprintf(stderr, "Failed to enable LRU crawler thread\n"); exit(EXIT_FAILURE); } #ifdef EXTSTORE if (storage && start_storage_compact_thread(storage) != 0) { fprintf(stderr, "Failed to start storage compaction thread\n"); exit(EXIT_FAILURE); } if (storage && start_storage_write_thread(storage) != 0) { fprintf(stderr, "Failed to start storage writer thread\n"); exit(EXIT_FAILURE); } if (start_lru_maintainer && start_lru_maintainer_thread(storage) != 0) { #else if (start_lru_maintainer && start_lru_maintainer_thread(NULL) != 0) { #endif fprintf(stderr, "Failed to enable LRU maintainer thread\n"); return 1; } if (settings.slab_reassign && start_slab_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (settings.idle_timeout && start_conn_timeout_thread() == -1) { exit(EXIT_FAILURE); } /* initialise clock event */ clock_handler(0, 0, 0); /* create unix mode sockets after dropping privileges */ if (settings.socketpath != NULL) { errno = 0; if (server_socket_unix(settings.socketpath,settings.access)) { vperror("failed to listen on UNIX socket: %s", settings.socketpath); exit(EX_OSERR); } } /* create the listening socket, bind it, and init */ if (settings.socketpath == NULL) { const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME"); char *temp_portnumber_filename = NULL; size_t len; FILE *portnumber_file = NULL; if (portnumber_filename != NULL) { len = strlen(portnumber_filename)+4+1; temp_portnumber_filename = malloc(len); snprintf(temp_portnumber_filename, len, "%s.lck", portnumber_filename); portnumber_file = fopen(temp_portnumber_filename, "a"); if (portnumber_file == NULL) { fprintf(stderr, "Failed to open \"%s\": %s\n", temp_portnumber_filename, strerror(errno)); } } errno = 0; if (settings.port && server_sockets(settings.port, tcp_transport, portnumber_file)) { vperror("failed to listen on TCP port %d", settings.port); exit(EX_OSERR); } /* * initialization order: first create the listening sockets * (may need root on low ports), then drop root if needed, * then daemonize if needed, then init libevent (in some cases * descriptors created by libevent wouldn't survive forking). */ /* create the UDP listening socket and bind it */ errno = 0; if (settings.udpport && server_sockets(settings.udpport, udp_transport, portnumber_file)) { vperror("failed to listen on UDP port %d", settings.udpport); exit(EX_OSERR); } if (portnumber_file) { fclose(portnumber_file); rename(temp_portnumber_filename, portnumber_filename); } if (temp_portnumber_filename) free(temp_portnumber_filename); } /* Give the sockets a moment to open. I know this is dumb, but the error * is only an advisory. */ usleep(1000); if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n"); exit(EXIT_FAILURE); } if (pid_file != NULL) { save_pid(pid_file); } /* Drop privileges no longer needed */ if (settings.drop_privileges) { drop_privileges(); } /* Initialize the uriencode lookup table. */ uriencode_init(); /* enter the event loop */ if (event_base_loop(main_base, 0) != 0) { retval = EXIT_FAILURE; } stop_assoc_maintenance_thread(); /* remove the PID file if we're a daemon */ if (do_daemonize) remove_pidfile(pid_file); /* Clean up strdup() call for bind() address */ if (settings.inter) free(settings.inter); /* cleanup base */ event_base_free(main_base); return retval; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1011_0
crossvul-cpp_data_good_5295_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } CheckNumberCompactPixels; compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5295_0
crossvul-cpp_data_bad_296_0
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "git2/types.h" #include "git2/errors.h" #include "git2/refs.h" #include "git2/revwalk.h" #include "smart.h" #include "util.h" #include "netops.h" #include "posix.h" #include "buffer.h" #include <ctype.h> #define PKT_LEN_SIZE 4 static const char pkt_done_str[] = "0009done\n"; static const char pkt_flush_str[] = "0000"; static const char pkt_have_prefix[] = "0032have "; static const char pkt_want_prefix[] = "0032want "; static int flush_pkt(git_pkt **out) { git_pkt *pkt; pkt = git__malloc(sizeof(git_pkt)); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_FLUSH; *out = pkt; return 0; } /* the rest of the line will be useful for multi_ack and multi_ack_detailed */ static int ack_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ack *pkt; GIT_UNUSED(line); GIT_UNUSED(len); pkt = git__calloc(1, sizeof(git_pkt_ack)); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_ACK; line += 3; len -= 3; if (len >= GIT_OID_HEXSZ) { git_oid_fromstr(&pkt->oid, line + 1); line += GIT_OID_HEXSZ + 1; len -= GIT_OID_HEXSZ + 1; } if (len >= 7) { if (!git__prefixcmp(line + 1, "continue")) pkt->status = GIT_ACK_CONTINUE; if (!git__prefixcmp(line + 1, "common")) pkt->status = GIT_ACK_COMMON; if (!git__prefixcmp(line + 1, "ready")) pkt->status = GIT_ACK_READY; } *out = (git_pkt *) pkt; return 0; } static int nak_pkt(git_pkt **out) { git_pkt *pkt; pkt = git__malloc(sizeof(git_pkt)); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_NAK; *out = pkt; return 0; } static int pack_pkt(git_pkt **out) { git_pkt *pkt; pkt = git__malloc(sizeof(git_pkt)); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_PACK; *out = pkt; return 0; } static int comment_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_comment *pkt; size_t alloclen; GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_comment), len); GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); pkt = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_COMMENT; memcpy(pkt->comment, line, len); pkt->comment[len] = '\0'; *out = (git_pkt *) pkt; return 0; } static int err_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_err *pkt; size_t alloclen; /* Remove "ERR " from the line */ line += 4; len -= 4; GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len); GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); pkt = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_ERR; pkt->len = (int)len; memcpy(pkt->error, line, len); pkt->error[len] = '\0'; *out = (git_pkt *) pkt; return 0; } static int data_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_data *pkt; size_t alloclen; line++; len--; GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len); pkt = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_DATA; pkt->len = (int) len; memcpy(pkt->data, line, len); *out = (git_pkt *) pkt; return 0; } static int sideband_progress_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_progress *pkt; size_t alloclen; line++; len--; GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(git_pkt_progress), len); pkt = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_PROGRESS; pkt->len = (int) len; memcpy(pkt->data, line, len); *out = (git_pkt *) pkt; return 0; } static int sideband_error_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_err *pkt; size_t alloc_len; line++; len--; GITERR_CHECK_ALLOC_ADD(&alloc_len, sizeof(git_pkt_err), len); GITERR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, 1); pkt = git__malloc(alloc_len); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_ERR; pkt->len = (int)len; memcpy(pkt->error, line, len); pkt->error[len] = '\0'; *out = (git_pkt *)pkt; return 0; } /* * Parse an other-ref line. */ static int ref_pkt(git_pkt **out, const char *line, size_t len) { int error; git_pkt_ref *pkt; size_t alloclen; pkt = git__malloc(sizeof(git_pkt_ref)); GITERR_CHECK_ALLOC(pkt); memset(pkt, 0x0, sizeof(git_pkt_ref)); pkt->type = GIT_PKT_REF; if ((error = git_oid_fromstr(&pkt->head.oid, line)) < 0) goto error_out; /* Check for a bit of consistency */ if (line[GIT_OID_HEXSZ] != ' ') { giterr_set(GITERR_NET, "error parsing pkt-line"); error = -1; goto error_out; } /* Jump from the name */ line += GIT_OID_HEXSZ + 1; len -= (GIT_OID_HEXSZ + 1); if (line[len - 1] == '\n') --len; GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->head.name = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt->head.name); memcpy(pkt->head.name, line, len); pkt->head.name[len] = '\0'; if (strlen(pkt->head.name) < len) { pkt->capabilities = strchr(pkt->head.name, '\0') + 1; } *out = (git_pkt *)pkt; return 0; error_out: git__free(pkt); return error; } static int ok_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ok *pkt; const char *ptr; size_t alloc_len; pkt = git__malloc(sizeof(*pkt)); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_OK; line += 3; /* skip "ok " */ if (!(ptr = strchr(line, '\n'))) { giterr_set(GITERR_NET, "invalid packet line"); git__free(pkt); return -1; } len = ptr - line; GITERR_CHECK_ALLOC_ADD(&alloc_len, len, 1); pkt->ref = git__malloc(alloc_len); GITERR_CHECK_ALLOC(pkt->ref); memcpy(pkt->ref, line, len); pkt->ref[len] = '\0'; *out = (git_pkt *)pkt; return 0; } static int ng_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_ng *pkt; const char *ptr; size_t alloclen; pkt = git__malloc(sizeof(*pkt)); GITERR_CHECK_ALLOC(pkt); pkt->ref = NULL; pkt->type = GIT_PKT_NG; line += 3; /* skip "ng " */ if (!(ptr = strchr(line, ' '))) goto out_err; len = ptr - line; GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->ref = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt->ref); memcpy(pkt->ref, line, len); pkt->ref[len] = '\0'; line = ptr + 1; if (!(ptr = strchr(line, '\n'))) goto out_err; len = ptr - line; GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1); pkt->msg = git__malloc(alloclen); GITERR_CHECK_ALLOC(pkt->msg); memcpy(pkt->msg, line, len); pkt->msg[len] = '\0'; *out = (git_pkt *)pkt; return 0; out_err: giterr_set(GITERR_NET, "invalid packet line"); git__free(pkt->ref); git__free(pkt); return -1; } static int unpack_pkt(git_pkt **out, const char *line, size_t len) { git_pkt_unpack *pkt; GIT_UNUSED(len); pkt = git__malloc(sizeof(*pkt)); GITERR_CHECK_ALLOC(pkt); pkt->type = GIT_PKT_UNPACK; if (!git__prefixcmp(line, "unpack ok")) pkt->unpack_ok = 1; else pkt->unpack_ok = 0; *out = (git_pkt *)pkt; return 0; } static int32_t parse_len(const char *line) { char num[PKT_LEN_SIZE + 1]; int i, k, error; int32_t len; const char *num_end; memcpy(num, line, PKT_LEN_SIZE); num[PKT_LEN_SIZE] = '\0'; for (i = 0; i < PKT_LEN_SIZE; ++i) { if (!isxdigit(num[i])) { /* Make sure there are no special characters before passing to error message */ for (k = 0; k < PKT_LEN_SIZE; ++k) { if(!isprint(num[k])) { num[k] = '.'; } } giterr_set(GITERR_NET, "invalid hex digit in length: '%s'", num); return -1; } } if ((error = git__strtol32(&len, num, &num_end, 16)) < 0) return error; return len; } /* * As per the documentation, the syntax is: * * pkt-line = data-pkt / flush-pkt * data-pkt = pkt-len pkt-payload * pkt-len = 4*(HEXDIG) * pkt-payload = (pkt-len -4)*(OCTET) * flush-pkt = "0000" * * Which means that the first four bytes are the length of the line, * in ASCII hexadecimal (including itself) */ int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; /* * The length has to be exactly 0 in case of a flush * packet or greater than PKT_LEN_SIZE, as the decoded * length includes its own encoded length of four bytes. */ if (len != 0 && len < PKT_LEN_SIZE) return GIT_ERROR; line += PKT_LEN_SIZE; /* * The Git protocol does not specify empty lines as part * of the protocol. Not knowing what to do with an empty * line, we should return an error upon hitting one. */ if (len == PKT_LEN_SIZE) { giterr_set_str(GITERR_NET, "Invalid empty packet"); return GIT_ERROR; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; } void git_pkt_free(git_pkt *pkt) { if (pkt->type == GIT_PKT_REF) { git_pkt_ref *p = (git_pkt_ref *) pkt; git__free(p->head.name); git__free(p->head.symref_target); } if (pkt->type == GIT_PKT_OK) { git_pkt_ok *p = (git_pkt_ok *) pkt; git__free(p->ref); } if (pkt->type == GIT_PKT_NG) { git_pkt_ng *p = (git_pkt_ng *) pkt; git__free(p->ref); git__free(p->msg); } git__free(pkt); } int git_pkt_buffer_flush(git_buf *buf) { return git_buf_put(buf, pkt_flush_str, strlen(pkt_flush_str)); } static int buffer_want_with_caps(const git_remote_head *head, transport_smart_caps *caps, git_buf *buf) { git_buf str = GIT_BUF_INIT; char oid[GIT_OID_HEXSZ +1] = {0}; size_t len; /* Prefer multi_ack_detailed */ if (caps->multi_ack_detailed) git_buf_puts(&str, GIT_CAP_MULTI_ACK_DETAILED " "); else if (caps->multi_ack) git_buf_puts(&str, GIT_CAP_MULTI_ACK " "); /* Prefer side-band-64k if the server supports both */ if (caps->side_band_64k) git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND_64K); else if (caps->side_band) git_buf_printf(&str, "%s ", GIT_CAP_SIDE_BAND); if (caps->include_tag) git_buf_puts(&str, GIT_CAP_INCLUDE_TAG " "); if (caps->thin_pack) git_buf_puts(&str, GIT_CAP_THIN_PACK " "); if (caps->ofs_delta) git_buf_puts(&str, GIT_CAP_OFS_DELTA " "); if (git_buf_oom(&str)) return -1; len = strlen("XXXXwant ") + GIT_OID_HEXSZ + 1 /* NUL */ + git_buf_len(&str) + 1 /* LF */; if (len > 0xffff) { giterr_set(GITERR_NET, "tried to produce packet with invalid length %" PRIuZ, len); return -1; } git_buf_grow_by(buf, len); git_oid_fmt(oid, &head->oid); git_buf_printf(buf, "%04xwant %s %s\n", (unsigned int)len, oid, git_buf_cstr(&str)); git_buf_free(&str); GITERR_CHECK_ALLOC_BUF(buf); return 0; } /* * All "want" packets have the same length and format, so what we do * is overwrite the OID each time. */ int git_pkt_buffer_wants( const git_remote_head * const *refs, size_t count, transport_smart_caps *caps, git_buf *buf) { size_t i = 0; const git_remote_head *head; if (caps->common) { for (; i < count; ++i) { head = refs[i]; if (!head->local) break; } if (buffer_want_with_caps(refs[i], caps, buf) < 0) return -1; i++; } for (; i < count; ++i) { char oid[GIT_OID_HEXSZ]; head = refs[i]; if (head->local) continue; git_oid_fmt(oid, &head->oid); git_buf_put(buf, pkt_want_prefix, strlen(pkt_want_prefix)); git_buf_put(buf, oid, GIT_OID_HEXSZ); git_buf_putc(buf, '\n'); if (git_buf_oom(buf)) return -1; } return git_pkt_buffer_flush(buf); } int git_pkt_buffer_have(git_oid *oid, git_buf *buf) { char oidhex[GIT_OID_HEXSZ + 1]; memset(oidhex, 0x0, sizeof(oidhex)); git_oid_fmt(oidhex, oid); return git_buf_printf(buf, "%s%s\n", pkt_have_prefix, oidhex); } int git_pkt_buffer_done(git_buf *buf) { return git_buf_puts(buf, pkt_done_str); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_296_0
crossvul-cpp_data_good_3911_1
/** * FreeRDP: A Remote Desktop Protocol Implementation * Auto-Detect PDUs * * Copyright 2014 Dell Software <Mike.McDonald@software.dell.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crypto.h> #include "autodetect.h" #define RDP_RTT_REQUEST_TYPE_CONTINUOUS 0x0001 #define RDP_RTT_REQUEST_TYPE_CONNECTTIME 0x1001 #define RDP_RTT_RESPONSE_TYPE 0x0000 #define RDP_BW_START_REQUEST_TYPE_CONTINUOUS 0x0014 #define RDP_BW_START_REQUEST_TYPE_TUNNEL 0x0114 #define RDP_BW_START_REQUEST_TYPE_CONNECTTIME 0x1014 #define RDP_BW_PAYLOAD_REQUEST_TYPE 0x0002 #define RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME 0x002B #define RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS 0x0429 #define RDP_BW_STOP_REQUEST_TYPE_TUNNEL 0x0629 #define RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME 0x0003 #define RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS 0x000B #define RDP_NETCHAR_SYNC_RESPONSE_TYPE 0x0018 typedef struct { UINT8 headerLength; UINT8 headerTypeId; UINT16 sequenceNumber; UINT16 requestType; } AUTODETECT_REQ_PDU; typedef struct { UINT8 headerLength; UINT8 headerTypeId; UINT16 sequenceNumber; UINT16 responseType; } AUTODETECT_RSP_PDU; static BOOL autodetect_send_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber, UINT16 requestType) { wStream* s; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending RTT Measure Request PDU"); Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */ context->rdp->autodetect->rttMeasureStartTime = GetTickCount64(); return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); } static BOOL autodetect_send_continuous_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_rtt_measure_request(context, sequenceNumber, RDP_RTT_REQUEST_TYPE_CONTINUOUS); } BOOL autodetect_send_connecttime_rtt_measure_request(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_rtt_measure_request(context, sequenceNumber, RDP_RTT_REQUEST_TYPE_CONNECTTIME); } static BOOL autodetect_send_rtt_measure_response(rdpRdp* rdp, UINT16 sequenceNumber) { wStream* s; /* Send the response PDU to the server */ s = rdp_message_channel_pdu_init(rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending RTT Measure Response PDU"); Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, RDP_RTT_RESPONSE_TYPE); /* responseType (1 byte) */ return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP); } static BOOL autodetect_send_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber, UINT16 requestType) { wStream* s; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Start PDU"); Stream_Write_UINT8(s, 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */ return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); } static BOOL autodetect_send_continuous_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_start(context, sequenceNumber, RDP_BW_START_REQUEST_TYPE_CONTINUOUS); } BOOL autodetect_send_connecttime_bandwidth_measure_start(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_start(context, sequenceNumber, RDP_BW_START_REQUEST_TYPE_CONNECTTIME); } BOOL autodetect_send_bandwidth_measure_payload(rdpContext* context, UINT16 payloadLength, UINT16 sequenceNumber) { wStream* s; UCHAR* buffer = NULL; BOOL bResult = FALSE; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Payload PDU -> payloadLength=%" PRIu16 "", payloadLength); /* 4-bytes aligned */ payloadLength &= ~3; if (!Stream_EnsureRemainingCapacity(s, 8 + payloadLength)) { Stream_Release(s); return FALSE; } Stream_Write_UINT8(s, 0x08); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, RDP_BW_PAYLOAD_REQUEST_TYPE); /* requestType (2 bytes) */ Stream_Write_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ /* Random data (better measurement in case the line is compressed) */ buffer = (UCHAR*)malloc(payloadLength); if (NULL == buffer) { Stream_Release(s); return FALSE; } winpr_RAND(buffer, payloadLength); Stream_Write(s, buffer, payloadLength); bResult = rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); free(buffer); return bResult; } static BOOL autodetect_send_bandwidth_measure_stop(rdpContext* context, UINT16 payloadLength, UINT16 sequenceNumber, UINT16 requestType) { wStream* s; UCHAR* buffer = NULL; BOOL bResult = FALSE; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Stop PDU -> payloadLength=%" PRIu16 "", payloadLength); /* 4-bytes aligned */ payloadLength &= ~3; Stream_Write_UINT8(s, requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME ? 0x08 : 0x06); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, requestType); /* requestType (2 bytes) */ if (requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME) { Stream_Write_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ if (payloadLength > 0) { if (!Stream_EnsureRemainingCapacity(s, payloadLength)) { Stream_Release(s); return FALSE; } /* Random data (better measurement in case the line is compressed) */ buffer = malloc(payloadLength); if (NULL == buffer) { Stream_Release(s); return FALSE; } winpr_RAND(buffer, payloadLength); Stream_Write(s, buffer, payloadLength); } } bResult = rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); free(buffer); return bResult; } static BOOL autodetect_send_continuous_bandwidth_measure_stop(rdpContext* context, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_stop(context, 0, sequenceNumber, RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS); } BOOL autodetect_send_connecttime_bandwidth_measure_stop(rdpContext* context, UINT16 payloadLength, UINT16 sequenceNumber) { return autodetect_send_bandwidth_measure_stop(context, payloadLength, sequenceNumber, RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME); } static BOOL autodetect_send_bandwidth_measure_results(rdpRdp* rdp, UINT16 responseType, UINT16 sequenceNumber) { BOOL success = TRUE; wStream* s; UINT64 timeDelta; /* Compute the total time */ timeDelta = GetTickCount64() - rdp->autodetect->bandwidthMeasureStartTime; /* Send the result PDU to the server */ s = rdp_message_channel_pdu_init(rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Results PDU -> timeDelta=%" PRIu32 ", byteCount=%" PRIu32 "", timeDelta, rdp->autodetect->bandwidthMeasureByteCount); Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, responseType); /* responseType (1 byte) */ Stream_Write_UINT32(s, timeDelta); /* timeDelta (4 bytes) */ Stream_Write_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ IFCALLRET(rdp->autodetect->ClientBandwidthMeasureResult, success, rdp->context, rdp->autodetect); if (!success) return FALSE; return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP); } static BOOL autodetect_send_netchar_result(rdpContext* context, UINT16 sequenceNumber) { wStream* s; s = rdp_message_channel_pdu_init(context->rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Network Characteristics Result PDU"); if (context->rdp->autodetect->netCharBandwidth > 0) { Stream_Write_UINT8(s, 0x12); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, 0x08C0); /* requestType (2 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ } else { Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, 0x0840); /* requestType (2 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Write_UINT32(s, context->rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ } return rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ); } static BOOL autodetect_send_netchar_sync(rdpRdp* rdp, UINT16 sequenceNumber) { wStream* s; /* Send the response PDU to the server */ s = rdp_message_channel_pdu_init(rdp); if (!s) return FALSE; WLog_VRB(AUTODETECT_TAG, "sending Network Characteristics Sync PDU -> bandwidth=%" PRIu32 ", rtt=%" PRIu32 "", rdp->autodetect->netCharBandwidth, rdp->autodetect->netCharAverageRTT); Stream_Write_UINT8(s, 0x0E); /* headerLength (1 byte) */ Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_RESPONSE); /* headerTypeId (1 byte) */ Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Write_UINT16(s, RDP_NETCHAR_SYNC_RESPONSE_TYPE); /* responseType (1 byte) */ Stream_Write_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Write_UINT32(s, rdp->autodetect->netCharAverageRTT); /* rtt (4 bytes) */ return rdp_send_message_channel_pdu(rdp, s, SEC_AUTODETECT_RSP); } static BOOL autodetect_recv_rtt_measure_request(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { if (autodetectReqPdu->headerLength != 0x06) return FALSE; WLog_VRB(AUTODETECT_TAG, "received RTT Measure Request PDU"); /* Send a response to the server */ return autodetect_send_rtt_measure_response(rdp, autodetectReqPdu->sequenceNumber); } static BOOL autodetect_recv_rtt_measure_response(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x06) return FALSE; WLog_VRB(AUTODETECT_TAG, "received RTT Measure Response PDU"); rdp->autodetect->netCharAverageRTT = GetTickCount64() - rdp->autodetect->rttMeasureStartTime; if (rdp->autodetect->netCharBaseRTT == 0 || rdp->autodetect->netCharBaseRTT > rdp->autodetect->netCharAverageRTT) rdp->autodetect->netCharBaseRTT = rdp->autodetect->netCharAverageRTT; IFCALLRET(rdp->autodetect->RTTMeasureResponse, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; } static BOOL autodetect_recv_bandwidth_measure_start(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { if (autodetectReqPdu->headerLength != 0x06) return FALSE; WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Start PDU - time=%" PRIu64 "", GetTickCount64()); /* Initialize bandwidth measurement parameters */ rdp->autodetect->bandwidthMeasureStartTime = GetTickCount64(); rdp->autodetect->bandwidthMeasureByteCount = 0; /* Continuous Auto-Detection: mark the start of the measurement */ if (autodetectReqPdu->requestType == RDP_BW_START_REQUEST_TYPE_CONTINUOUS) { rdp->autodetect->bandwidthMeasureStarted = TRUE; } return TRUE; } static BOOL autodetect_recv_bandwidth_measure_payload(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { UINT16 payloadLength; if (autodetectReqPdu->headerLength != 0x08) return FALSE; if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ if (!Stream_SafeSeek(s, payloadLength)) return FALSE; WLog_DBG(AUTODETECT_TAG, "received Bandwidth Measure Payload PDU -> payloadLength=%" PRIu16 "", payloadLength); /* Add the payload length to the bandwidth measurement parameters */ rdp->autodetect->bandwidthMeasureByteCount += payloadLength; return TRUE; } static BOOL autodetect_recv_bandwidth_measure_stop(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { UINT16 payloadLength; UINT16 responseType; if (autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME) { if (autodetectReqPdu->headerLength != 0x08) return FALSE; if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, payloadLength); /* payloadLength (2 bytes) */ } else { if (autodetectReqPdu->headerLength != 0x06) return FALSE; payloadLength = 0; } if (!Stream_SafeSeek(s, payloadLength)) return FALSE; WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Stop PDU -> payloadLength=%" PRIu16 "", payloadLength); /* Add the payload length to the bandwidth measurement parameters */ rdp->autodetect->bandwidthMeasureByteCount += payloadLength; /* Continuous Auto-Detection: mark the stop of the measurement */ if (autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS) { rdp->autodetect->bandwidthMeasureStarted = FALSE; } /* Send a response the server */ responseType = autodetectReqPdu->requestType == RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME ? RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME : RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS; return autodetect_send_bandwidth_measure_results(rdp, responseType, autodetectReqPdu->sequenceNumber); } static BOOL autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x0E) return FALSE; WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Results PDU"); if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ if (rdp->autodetect->bandwidthMeasureTimeDelta > 0) rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 / rdp->autodetect->bandwidthMeasureTimeDelta; else rdp->autodetect->netCharBandwidth = 0; IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; } static BOOL autodetect_recv_netchar_result(rdpRdp* rdp, wStream* s, AUTODETECT_REQ_PDU* autodetectReqPdu) { BOOL success = TRUE; switch (autodetectReqPdu->requestType) { case 0x0840: /* baseRTT and averageRTT fields are present (bandwidth field is not) */ if ((autodetectReqPdu->headerLength != 0x0E) || (Stream_GetRemainingLength(s) < 8)) return FALSE; Stream_Read_UINT32(s, rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ break; case 0x0880: /* bandwidth and averageRTT fields are present (baseRTT field is not) */ if ((autodetectReqPdu->headerLength != 0x0E) || (Stream_GetRemainingLength(s) < 8)) return FALSE; Stream_Read_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ break; case 0x08C0: /* baseRTT, bandwidth, and averageRTT fields are present */ if ((autodetectReqPdu->headerLength != 0x12) || (Stream_GetRemainingLength(s) < 12)) return FALSE; Stream_Read_UINT32(s, rdp->autodetect->netCharBaseRTT); /* baseRTT (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharBandwidth); /* bandwidth (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->netCharAverageRTT); /* averageRTT (4 bytes) */ break; } WLog_VRB(AUTODETECT_TAG, "received Network Characteristics Result PDU -> baseRTT=%" PRIu32 ", bandwidth=%" PRIu32 ", averageRTT=%" PRIu32 "", rdp->autodetect->netCharBaseRTT, rdp->autodetect->netCharBandwidth, rdp->autodetect->netCharAverageRTT); IFCALLRET(rdp->autodetect->NetworkCharacteristicsResult, success, rdp->context, autodetectReqPdu->sequenceNumber); return success; } int rdp_recv_autodetect_request_packet(rdpRdp* rdp, wStream* s) { AUTODETECT_REQ_PDU autodetectReqPdu; BOOL success = FALSE; if (Stream_GetRemainingLength(s) < 6) return -1; Stream_Read_UINT8(s, autodetectReqPdu.headerLength); /* headerLength (1 byte) */ Stream_Read_UINT8(s, autodetectReqPdu.headerTypeId); /* headerTypeId (1 byte) */ Stream_Read_UINT16(s, autodetectReqPdu.sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Read_UINT16(s, autodetectReqPdu.requestType); /* requestType (2 bytes) */ WLog_VRB(AUTODETECT_TAG, "rdp_recv_autodetect_request_packet: headerLength=%" PRIu8 ", headerTypeId=%" PRIu8 ", sequenceNumber=%" PRIu16 ", requestType=%04" PRIx16 "", autodetectReqPdu.headerLength, autodetectReqPdu.headerTypeId, autodetectReqPdu.sequenceNumber, autodetectReqPdu.requestType); if (autodetectReqPdu.headerTypeId != TYPE_ID_AUTODETECT_REQUEST) return -1; switch (autodetectReqPdu.requestType) { case RDP_RTT_REQUEST_TYPE_CONTINUOUS: case RDP_RTT_REQUEST_TYPE_CONNECTTIME: /* RTT Measure Request (RDP_RTT_REQUEST) - MS-RDPBCGR 2.2.14.1.1 */ success = autodetect_recv_rtt_measure_request(rdp, s, &autodetectReqPdu); break; case RDP_BW_START_REQUEST_TYPE_CONTINUOUS: case RDP_BW_START_REQUEST_TYPE_TUNNEL: case RDP_BW_START_REQUEST_TYPE_CONNECTTIME: /* Bandwidth Measure Start (RDP_BW_START) - MS-RDPBCGR 2.2.14.1.2 */ success = autodetect_recv_bandwidth_measure_start(rdp, s, &autodetectReqPdu); break; case RDP_BW_PAYLOAD_REQUEST_TYPE: /* Bandwidth Measure Payload (RDP_BW_PAYLOAD) - MS-RDPBCGR 2.2.14.1.3 */ success = autodetect_recv_bandwidth_measure_payload(rdp, s, &autodetectReqPdu); break; case RDP_BW_STOP_REQUEST_TYPE_CONNECTTIME: case RDP_BW_STOP_REQUEST_TYPE_CONTINUOUS: case RDP_BW_STOP_REQUEST_TYPE_TUNNEL: /* Bandwidth Measure Stop (RDP_BW_STOP) - MS-RDPBCGR 2.2.14.1.4 */ success = autodetect_recv_bandwidth_measure_stop(rdp, s, &autodetectReqPdu); break; case 0x0840: case 0x0880: case 0x08C0: /* Network Characteristics Result (RDP_NETCHAR_RESULT) - MS-RDPBCGR 2.2.14.1.5 */ success = autodetect_recv_netchar_result(rdp, s, &autodetectReqPdu); break; default: break; } return success ? 0 : -1; } int rdp_recv_autodetect_response_packet(rdpRdp* rdp, wStream* s) { AUTODETECT_RSP_PDU autodetectRspPdu; BOOL success = FALSE; if (Stream_GetRemainingLength(s) < 6) return -1; Stream_Read_UINT8(s, autodetectRspPdu.headerLength); /* headerLength (1 byte) */ Stream_Read_UINT8(s, autodetectRspPdu.headerTypeId); /* headerTypeId (1 byte) */ Stream_Read_UINT16(s, autodetectRspPdu.sequenceNumber); /* sequenceNumber (2 bytes) */ Stream_Read_UINT16(s, autodetectRspPdu.responseType); /* responseType (2 bytes) */ WLog_VRB(AUTODETECT_TAG, "rdp_recv_autodetect_response_packet: headerLength=%" PRIu8 ", headerTypeId=%" PRIu8 ", sequenceNumber=%" PRIu16 ", requestType=%04" PRIx16 "", autodetectRspPdu.headerLength, autodetectRspPdu.headerTypeId, autodetectRspPdu.sequenceNumber, autodetectRspPdu.responseType); if (autodetectRspPdu.headerTypeId != TYPE_ID_AUTODETECT_RESPONSE) return -1; switch (autodetectRspPdu.responseType) { case RDP_RTT_RESPONSE_TYPE: /* RTT Measure Response (RDP_RTT_RESPONSE) - MS-RDPBCGR 2.2.14.2.1 */ success = autodetect_recv_rtt_measure_response(rdp, s, &autodetectRspPdu); break; case RDP_BW_RESULTS_RESPONSE_TYPE_CONNECTTIME: case RDP_BW_RESULTS_RESPONSE_TYPE_CONTINUOUS: /* Bandwidth Measure Results (RDP_BW_RESULTS) - MS-RDPBCGR 2.2.14.2.2 */ success = autodetect_recv_bandwidth_measure_results(rdp, s, &autodetectRspPdu); break; default: break; } return success ? 0 : -1; } rdpAutoDetect* autodetect_new(void) { rdpAutoDetect* autoDetect = (rdpAutoDetect*)calloc(1, sizeof(rdpAutoDetect)); if (autoDetect) { } return autoDetect; } void autodetect_free(rdpAutoDetect* autoDetect) { free(autoDetect); } void autodetect_register_server_callbacks(rdpAutoDetect* autodetect) { autodetect->RTTMeasureRequest = autodetect_send_continuous_rtt_measure_request; autodetect->BandwidthMeasureStart = autodetect_send_continuous_bandwidth_measure_start; autodetect->BandwidthMeasureStop = autodetect_send_continuous_bandwidth_measure_stop; autodetect->NetworkCharacteristicsResult = autodetect_send_netchar_result; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3911_1
crossvul-cpp_data_bad_351_8
/* * card-iasecc.c: Support for IAS/ECC smart cards * * Copyright (C) 2010 Viktor Tarasov <vtarasov@gmail.com> * OpenTrust <www.opentrust.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef ENABLE_OPENSSL /* empty file without openssl */ #include <string.h> #include <stdlib.h> #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/sha.h> #include <openssl/rsa.h> #include <openssl/pkcs12.h> #include <openssl/x509v3.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" #include "opensc.h" /* #include "sm.h" */ #include "pkcs15.h" /* #include "hash-strings.h" */ #include "gp.h" #include "iasecc.h" #define IASECC_CARD_DEFAULT_FLAGS ( 0 \ | SC_ALGORITHM_ONBOARD_KEY_GEN \ | SC_ALGORITHM_RSA_PAD_ISO9796 \ | SC_ALGORITHM_RSA_PAD_PKCS1 \ | SC_ALGORITHM_RSA_HASH_NONE \ | SC_ALGORITHM_RSA_HASH_SHA1 \ | SC_ALGORITHM_RSA_HASH_SHA256) /* generic iso 7816 operations table */ static const struct sc_card_operations *iso_ops = NULL; /* our operations table with overrides */ static struct sc_card_operations iasecc_ops; static struct sc_card_driver iasecc_drv = { "IAS-ECC", "iasecc", &iasecc_ops, NULL, 0, NULL }; static struct sc_atr_table iasecc_known_atrs[] = { { "3B:7F:96:00:00:00:31:B8:64:40:70:14:10:73:94:01:80:82:90:00", "FF:FF:FF:FF:FF:FF:FF:FE:FF:FF:00:00:FF:FF:FF:FF:FF:FF:FF:FF", "IAS/ECC Gemalto", SC_CARD_TYPE_IASECC_GEMALTO, 0, NULL }, { "3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:08:00:07:90:00:FE", NULL, "IAS/ECC v1.0.1 Oberthur", SC_CARD_TYPE_IASECC_OBERTHUR, 0, NULL }, { "3B:7D:13:00:00:4D:44:57:2D:49:41:53:2D:43:41:52:44:32", NULL, "IAS/ECC v1.0.1 Sagem MDW-IAS-CARD2", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL }, { "3B:7F:18:00:00:00:31:B8:64:50:23:EC:C1:73:94:01:80:82:90:00", NULL, "IAS/ECC v1.0.1 Sagem ypsID S3", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL }, { "3B:DF:96:00:80:31:FE:45:00:31:B8:64:04:1F:EC:C1:73:94:01:80:82:90:00:EC", NULL, "IAS/ECC Morpho MinInt - Agent Card", SC_CARD_TYPE_IASECC_MI, 0, NULL }, { "3B:DF:18:FF:81:91:FE:1F:C3:00:31:B8:64:0C:01:EC:C1:73:94:01:80:82:90:00:B3", NULL, "IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL }, { "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:02:04:03:55:00:02:34", NULL, "IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL }, { "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:01:0B:03:52:00:05:38", NULL, "IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_aid OberthurIASECC_AID = { {0xA0,0x00,0x00,0x00,0x77,0x01,0x08,0x00,0x07,0x00,0x00,0xFE,0x00,0x00,0x01,0x00}, 16 }; static struct sc_aid MIIASECC_AID = { { 0x4D, 0x49, 0x4F, 0x4D, 0x43, 0x54}, 6 }; struct iasecc_pin_status { unsigned char sha1[SHA_DIGEST_LENGTH]; unsigned char reference; struct iasecc_pin_status *next; struct iasecc_pin_status *prev; }; struct iasecc_pin_status *checked_pins = NULL; static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out); static int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen); static int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial); static int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo); static int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data); static int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left); static int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data); static int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update); #ifdef ENABLE_SM static int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count); static int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count); #endif static int iasecc_chv_cache_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd) { struct sc_context *ctx = card->ctx; struct iasecc_pin_status *pin_status = NULL, *current = NULL; LOG_FUNC_CALLED(ctx); for(current = checked_pins; current; current = current->next) if (current->reference == pin_cmd->pin_reference) break; if (current) { sc_log(ctx, "iasecc_chv_cache_verified() current PIN-%i", current->reference); pin_status = current; } else { pin_status = calloc(1, sizeof(struct iasecc_pin_status)); if (!pin_status) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate PIN status info"); sc_log(ctx, "iasecc_chv_cache_verified() allocated %p", pin_status); } pin_status->reference = pin_cmd->pin_reference; if (pin_cmd->pin1.data) SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_status->sha1); else memset(pin_status->sha1, 0, SHA_DIGEST_LENGTH); sc_log_hex(ctx, "iasecc_chv_cache_verified() sha1(PIN)", pin_status->sha1, SHA_DIGEST_LENGTH); if (!current) { if (!checked_pins) { checked_pins = pin_status; } else { checked_pins->prev = pin_status; pin_status->next = checked_pins; checked_pins = pin_status; } } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_chv_cache_clean(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd) { struct sc_context *ctx = card->ctx; struct iasecc_pin_status *current = NULL; LOG_FUNC_CALLED(ctx); for(current = checked_pins; current; current = current->next) if (current->reference == pin_cmd->pin_reference) break; if (!current) LOG_FUNC_RETURN(ctx, SC_SUCCESS); if (current->next && current->prev) { current->prev->next = current->next; current->next->prev = current->prev; } else if (!current->prev) { checked_pins = current->next; } else if (!current->next && current->prev) { current->prev->next = NULL; } free(current); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static struct iasecc_pin_status * iasecc_chv_cache_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd) { struct sc_context *ctx = card->ctx; struct iasecc_pin_status *current = NULL; unsigned char data_sha1[SHA_DIGEST_LENGTH]; LOG_FUNC_CALLED(ctx); if (pin_cmd->pin1.data) SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, data_sha1); else memset(data_sha1, 0, SHA_DIGEST_LENGTH); sc_log_hex(ctx, "data_sha1: %s", data_sha1, SHA_DIGEST_LENGTH); for(current = checked_pins; current; current = current->next) if (current->reference == pin_cmd->pin_reference) break; if (current && !memcmp(data_sha1, current->sha1, SHA_DIGEST_LENGTH)) { sc_log(ctx, "PIN-%i status 'verified'", pin_cmd->pin_reference); return current; } sc_log(ctx, "PIN-%i status 'not verified'", pin_cmd->pin_reference); return NULL; } static int iasecc_select_mf(struct sc_card *card, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_file *mf_file = NULL; struct sc_path path; int rv; LOG_FUNC_CALLED(ctx); if (file_out) *file_out = NULL; memset(&path, 0, sizeof(struct sc_path)); if (!card->ef_atr || !card->ef_atr->aid.len) { struct sc_apdu apdu; unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE]; /* ISO 'select' command fails when not FCP data returned */ sc_format_path("3F00", &path); path.type = SC_PATH_TYPE_FILE_ID; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x00, 0x00); apdu.lc = path.len; apdu.data = path.value; apdu.datalen = path.len; apdu.resplen = sizeof(apdu_resp); apdu.resp = apdu_resp; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, rv, "Cannot select MF"); } else { memset(&path, 0, sizeof(path)); path.type = SC_PATH_TYPE_DF_NAME; memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len); path.len = card->ef_atr->aid.len; rv = iasecc_select_file(card, &path, file_out); LOG_TEST_RET(ctx, rv, "Unable to ROOT selection"); } /* Ignore the FCP of the MF, because: * - some cards do not return it; * - there is not need of it -- create/delete of the files in MF is not envisaged. */ mf_file = sc_file_new(); if (mf_file == NULL) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate MF file"); mf_file->type = SC_FILE_TYPE_DF; mf_file->path = path; if (card->cache.valid) sc_file_free(card->cache.current_df); card->cache.current_df = NULL; if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_df, mf_file); card->cache.valid = 1; if (file_out && *file_out == NULL) *file_out = mf_file; else sc_file_free(mf_file); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_select_aid(struct sc_card *card, struct sc_aid *aid, unsigned char *out, size_t *out_len) { struct sc_apdu apdu; unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE]; int rv; /* Select application (deselect previously selected application) */ sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00); apdu.lc = aid->len; apdu.data = aid->value; apdu.datalen = aid->len; apdu.resplen = sizeof(apdu_resp); apdu.resp = apdu_resp; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(card->ctx, rv, "Cannot select AID"); if (*out_len < apdu.resplen) LOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, "Cannot select AID"); memcpy(out, apdu.resp, apdu.resplen); return SC_SUCCESS; } static int iasecc_match_card(struct sc_card *card) { struct sc_context *ctx = card->ctx; int i; i = _sc_match_atr(card, iasecc_known_atrs, &card->type); if (i < 0) { sc_log(ctx, "card not matched"); return 0; } sc_log(ctx, "'%s' card matched", iasecc_known_atrs[i].name); return 1; } static int iasecc_parse_ef_atr(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *pdata = (struct iasecc_private_data *) card->drv_data; struct iasecc_version *version = &pdata->version; struct iasecc_io_buffer_sizes *sizes = &pdata->max_sizes; int rv; LOG_FUNC_CALLED(ctx); rv = sc_parse_ef_atr(card); LOG_TEST_RET(ctx, rv, "MF selection error"); if (card->ef_atr->pre_issuing_len < 4) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid pre-issuing data"); version->ic_manufacturer = card->ef_atr->pre_issuing[0]; version->ic_type = card->ef_atr->pre_issuing[1]; version->os_version = card->ef_atr->pre_issuing[2]; version->iasecc_version = card->ef_atr->pre_issuing[3]; sc_log(ctx, "EF.ATR: IC manufacturer/type %X/%X, OS/IasEcc versions %X/%X", version->ic_manufacturer, version->ic_type, version->os_version, version->iasecc_version); if (card->ef_atr->issuer_data_len < 16) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid issuer data"); sizes->send = card->ef_atr->issuer_data[2] * 0x100 + card->ef_atr->issuer_data[3]; sizes->send_sc = card->ef_atr->issuer_data[6] * 0x100 + card->ef_atr->issuer_data[7]; sizes->recv = card->ef_atr->issuer_data[10] * 0x100 + card->ef_atr->issuer_data[11]; sizes->recv_sc = card->ef_atr->issuer_data[14] * 0x100 + card->ef_atr->issuer_data[15]; card->max_send_size = sizes->send; card->max_recv_size = sizes->recv; /* Most of the card producers interpret 'send' values as "maximum APDU data size". * Oberthur strictly follows specification and interpret these values as "maximum APDU command size". * Here we need 'data size'. */ if (card->max_send_size > 0xFF) card->max_send_size -= 5; sc_log(ctx, "EF.ATR: max send/recv sizes %"SC_FORMAT_LEN_SIZE_T"X/%"SC_FORMAT_LEN_SIZE_T"X", card->max_send_size, card->max_recv_size); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init_gemalto(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct sc_path path; unsigned int flags; int rv = 0; LOG_FUNC_CALLED(ctx); flags = IASECC_CARD_DEFAULT_FLAGS; _sc_card_add_rsa_alg(card, 1024, flags, 0x10001); _sc_card_add_rsa_alg(card, 2048, flags, 0x10001); card->caps = SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; card->caps |= SC_CARD_CAP_USE_FCI_AC; sc_format_path("3F00", &path); rv = sc_select_file(card, &path, NULL); /* Result ignored*/ rv = iasecc_parse_ef_atr(card); sc_log(ctx, "rv %i", rv); if (rv == SC_ERROR_FILE_NOT_FOUND) { sc_log(ctx, "Select MF"); rv = iasecc_select_mf(card, NULL); sc_log(ctx, "rv %i", rv); LOG_TEST_RET(ctx, rv, "MF selection error"); rv = iasecc_parse_ef_atr(card); sc_log(ctx, "rv %i", rv); } sc_log(ctx, "rv %i", rv); LOG_TEST_RET(ctx, rv, "Cannot read/parse EF.ATR"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_oberthur_match(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned char *hist = card->reader->atr_info.hist_bytes; LOG_FUNC_CALLED(ctx); if (*hist != 0x80 || ((*(hist+1)&0xF0) != 0xF0)) LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND); sc_log_hex(ctx, "AID in historical_bytes", hist + 2, *(hist+1) & 0x0F); if (memcmp(hist + 2, OberthurIASECC_AID.value, *(hist+1) & 0x0F)) LOG_FUNC_RETURN(ctx, SC_ERROR_RECORD_NOT_FOUND); if (!card->ef_atr) card->ef_atr = calloc(1, sizeof(struct sc_ef_atr)); if (!card->ef_atr) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(card->ef_atr->aid.value, OberthurIASECC_AID.value, OberthurIASECC_AID.len); card->ef_atr->aid.len = OberthurIASECC_AID.len; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init_oberthur(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned int flags; int rv = 0; LOG_FUNC_CALLED(ctx); flags = IASECC_CARD_DEFAULT_FLAGS; _sc_card_add_rsa_alg(card, 1024, flags, 0x10001); _sc_card_add_rsa_alg(card, 2048, flags, 0x10001); card->caps = SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; card->caps |= SC_CARD_CAP_USE_FCI_AC; iasecc_parse_ef_atr(card); /* if we fail to select CM, */ if (gp_select_card_manager(card)) { gp_select_isd_rid(card); } rv = iasecc_oberthur_match(card); LOG_TEST_RET(ctx, rv, "unknown Oberthur's IAS/ECC card"); rv = iasecc_select_mf(card, NULL); LOG_TEST_RET(ctx, rv, "MF selection error"); rv = iasecc_parse_ef_atr(card); LOG_TEST_RET(ctx, rv, "EF.ATR read or parse error"); sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len)); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_mi_match(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned char resp[0x100]; size_t resp_len; int rv = 0; LOG_FUNC_CALLED(ctx); resp_len = sizeof(resp); rv = iasecc_select_aid(card, &MIIASECC_AID, resp, &resp_len); LOG_TEST_RET(ctx, rv, "IASECC: failed to select MI IAS/ECC applet"); if (!card->ef_atr) card->ef_atr = calloc(1, sizeof(struct sc_ef_atr)); if (!card->ef_atr) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); memcpy(card->ef_atr->aid.value, MIIASECC_AID.value, MIIASECC_AID.len); card->ef_atr->aid.len = MIIASECC_AID.len; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init_amos_or_sagem(struct sc_card *card) { struct sc_context *ctx = card->ctx; unsigned int flags; int rv = 0; LOG_FUNC_CALLED(ctx); flags = IASECC_CARD_DEFAULT_FLAGS; _sc_card_add_rsa_alg(card, 1024, flags, 0x10001); _sc_card_add_rsa_alg(card, 2048, flags, 0x10001); card->caps = SC_CARD_CAP_RNG; card->caps |= SC_CARD_CAP_APDU_EXT; card->caps |= SC_CARD_CAP_USE_FCI_AC; if (card->type == SC_CARD_TYPE_IASECC_MI) { rv = iasecc_mi_match(card); if (rv) card->type = SC_CARD_TYPE_IASECC_MI2; else LOG_FUNC_RETURN(ctx, SC_SUCCESS); } rv = iasecc_parse_ef_atr(card); if (rv == SC_ERROR_FILE_NOT_FOUND) { rv = iasecc_select_mf(card, NULL); LOG_TEST_RET(ctx, rv, "MF selection error"); rv = iasecc_parse_ef_atr(card); } LOG_TEST_RET(ctx, rv, "IASECC: ATR parse failed"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_init(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *private_data = NULL; int rv = SC_ERROR_NO_CARD_SUPPORT; LOG_FUNC_CALLED(ctx); private_data = (struct iasecc_private_data *) calloc(1, sizeof(struct iasecc_private_data)); if (private_data == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); card->cla = 0x00; card->drv_data = private_data; if (card->type == SC_CARD_TYPE_IASECC_GEMALTO) rv = iasecc_init_gemalto(card); else if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) rv = iasecc_init_oberthur(card); else if (card->type == SC_CARD_TYPE_IASECC_SAGEM) rv = iasecc_init_amos_or_sagem(card); else if (card->type == SC_CARD_TYPE_IASECC_AMOS) rv = iasecc_init_amos_or_sagem(card); else if (card->type == SC_CARD_TYPE_IASECC_MI) rv = iasecc_init_amos_or_sagem(card); else LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD); if (!rv) { if (card->ef_atr && card->ef_atr->aid.len) { struct sc_path path; memset(&path, 0, sizeof(struct sc_path)); path.type = SC_PATH_TYPE_DF_NAME; memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len); path.len = card->ef_atr->aid.len; rv = iasecc_select_file(card, &path, NULL); sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv); LOG_TEST_RET(ctx, rv, "Select EF.ATR AID failed"); } rv = iasecc_get_serialnr(card, NULL); } #ifdef ENABLE_SM card->sm_ctx.ops.read_binary = _iasecc_sm_read_binary; card->sm_ctx.ops.update_binary = _iasecc_sm_update_binary; #endif if (!rv) { sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len)); rv = SC_ERROR_INVALID_CARD; } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_read_binary(card:%p) offs %i; count %"SC_FORMAT_LEN_SIZE_T"u", card, offs, count); if (offs > 0x7fff) { sc_log(ctx, "invalid EF offset: 0x%X > 0x7FFF", offs); return SC_ERROR_OFFSET_TOO_LARGE; } sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (offs >> 8) & 0x7F, offs & 0xFF); apdu.le = count < 0x100 ? count : 0x100; apdu.resplen = count; apdu.resp = buf; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "iasecc_read_binary() failed"); sc_log(ctx, "iasecc_read_binary() apdu.resplen %"SC_FORMAT_LEN_SIZE_T"u", apdu.resplen); if (apdu.resplen == IASECC_READ_BINARY_LENGTH_MAX && apdu.resplen < count) { rv = iasecc_read_binary(card, offs + apdu.resplen, buf + apdu.resplen, count - apdu.resplen, flags); if (rv != SC_ERROR_WRONG_LENGTH) { LOG_TEST_RET(ctx, rv, "iasecc_read_binary() read tail failed"); apdu.resplen += rv; } } LOG_FUNC_RETURN(ctx, apdu.resplen); } static int iasecc_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags) { struct sc_context *ctx = card->ctx; unsigned char *tmp = NULL; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_erase_binary(card:%p) count %"SC_FORMAT_LEN_SIZE_T"u", card, count); if (!count) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "'ERASE BINARY' failed: invalid size to erase"); tmp = malloc(count); if (!tmp) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate temporary buffer"); memset(tmp, 0xFF, count); rv = sc_update_binary(card, offs, tmp, count, flags); free(tmp); LOG_TEST_RET(ctx, rv, "iasecc_erase_binary() update binary error"); LOG_FUNC_RETURN(ctx, rv); } #if ENABLE_SM static int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buff, size_t count) { struct sc_context *ctx = card->ctx; const struct sc_acl_entry *entry = NULL; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ", card, offs, count); if (offs > 0x7fff) LOG_TEST_RET(ctx, SC_ERROR_OFFSET_TOO_LARGE, "Invalid arguments"); if (count == 0) return 0; sc_print_cache(card); if (card->cache.valid && card->cache.current_ef) { entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_READ); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_read() 'READ' ACL not present"); sc_log(ctx, "READ method/reference %X/%X", entry->method, entry->key_ref); if ((entry->method == SC_AC_SCB) && (entry->key_ref & IASECC_SCB_METHOD_SM)) { unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0; rv = iasecc_sm_read_binary(card, se_num, offs, buff, count); LOG_FUNC_RETURN(ctx, rv); } } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count) { struct sc_context *ctx = card->ctx; const struct sc_acl_entry *entry = NULL; int rv; if (count == 0) return SC_SUCCESS; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ", card, offs, count); sc_print_cache(card); if (card->cache.valid && card->cache.current_ef) { entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_UPDATE); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_update() 'UPDATE' ACL not present"); sc_log(ctx, "UPDATE method/reference %X/%X", entry->method, entry->key_ref); if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) { unsigned char se_num = entry->method == SC_AC_SCB ? entry->key_ref & IASECC_SCB_METHOD_MASK_REF : 0; rv = iasecc_sm_update_binary(card, se_num, offs, buff, count); LOG_FUNC_RETURN(ctx, rv); } } LOG_FUNC_RETURN(ctx, 0); } #endif static int iasecc_emulate_fcp(struct sc_context *ctx, struct sc_apdu *apdu) { unsigned char dummy_df_fcp[] = { 0x62,0xFF, 0x82,0x01,0x38, 0x8A,0x01,0x05, 0xA1,0x04,0x8C,0x02,0x02,0x00, 0x84,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF }; LOG_FUNC_CALLED(ctx); if (apdu->p1 != 0x04) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "FCP emulation supported only for the DF-NAME selection type"); if (apdu->datalen > 16) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid DF-NAME length"); if (apdu->resplen < apdu->datalen + 16) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "not enough space for FCP data"); memcpy(dummy_df_fcp + 16, apdu->data, apdu->datalen); dummy_df_fcp[15] = apdu->datalen; dummy_df_fcp[1] = apdu->datalen + 14; memcpy(apdu->resp, dummy_df_fcp, apdu->datalen + 16); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } /* TODO: redesign using of cache * TODO: do not keep intermediate results in 'file_out' argument */ static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_path lpath; int cache_valid = card->cache.valid, df_from_cache = 0; int rv, ii; LOG_FUNC_CALLED(ctx); memcpy(&lpath, path, sizeof(struct sc_path)); if (file_out) *file_out = NULL; sc_log(ctx, "iasecc_select_file(card:%p) path.len %"SC_FORMAT_LEN_SIZE_T"u; path.type %i; aid_len %"SC_FORMAT_LEN_SIZE_T"u", card, path->len, path->type, path->aid.len); sc_log(ctx, "iasecc_select_file() path:%s", sc_print_path(path)); sc_print_cache(card); if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) { sc_log(ctx, "EF.ATR(aid:'%s')", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : ""); rv = iasecc_select_mf(card, file_out); LOG_TEST_RET(ctx, rv, "MF selection error"); if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) { memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2); lpath.len -= 2; } } if (lpath.aid.len) { struct sc_file *file = NULL; struct sc_path ppath; sc_log(ctx, "iasecc_select_file() select parent AID:%p/%"SC_FORMAT_LEN_SIZE_T"u", lpath.aid.value, lpath.aid.len); sc_log(ctx, "iasecc_select_file() select parent AID:%s", sc_dump_hex(lpath.aid.value, lpath.aid.len)); memset(&ppath, 0, sizeof(ppath)); memcpy(ppath.value, lpath.aid.value, lpath.aid.len); ppath.len = lpath.aid.len; ppath.type = SC_PATH_TYPE_DF_NAME; if (card->cache.valid && card->cache.current_df && card->cache.current_df->path.len == lpath.aid.len && !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len)) df_from_cache = 1; rv = iasecc_select_file(card, &ppath, &file); LOG_TEST_RET(ctx, rv, "select AID path failed"); if (file_out) *file_out = file; else sc_file_free(file); if (lpath.type == SC_PATH_TYPE_DF_NAME) lpath.type = SC_PATH_TYPE_FROM_CURRENT; } if (lpath.type == SC_PATH_TYPE_PATH) lpath.type = SC_PATH_TYPE_FROM_CURRENT; if (!lpath.len) LOG_FUNC_RETURN(ctx, SC_SUCCESS); sc_print_cache(card); if (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME && card->cache.current_df->path.len == lpath.len && !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) { sc_log(ctx, "returns current DF path %s", sc_print_path(&card->cache.current_df->path)); if (file_out) { sc_file_free(*file_out); sc_file_dup(file_out, card->cache.current_df); } sc_print_cache(card); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } do { struct sc_apdu apdu; struct sc_file *file = NULL; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int pathlen = lpath.len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00); if (card->type != SC_CARD_TYPE_IASECC_GEMALTO && card->type != SC_CARD_TYPE_IASECC_OBERTHUR && card->type != SC_CARD_TYPE_IASECC_SAGEM && card->type != SC_CARD_TYPE_IASECC_AMOS && card->type != SC_CARD_TYPE_IASECC_MI && card->type != SC_CARD_TYPE_IASECC_MI2) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card"); if (lpath.type == SC_PATH_TYPE_FILE_ID) { apdu.p1 = 0x02; if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) { apdu.p1 = 0x01; apdu.p2 = 0x04; } if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) { apdu.p1 = 0x09; if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else if (lpath.type == SC_PATH_TYPE_PARENT) { apdu.p1 = 0x03; pathlen = 0; apdu.cse = SC_APDU_CASE_2_SHORT; } else if (lpath.type == SC_PATH_TYPE_DF_NAME) { apdu.p1 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_AMOS) apdu.p2 = 0x04; if (card->type == SC_CARD_TYPE_IASECC_MI2) apdu.p2 = 0x04; } else { sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type); LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "iasecc_select_file() invalid PATH type"); } for (ii=0; ii<2; ii++) { apdu.lc = pathlen; apdu.data = lpath.value; apdu.datalen = pathlen; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); if (rv == SC_ERROR_INCORRECT_PARAMETERS && lpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) { apdu.p2 = 0x0C; continue; } if (ii) { /* 'SELECT AID' do not returned FCP. Try to emulate. */ apdu.resplen = sizeof(rbuf); rv = iasecc_emulate_fcp(ctx, &apdu); LOG_TEST_RET(ctx, rv, "Failed to emulate DF FCP"); } break; } /* * Using of the cached DF and EF can cause problems in the multi-thread environment. * FIXME: introduce config. option that invalidates this cache outside the locked card session, * (or invent something else) */ if (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) { sc_invalidate_cache(card); sc_log(ctx, "iasecc_select_file() file not found, retry without cached DF"); if (file_out) { sc_file_free(*file_out); *file_out = NULL; } rv = iasecc_select_file(card, path, file_out); LOG_FUNC_RETURN(ctx, rv); } LOG_TEST_RET(ctx, rv, "iasecc_select_file() check SW failed"); sc_log(ctx, "iasecc_select_file() apdu.resp %"SC_FORMAT_LEN_SIZE_T"u", apdu.resplen); if (apdu.resplen) { sc_log(ctx, "apdu.resp %02X:%02X:%02X...", apdu.resp[0], apdu.resp[1], apdu.resp[2]); switch (apdu.resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); file->path = lpath; rv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen); if (rv) LOG_FUNC_RETURN(ctx, rv); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } sc_log(ctx, "FileType %i", file->type); if (file->type == SC_FILE_TYPE_DF) { if (card->cache.valid) sc_file_free(card->cache.current_df); card->cache.current_df = NULL; if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_df, file); card->cache.valid = 1; } else { if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) { sc_file_free(*file_out); *file_out = file; } else { sc_file_free(file); } } else if (lpath.type == SC_PATH_TYPE_DF_NAME) { sc_file_free(card->cache.current_df); card->cache.current_df = NULL; sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } } while(0); sc_print_cache(card); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen) { struct sc_context *ctx = card->ctx; size_t taglen; int rv, ii, offs; const unsigned char *acls = NULL, *tag = NULL; unsigned char mask; unsigned char ops_DF[7] = { SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_CREATE, 0xFF }; unsigned char ops_EF[7] = { SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ }; LOG_FUNC_CALLED(ctx); tag = sc_asn1_find_tag(ctx, buf, buflen, 0x6F, &taglen); sc_log(ctx, "processing FCI: 0x6F tag %p", tag); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } tag = sc_asn1_find_tag(ctx, buf, buflen, 0x62, &taglen); sc_log(ctx, "processing FCI: 0x62 tag %p", tag); if (tag != NULL) { sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen); buf = tag; buflen = taglen; } rv = iso_ops->process_fci(card, file, buf, buflen); LOG_TEST_RET(ctx, rv, "ISO parse FCI failed"); /* Gemalto: 6F 19 80 02 02 ED 82 01 01 83 02 B0 01 88 00 8C 07 7B 17 17 17 17 17 00 8A 01 05 90 00 Sagem: 6F 17 62 15 80 02 00 7D 82 01 01 8C 02 01 00 83 02 2F 00 88 01 F0 8A 01 05 90 00 Oberthur: 62 1B 80 02 05 DC 82 01 01 83 02 B0 01 88 00 A1 09 8C 07 7B 17 FF 17 17 17 00 8A 01 05 90 00 */ sc_log(ctx, "iasecc_process_fci() type %i; let's parse file ACLs", file->type); tag = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS, &taglen); if (tag) acls = sc_asn1_find_tag(ctx, tag, taglen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen); else acls = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen); if (!acls) { sc_log(ctx, "ACLs not found in data(%"SC_FORMAT_LEN_SIZE_T"u) %s", buflen, sc_dump_hex(buf, buflen)); LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing"); } sc_log(ctx, "ACLs(%"SC_FORMAT_LEN_SIZE_T"u) '%s'", taglen, sc_dump_hex(acls, taglen)); mask = 0x40, offs = 1; for (ii = 0; ii < 7; ii++, mask /= 2) { unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii]; if (!(mask & acls[0])) continue; sc_log(ctx, "ACLs mask 0x%X, offs %i, op 0x%X, acls[offs] 0x%X", mask, offs, op, acls[offs]); if (op == 0xFF) { ; } else if (acls[offs] == 0) { sc_file_add_acl_entry(file, op, SC_AC_NONE, 0); } else if (acls[offs] == 0xFF) { sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } else if ((acls[offs] & IASECC_SCB_METHOD_MASK) == IASECC_SCB_METHOD_USER_AUTH) { sc_file_add_acl_entry(file, op, SC_AC_SEN, acls[offs] & IASECC_SCB_METHOD_MASK_REF); } else if (acls[offs] & IASECC_SCB_METHOD_MASK) { sc_file_add_acl_entry(file, op, SC_AC_SCB, acls[offs]); } else { sc_log(ctx, "Warning: non supported SCB method: %X", acls[offs]); sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0); } offs++; } LOG_FUNC_RETURN(ctx, 0); } static int iasecc_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; unsigned char buf[0x80], type; unsigned char ops[7] = { SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ }; unsigned char smbs[8]; size_t ii, offs = 0, amb, mask, nn_smb; LOG_FUNC_CALLED(ctx); if (file->type == SC_FILE_TYPE_DF) type = IASECC_FCP_TYPE_DF; else type = IASECC_FCP_TYPE_EF; buf[offs++] = IASECC_FCP_TAG_SIZE; buf[offs++] = 2; buf[offs++] = (file->size >> 8) & 0xFF; buf[offs++] = file->size & 0xFF; buf[offs++] = IASECC_FCP_TAG_TYPE; buf[offs++] = 1; buf[offs++] = type; buf[offs++] = IASECC_FCP_TAG_FID; buf[offs++] = 2; buf[offs++] = (file->id >> 8) & 0xFF; buf[offs++] = file->id & 0xFF; buf[offs++] = IASECC_FCP_TAG_SFID; buf[offs++] = 0; amb = 0, mask = 0x40, nn_smb = 0; for (ii = 0; ii < sizeof(ops); ii++, mask >>= 1) { const struct sc_acl_entry *entry; if (ops[ii]==0xFF) continue; entry = sc_file_get_acl_entry(file, ops[ii]); if (!entry) continue; sc_log(ctx, "method %X; reference %X", entry->method, entry->key_ref); if (entry->method == SC_AC_NEVER) continue; else if (entry->method == SC_AC_NONE) smbs[nn_smb++] = 0x00; else if (entry->method == SC_AC_CHV) smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH; else if (entry->method == SC_AC_SEN) smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH; else if (entry->method == SC_AC_SCB) smbs[nn_smb++] = entry->key_ref; else if (entry->method == SC_AC_PRO) smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_SM; else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported AC method"); amb |= mask; sc_log(ctx, "%"SC_FORMAT_LEN_SIZE_T"u: AMB %"SC_FORMAT_LEN_SIZE_T"X; nn_smb %"SC_FORMAT_LEN_SIZE_T"u", ii, amb, nn_smb); } /* TODO: Encode contactless ACLs and life cycle status for all IAS/ECC cards */ if (card->type == SC_CARD_TYPE_IASECC_SAGEM || card->type == SC_CARD_TYPE_IASECC_AMOS ) { unsigned char status = 0; buf[offs++] = IASECC_FCP_TAG_ACLS; buf[offs++] = 2*(2 + 1 + nn_smb); buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT; buf[offs++] = nn_smb + 1; buf[offs++] = amb; memcpy(buf + offs, smbs, nn_smb); offs += nn_smb; /* Same ACLs for contactless */ buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACTLESS; buf[offs++] = nn_smb + 1; buf[offs++] = amb; memcpy(buf + offs, smbs, nn_smb); offs += nn_smb; if (file->status == SC_FILE_STATUS_ACTIVATED) status = 0x05; else if (file->status == SC_FILE_STATUS_CREATION) status = 0x01; if (status) { buf[offs++] = 0x8A; buf[offs++] = 0x01; buf[offs++] = status; } } else { buf[offs++] = IASECC_FCP_TAG_ACLS; buf[offs++] = 2 + 1 + nn_smb; buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT; buf[offs++] = nn_smb + 1; buf[offs++] = amb; memcpy(buf + offs, smbs, nn_smb); offs += nn_smb; } if (out) { if (out_len < offs) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to encode FCP"); memcpy(out, buf, offs); } LOG_FUNC_RETURN(ctx, offs); } static int iasecc_create_file(struct sc_card *card, struct sc_file *file) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; const struct sc_acl_entry *entry = NULL; unsigned char sbuf[0x100]; size_t sbuf_len; int rv; LOG_FUNC_CALLED(ctx); sc_print_cache(card); if (file->type != SC_FILE_TYPE_WORKING_EF) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Creation of the file with of this type is not supported"); sbuf_len = iasecc_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2); LOG_TEST_RET(ctx, sbuf_len, "FCP encode error"); sbuf[0] = IASECC_FCP_TAG; sbuf[1] = sbuf_len; if (card->cache.valid && card->cache.current_df) { entry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_create_file() 'CREATE' ACL not present"); sc_log(ctx, "iasecc_create_file() 'CREATE' method/reference %X/%X", entry->method, entry->key_ref); sc_log(ctx, "iasecc_create_file() create data: '%s'", sc_dump_hex(sbuf, sbuf_len + 2)); if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) { rv = iasecc_sm_create_file(card, entry->key_ref & IASECC_SCB_METHOD_MASK_REF, sbuf, sbuf_len + 2); LOG_TEST_RET(ctx, rv, "iasecc_create_file() SM create file error"); rv = iasecc_select_file(card, &file->path, NULL); LOG_FUNC_RETURN(ctx, rv); } } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0); apdu.data = sbuf; apdu.datalen = sbuf_len + 2; apdu.lc = sbuf_len + 2; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "iasecc_create_file() create file error"); rv = iasecc_select_file(card, &file->path, NULL); LOG_TEST_RET(ctx, rv, "Cannot select newly created file"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_logout(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct sc_path path; int rv; LOG_FUNC_CALLED(ctx); if (!card->ef_atr || !card->ef_atr->aid.len) return SC_SUCCESS; memset(&path, 0, sizeof(struct sc_path)); path.type = SC_PATH_TYPE_DF_NAME; memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len); path.len = card->ef_atr->aid.len; rv = iasecc_select_file(card, &path, NULL); sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_finish(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *private_data = (struct iasecc_private_data *)card->drv_data; struct iasecc_se_info *se_info = private_data->se_info, *next; LOG_FUNC_CALLED(ctx); while (se_info) { sc_file_free(se_info->df); next = se_info->next; free(se_info); se_info = next; } free(card->drv_data); card->drv_data = NULL; LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_delete_file(struct sc_card *card, const struct sc_path *path) { struct sc_context *ctx = card->ctx; const struct sc_acl_entry *entry = NULL; struct sc_apdu apdu; struct sc_file *file = NULL; int rv; LOG_FUNC_CALLED(ctx); sc_print_cache(card); rv = iasecc_select_file(card, path, &file); if (rv == SC_ERROR_FILE_NOT_FOUND) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_TEST_RET(ctx, rv, "Cannot select file to delete"); entry = sc_file_get_acl_entry(file, SC_AC_OP_DELETE); if (!entry) LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Cannot delete file: no 'DELETE' acl"); sc_log(ctx, "DELETE method/reference %X/%X", entry->method, entry->key_ref); if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) { unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0; rv = iasecc_sm_delete_file(card, se_num, file->id); } else { sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xE4, 0x00, 0x00); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Delete file failed"); if (card->cache.valid) sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; } sc_file_free(file); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2) { if (sw1 == 0x62 && sw2 == 0x82) return SC_SUCCESS; return iso_ops->check_sw(card, sw1, sw2); } static unsigned iasecc_get_algorithm(struct sc_context *ctx, const struct sc_security_env *env, unsigned operation, unsigned mechanism) { const struct sc_supported_algo_info *info = NULL; int ii; if (!env) return 0; for (ii=0;ii<SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference; ii++) if ((env->supported_algos[ii].operations & operation) && (env->supported_algos[ii].mechanism == mechanism)) break; if (ii < SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference) { info = &env->supported_algos[ii]; sc_log(ctx, "found IAS/ECC algorithm %X:%X:%X:%X", info->reference, info->mechanism, info->operations, info->algo_ref); } else { sc_log(ctx, "cannot find IAS/ECC algorithm (operation:%X,mechanism:%X)", operation, mechanism); } return info ? info->algo_ref : 0; } static int iasecc_se_cache_info(struct sc_card *card, struct iasecc_se_info *se) { struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_context *ctx = card->ctx; struct iasecc_se_info *se_info = NULL, *si = NULL; int rv; LOG_FUNC_CALLED(ctx); se_info = calloc(1, sizeof(struct iasecc_se_info)); if (!se_info) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "SE info allocation error"); memcpy(se_info, se, sizeof(struct iasecc_se_info)); if (card->cache.valid && card->cache.current_df) { sc_file_dup(&se_info->df, card->cache.current_df); if (se_info->df == NULL) { free(se_info); LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file"); } } rv = iasecc_docp_copy(ctx, &se->docp, &se_info->docp); if (rv < 0) { free(se_info->df); free(se_info); LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP"); } if (!prv->se_info) { prv->se_info = se_info; } else { for (si = prv->se_info; si->next; si = si->next) ; si->next = se_info; } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_se_get_info_from_cache(struct sc_card *card, struct iasecc_se_info *se) { struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_context *ctx = card->ctx; struct iasecc_se_info *si = NULL; int rv; LOG_FUNC_CALLED(ctx); for(si = prv->se_info; si; si = si->next) { if (si->reference != se->reference) continue; if (!(card->cache.valid && card->cache.current_df) && si->df) continue; if (card->cache.valid && card->cache.current_df && !si->df) continue; if (card->cache.valid && card->cache.current_df && si->df) if (memcmp(&card->cache.current_df->path, &si->df->path, sizeof(struct sc_path))) continue; break; } if (!si) return SC_ERROR_OBJECT_NOT_FOUND; memcpy(se, si, sizeof(struct iasecc_se_info)); if (si->df) { sc_file_dup(&se->df, si->df); if (se->df == NULL) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file"); } rv = iasecc_docp_copy(ctx, &si->docp, &se->docp); LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP"); LOG_FUNC_RETURN(ctx, rv); } int iasecc_se_get_info(struct sc_card *card, struct iasecc_se_info *se) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char rbuf[0x100]; unsigned char sbuf_iasecc[10] = { 0x4D, 0x08, IASECC_SDO_TEMPLATE_TAG, 0x06, IASECC_SDO_TAG_HEADER, IASECC_SDO_CLASS_SE | IASECC_OBJECT_REF_LOCAL, se->reference & 0x3F, 0x02, IASECC_SDO_CLASS_SE, 0x80 }; int rv; LOG_FUNC_CALLED(ctx); if (se->reference > IASECC_SE_REF_MAX) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); rv = iasecc_se_get_info_from_cache(card, se); if (rv == SC_ERROR_OBJECT_NOT_FOUND) { sc_log(ctx, "No SE#%X info in cache, try to use 'GET DATA'", se->reference); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF); apdu.data = sbuf_iasecc; apdu.datalen = sizeof(sbuf_iasecc); apdu.lc = apdu.datalen; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "get SE data error"); rv = iasecc_se_parse(card, apdu.resp, apdu.resplen, se); LOG_TEST_RET(ctx, rv, "cannot parse SE data"); rv = iasecc_se_cache_info(card, se); LOG_TEST_RET(ctx, rv, "failed to put SE data into cache"); } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_set_security_env(struct sc_card *card, const struct sc_security_env *env, int se_num) { struct sc_context *ctx = card->ctx; struct iasecc_sdo sdo; struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; unsigned algo_ref; struct sc_apdu apdu; unsigned sign_meth, sign_ref, auth_meth, auth_ref, aflags; unsigned char cse_crt_at[] = { 0x84, 0x01, 0xFF, 0x80, 0x01, IASECC_ALGORITHM_RSA_PKCS }; unsigned char cse_crt_dst[] = { 0x84, 0x01, 0xFF, 0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1) }; unsigned char cse_crt_ht[] = { 0x80, 0x01, IASECC_ALGORITHM_SHA1 }; unsigned char cse_crt_ct[] = { 0x84, 0x01, 0xFF, 0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1) }; int rv, operation = env->operation; /* TODO: take algorithm references from 5032, not from header file. */ LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_set_security_env(card:%p) operation 0x%X; senv.algorithm 0x%X, senv.algorithm_ref 0x%X", card, env->operation, env->algorithm, env->algorithm_ref); memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_RSA_PRIVATE; sdo.sdo_ref = env->key_ref[0] & ~IASECC_OBJECT_REF_LOCAL; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "Cannot get RSA PRIVATE SDO data"); /* To made by iasecc_sdo_convert_to_file() */ prv->key_size = *(sdo.docp.size.value + 0) * 0x100 + *(sdo.docp.size.value + 1); sc_log(ctx, "prv->key_size 0x%"SC_FORMAT_LEN_SIZE_T"X", prv->key_size); rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_COMPUTE_SIGNATURE, &sign_meth, &sign_ref); LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_SIGN acl"); rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_INTERNAL_AUTHENTICATE, &auth_meth, &auth_ref); LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_INT_AUTH acl"); aflags = env->algorithm_flags; if (!(aflags & SC_ALGORITHM_RSA_PAD_PKCS1)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Only supported signature with PKCS1 padding"); if (operation == SC_SEC_OPERATION_SIGN) { if (!(aflags & (SC_ALGORITHM_RSA_HASH_SHA1 | SC_ALGORITHM_RSA_HASH_SHA256))) { sc_log(ctx, "CKM_RSA_PKCS asked -- use 'AUTHENTICATE' sign operation instead of 'SIGN'"); operation = SC_SEC_OPERATION_AUTHENTICATE; } else if (sign_meth == SC_AC_NEVER) { LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PSO_DST not allowed for this key"); } } if (operation == SC_SEC_OPERATION_SIGN) { prv->op_method = sign_meth; prv->op_ref = sign_ref; } else if (operation == SC_SEC_OPERATION_AUTHENTICATE) { if (auth_meth == SC_AC_NEVER) LOG_TEST_RET(ctx, SC_ERROR_NOT_ALLOWED, "INTERNAL_AUTHENTICATE is not allowed for this key"); prv->op_method = auth_meth; prv->op_ref = auth_ref; } sc_log(ctx, "senv.algorithm 0x%X, senv.algorithm_ref 0x%X", env->algorithm, env->algorithm_ref); sc_log(ctx, "se_num %i, operation 0x%X, algorithm 0x%X, algorithm_ref 0x%X, flags 0x%X; key size %"SC_FORMAT_LEN_SIZE_T"u", se_num, operation, env->algorithm, env->algorithm_ref, env->algorithm_flags, prv->key_size); switch (operation) { case SC_SEC_OPERATION_SIGN: if (!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_PKCS1 specified"); if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) { algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA256); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA256"); cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA2 */ algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA256_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS"); cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA2 */ } else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) { algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA_1); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA1"); cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA1 */ algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA1_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS"); cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1 */ } else { LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA[1,256] specified"); } sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_HT); apdu.data = cse_crt_ht; apdu.datalen = sizeof(cse_crt_ht); apdu.lc = sizeof(cse_crt_ht); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "MSE restore error"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_DST); apdu.data = cse_crt_dst; apdu.datalen = sizeof(cse_crt_dst); apdu.lc = sizeof(cse_crt_dst); break; case SC_SEC_OPERATION_AUTHENTICATE: algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports SIGNATURE:RSA_PKCS"); cse_crt_at[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_at[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_AT); apdu.data = cse_crt_at; apdu.datalen = sizeof(cse_crt_at); apdu.lc = sizeof(cse_crt_at); break; case SC_SEC_OPERATION_DECIPHER: rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_DECRYPT, &prv->op_method, &prv->op_ref); LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_PSO_DECRYPT acl"); algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_DECIPHER, CKM_RSA_PKCS); if (!algo_ref) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports DECIPHER:RSA_PKCS"); cse_crt_ct[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL; cse_crt_ct[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1 */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_CT); apdu.data = cse_crt_ct; apdu.datalen = sizeof(cse_crt_ct); apdu.lc = sizeof(cse_crt_ct); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "MSE restore error"); prv->security_env = *env; prv->security_env.operation = operation; LOG_FUNC_RETURN(ctx, 0); } static int iasecc_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left) { struct sc_context *ctx = card->ctx; unsigned char buffer[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "CHV PINPAD PIN reference %i", pin_cmd->pin_reference); rv = iasecc_pin_is_verified(card, pin_cmd, tries_left); if (!rv) LOG_FUNC_RETURN(ctx, rv); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } /* When PIN stored length available * P10 verify data contains full template of 'VERIFY PIN' APDU. * Without PIN stored length * pin-pad has to set the Lc and fill PIN data itself. * Not all pin-pads support this case */ pin_cmd->pin1.len = pin_cmd->pin1.stored_length; pin_cmd->pin1.length_offset = 5; memset(buffer, 0xFF, sizeof(buffer)); pin_cmd->pin1.data = buffer; pin_cmd->cmd = SC_PIN_CMD_VERIFY; pin_cmd->flags |= SC_PIN_CMD_USE_PINPAD; /* if (card->reader && card->reader->ops && card->reader->ops->load_message) { rv = card->reader->ops->load_message(card->reader, card->slot, 0, "Here we are!"); sc_log(ctx, "Load message returned %i", rv); } */ rv = iso_ops->pin_cmd(card, pin_cmd, tries_left); sc_log(ctx, "rv %i", rv); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_acl_entry acl = pin_cmd->pin1.acls[IASECC_ACLS_CHV_VERIFY]; struct sc_apdu apdu; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Verify CHV PIN(ref:%i,len:%i,acl:%X:%X)", pin_cmd->pin_reference, pin_cmd->pin1.len, acl.method, acl.key_ref); if (acl.method & IASECC_SCB_METHOD_SM) { rv = iasecc_sm_pin_verify(card, acl.key_ref, pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } if (pin_cmd->pin1.data && !pin_cmd->pin1.len) { sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference); } else if (pin_cmd->pin1.data && pin_cmd->pin1.len) { sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference); apdu.data = pin_cmd->pin1.data; apdu.datalen = pin_cmd->pin1.len; apdu.lc = pin_cmd->pin1.len; } else if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin_cmd->pin1.data && !pin_cmd->pin1.len) { rv = iasecc_chv_verify_pinpad(card, pin_cmd, tries_left); sc_log(ctx, "Result of verifying CHV with PIN pad %i", rv); LOG_FUNC_RETURN(ctx, rv); } else { LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); if (tries_left && apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0) *tries_left = apdu.sw2 & 0x0F; rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_se_at_to_chv_reference(struct sc_card *card, unsigned reference, unsigned *chv_reference) { struct sc_context *ctx = card->ctx; struct iasecc_se_info se; struct sc_crt crt; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "SE reference %i", reference); if (reference > IASECC_SE_REF_MAX) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); memset(&se, 0, sizeof(se)); se.reference = reference; rv = iasecc_se_get_info(card, &se); LOG_TEST_RET(ctx, rv, "SDO get data error"); memset(&crt, 0, sizeof(crt)); crt.tag = IASECC_CRT_TAG_AT; crt.usage = IASECC_UQB_AT_USER_PASSWORD; rv = iasecc_se_get_crt(card, &se, &crt); LOG_TEST_RET(ctx, rv, "no authentication template for USER PASSWORD"); if (chv_reference) *chv_reference = crt.refs[0]; sc_file_free(se.df); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; struct sc_acl_entry acl = pin_cmd_data->pin1.acls[IASECC_ACLS_CHV_VERIFY]; int rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; LOG_FUNC_CALLED(ctx); if (pin_cmd_data->pin_type != SC_AC_CHV) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN type is not supported for the verification"); sc_log(ctx, "Verify ACL(method:%X;ref:%X)", acl.method, acl.key_ref); if (acl.method != IASECC_SCB_ALWAYS) LOG_FUNC_RETURN(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED); pin_cmd = *pin_cmd_data; pin_cmd.pin1.data = (unsigned char *)""; pin_cmd.pin1.len = 0; rv = iasecc_chv_verify(card, &pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_verify(struct sc_card *card, unsigned type, unsigned reference, const unsigned char *data, size_t data_len, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned chv_ref = reference; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Verify PIN(type:%X,ref:%i,data(len:%"SC_FORMAT_LEN_SIZE_T"u,%p)", type, reference, data_len, data); if (type == SC_AC_AUT) { rv = iasecc_sm_external_authentication(card, reference, tries_left); LOG_FUNC_RETURN(ctx, rv); } else if (type == SC_AC_SCB) { if (reference & IASECC_SCB_METHOD_USER_AUTH) { type = SC_AC_SEN; reference = reference & IASECC_SCB_METHOD_MASK_REF; } else { sc_log(ctx, "Do not try to verify non CHV PINs"); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } } if (type == SC_AC_SEN) { rv = iasecc_se_at_to_chv_reference(card, reference, &chv_ref); LOG_TEST_RET(ctx, rv, "SE AT to CHV reference error"); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = chv_ref; pin_cmd.cmd = SC_PIN_CMD_VERIFY; rv = iasecc_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); pin_cmd.pin1.data = data; pin_cmd.pin1.len = data_len; rv = iasecc_pin_is_verified(card, &pin_cmd, tries_left); if (data && !data_len) LOG_FUNC_RETURN(ctx, rv); if (!rv) { if (iasecc_chv_cache_is_verified(card, &pin_cmd)) LOG_FUNC_RETURN(ctx, SC_SUCCESS); } else if (rv != SC_ERROR_PIN_CODE_INCORRECT && rv != SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) { LOG_FUNC_RETURN(ctx, rv); } iasecc_chv_cache_clean(card, &pin_cmd); rv = iasecc_chv_verify(card, &pin_cmd, tries_left); LOG_TEST_RET(ctx, rv, "PIN CHV verification error"); rv = iasecc_chv_cache_verified(card, &pin_cmd); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_chv_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned char pin1_data[0x100], pin2_data[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "CHV PINPAD PIN reference %i", reference); memset(pin1_data, 0xFF, sizeof(pin1_data)); memset(pin2_data, 0xFF, sizeof(pin2_data)); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = reference; pin_cmd.cmd = SC_PIN_CMD_CHANGE; pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD; rv = iasecc_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); /* Some pin-pads do not support mode with Lc=0. * Give them a chance to work with some cards. */ if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length)) pin_cmd.pin1.len = pin_cmd.pin1.stored_length; else pin_cmd.pin1.len = 0; pin_cmd.pin1.length_offset = 5; pin_cmd.pin1.data = pin1_data; memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1)); pin_cmd.pin2.data = pin2_data; sc_log(ctx, "PIN1 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length, pin_cmd.pin1.stored_length); sc_log(ctx, "PIN2 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length, pin_cmd.pin2.stored_length); rv = iso_ops->pin_cmd(card, &pin_cmd, tries_left); LOG_FUNC_RETURN(ctx, rv); } #if 0 static int iasecc_chv_set_pinpad(struct sc_card *card, unsigned char reference) { struct sc_context *ctx = card->ctx; struct sc_pin_cmd_data pin_cmd; unsigned char pin_data[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Set CHV PINPAD PIN reference %i", reference); memset(pin_data, 0xFF, sizeof(pin_data)); if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) { sc_log(ctx, "Reader not ready for PIN PAD"); LOG_FUNC_RETURN(ctx, SC_ERROR_READER); } memset(&pin_cmd, 0, sizeof(pin_cmd)); pin_cmd.pin_type = SC_AC_CHV; pin_cmd.pin_reference = reference; pin_cmd.cmd = SC_PIN_CMD_UNBLOCK; pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD; rv = iasecc_pin_get_policy(card, &pin_cmd); LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error"); if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length)) pin_cmd.pin1.len = pin_cmd.pin1.stored_length; else pin_cmd.pin1.len = 0; pin_cmd.pin1.length_offset = 5; pin_cmd.pin1.data = pin_data; memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1)); memset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1)); pin_cmd.flags |= SC_PIN_CMD_IMPLICIT_CHANGE; sc_log(ctx, "PIN1(max:%i,min:%i)", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length); sc_log(ctx, "PIN2(max:%i,min:%i)", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length); rv = iso_ops->pin_cmd(card, &pin_cmd, NULL); LOG_FUNC_RETURN(ctx, rv); } #endif static int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data) { struct sc_context *ctx = card->ctx; struct sc_file *save_current_df = NULL, *save_current_ef = NULL; struct iasecc_sdo sdo; struct sc_path path; unsigned ii; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_pin_get_policy(card:%p)", card); if (data->pin_type != SC_AC_CHV) { sc_log(ctx, "To unblock PIN it's CHV reference should be presented"); LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } if (card->cache.valid && card->cache.current_df) { sc_file_dup(&save_current_df, card->cache.current_df); if (save_current_df == NULL) { rv = SC_ERROR_OUT_OF_MEMORY; sc_log(ctx, "Cannot duplicate current DF file"); goto err; } } if (card->cache.valid && card->cache.current_ef) { sc_file_dup(&save_current_ef, card->cache.current_ef); if (save_current_ef == NULL) { rv = SC_ERROR_OUT_OF_MEMORY; sc_log(ctx, "Cannot duplicate current EF file"); goto err; } } if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) { sc_format_path("3F00", &path); path.type = SC_PATH_TYPE_FILE_ID; rv = iasecc_select_file(card, &path, NULL); LOG_TEST_GOTO_ERR(ctx, rv, "Unable to select MF"); } memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_CHV; sdo.sdo_ref = data->pin_reference & ~IASECC_OBJECT_REF_LOCAL; sc_log(ctx, "iasecc_pin_get_policy() reference %i", sdo.sdo_ref); rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_GOTO_ERR(ctx, rv, "Cannot get SDO PIN data"); if (sdo.docp.acls_contact.size == 0) { rv = SC_ERROR_INVALID_DATA; sc_log(ctx, "Extremely strange ... there is no ACLs"); goto err; } sc_log(ctx, "iasecc_pin_get_policy() sdo.docp.size.size %"SC_FORMAT_LEN_SIZE_T"u", sdo.docp.size.size); for (ii=0; ii<sizeof(sdo.docp.scbs); ii++) { struct iasecc_se_info se; unsigned char scb = sdo.docp.scbs[ii]; struct sc_acl_entry *acl = &data->pin1.acls[ii]; int crt_num = 0; memset(&se, 0, sizeof(se)); memset(&acl->crts, 0, sizeof(acl->crts)); sc_log(ctx, "iasecc_pin_get_policy() set info acls: SCB 0x%X", scb); /* acl->raw_value = scb; */ acl->method = scb & IASECC_SCB_METHOD_MASK; acl->key_ref = scb & IASECC_SCB_METHOD_MASK_REF; if (scb==0 || scb==0xFF) continue; if (se.reference != (int)acl->key_ref) { memset(&se, 0, sizeof(se)); se.reference = acl->key_ref; rv = iasecc_se_get_info(card, &se); LOG_TEST_GOTO_ERR(ctx, rv, "SDO get data error"); } if (scb & IASECC_SCB_METHOD_USER_AUTH) { rv = iasecc_se_get_crt_by_usage(card, &se, IASECC_CRT_TAG_AT, IASECC_UQB_AT_USER_PASSWORD, &acl->crts[crt_num]); LOG_TEST_GOTO_ERR(ctx, rv, "no authentication template for 'USER PASSWORD'"); sc_log(ctx, "iasecc_pin_get_policy() scb:0x%X; sdo_ref:[%i,%i,...]", scb, acl->crts[crt_num].refs[0], acl->crts[crt_num].refs[1]); crt_num++; } if (scb & (IASECC_SCB_METHOD_SM | IASECC_SCB_METHOD_EXT_AUTH)) { sc_log(ctx, "'SM' and 'EXTERNAL AUTHENTICATION' protection methods are not supported: SCB:0x%X", scb); /* Set to 'NEVER' if all conditions are needed or * there is no user authentication method allowed */ if (!crt_num || (scb & IASECC_SCB_METHOD_NEED_ALL)) acl->method = SC_AC_NEVER; continue; } sc_file_free(se.df); } if (sdo.data.chv.size_max.value) data->pin1.max_length = *sdo.data.chv.size_max.value; if (sdo.data.chv.size_min.value) data->pin1.min_length = *sdo.data.chv.size_min.value; if (sdo.docp.tries_maximum.value) data->pin1.max_tries = *sdo.docp.tries_maximum.value; if (sdo.docp.tries_remaining.value) data->pin1.tries_left = *sdo.docp.tries_remaining.value; if (sdo.docp.size.value) { for (ii=0; ii<sdo.docp.size.size; ii++) data->pin1.stored_length = ((data->pin1.stored_length) << 8) + *(sdo.docp.size.value + ii); } data->pin1.encoding = SC_PIN_ENCODING_ASCII; data->pin1.offset = 5; data->pin1.logged_in = SC_PIN_STATE_UNKNOWN; sc_log(ctx, "PIN policy: size max/min %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u, tries max/left %i/%i", data->pin1.max_length, data->pin1.min_length, data->pin1.max_tries, data->pin1.tries_left); iasecc_sdo_free_fields(card, &sdo); if (save_current_df) { sc_log(ctx, "iasecc_pin_get_policy() restore current DF"); rv = iasecc_select_file(card, &save_current_df->path, NULL); LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved DF"); } if (save_current_ef) { sc_log(ctx, "iasecc_pin_get_policy() restore current EF"); rv = iasecc_select_file(card, &save_current_ef->path, NULL); LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved EF"); } err: sc_file_free(save_current_df); sc_file_free(save_current_ef); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_keyset_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct iasecc_sdo_update update; struct iasecc_sdo sdo; unsigned scb; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Change keyset(ref:%i,lengths:%i)", data->pin_reference, data->pin2.len); if (!data->pin2.data || data->pin2.len < 32) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Needs at least 32 bytes for a new keyset value"); memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_KEYSET; sdo.sdo_ref = data->pin_reference; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "Cannot get keyset data"); if (sdo.docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs"); scb = sdo.docp.scbs[IASECC_ACLS_KEYSET_PUT_DATA]; iasecc_sdo_free_fields(card, &sdo); sc_log(ctx, "SCB:0x%X", scb); if (!(scb & IASECC_SCB_METHOD_SM)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Other then protected by SM, the keyset change is not supported"); memset(&update, 0, sizeof(update)); update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA; update.sdo_class = sdo.sdo_class; update.sdo_ref = sdo.sdo_ref; update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG; update.fields[0].tag = IASECC_SDO_KEYSET_TAG_MAC; /* FIXME is it safe to modify the const value here? */ update.fields[0].value = (unsigned char *) data->pin2.data; update.fields[0].size = 16; update.fields[1].parent_tag = IASECC_SDO_KEYSET_TAG; update.fields[1].tag = IASECC_SDO_KEYSET_TAG_ENC; /* FIXME is it safe to modify the const value here? */ update.fields[1].value = (unsigned char *) data->pin2.data + 16; update.fields[1].size = 16; rv = iasecc_sm_sdo_update(card, (scb & IASECC_SCB_METHOD_MASK_REF), &update); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned reference = data->pin_reference; unsigned char pin_data[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Change PIN(ref:%i,type:0x%X,lengths:%i/%i)", reference, data->pin_type, data->pin1.len, data->pin2.len); if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD)) { if (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) { rv = iasecc_chv_change_pinpad(card, reference, tries_left); sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i", rv); LOG_FUNC_RETURN(ctx, rv); } } if (!data->pin1.data && data->pin1.len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN1 arguments"); if (!data->pin2.data && data->pin2.len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN2 arguments"); rv = iasecc_pin_verify(card, data->pin_type, reference, data->pin1.data, data->pin1.len, tries_left); sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) pin_verify returned %i", rv); LOG_TEST_RET(ctx, rv, "PIN verification error"); if ((unsigned)(data->pin1.len + data->pin2.len) > sizeof(pin_data)) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small for the 'Change PIN' data"); if (data->pin1.data) memcpy(pin_data, data->pin1.data, data->pin1.len); if (data->pin2.data) memcpy(pin_data + data->pin1.len, data->pin2.data, data->pin2.len); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0, reference); apdu.data = pin_data; apdu.datalen = data->pin1.len + data->pin2.len; apdu.lc = apdu.datalen; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; struct sc_file *save_current = NULL; struct iasecc_sdo sdo; struct sc_apdu apdu; unsigned reference, scb; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "Reset PIN(ref:%i,lengths:%i/%i)", data->pin_reference, data->pin1.len, data->pin2.len); if (data->pin_type != SC_AC_CHV) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Unblock procedure can be used only with the PINs of type CHV"); reference = data->pin_reference; if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) { struct sc_path path; sc_file_dup(&save_current, card->cache.current_df); if (save_current == NULL) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file"); sc_format_path("3F00", &path); path.type = SC_PATH_TYPE_FILE_ID; rv = iasecc_select_file(card, &path, NULL); LOG_TEST_RET(ctx, rv, "Unable to select MF"); } memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_CHV; sdo.sdo_ref = reference & ~IASECC_OBJECT_REF_LOCAL; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "Cannot get PIN data"); if (sdo.docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Extremely strange ... there are no ACLs"); scb = sdo.docp.scbs[IASECC_ACLS_CHV_RESET]; do { unsigned need_all = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0; unsigned char se_num = scb & IASECC_SCB_METHOD_MASK_REF; if (scb & IASECC_SCB_METHOD_USER_AUTH) { sc_log(ctx, "Verify PIN in SE %X", se_num); rv = iasecc_pin_verify(card, SC_AC_SEN, se_num, data->pin1.data, data->pin1.len, tries_left); LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() verify PUK error"); if (!need_all) break; } if (scb & IASECC_SCB_METHOD_SM) { rv = iasecc_sm_pin_reset(card, se_num, data); LOG_FUNC_RETURN(ctx, rv); } if (scb & IASECC_SCB_METHOD_EXT_AUTH) { rv = iasecc_sm_external_authentication(card, reference, tries_left); LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() external authentication error"); } } while(0); iasecc_sdo_free_fields(card, &sdo); if (data->pin2.len) { sc_log(ctx, "Reset PIN %X and set new value", reference); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference); apdu.data = data->pin2.data; apdu.datalen = data->pin2.len; apdu.lc = apdu.datalen; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); } else if (data->pin2.data) { sc_log(ctx, "Reset PIN %X and set new value", reference); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "PIN cmd failed"); } else { sc_log(ctx, "Reset PIN %X and set new value with PIN-PAD", reference); #if 0 rv = iasecc_chv_set_pinpad(card, reference); LOG_TEST_RET(ctx, rv, "Reset PIN failed"); #else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Reset retry counter with PIN PAD not supported "); #endif } if (save_current) { rv = iasecc_select_file(card, &save_current->path, NULL); LOG_TEST_RET(ctx, rv, "Cannot return to saved PATH"); } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { struct sc_context *ctx = card->ctx; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_pin_cmd() cmd 0x%X, PIN type 0x%X, PIN reference %i, PIN-1 %p:%i, PIN-2 %p:%i", data->cmd, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, data->pin2.data, data->pin2.len); switch (data->cmd) { case SC_PIN_CMD_VERIFY: rv = iasecc_pin_verify(card, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, tries_left); break; case SC_PIN_CMD_CHANGE: if (data->pin_type == SC_AC_AUT) rv = iasecc_keyset_change(card, data, tries_left); else rv = iasecc_pin_change(card, data, tries_left); break; case SC_PIN_CMD_UNBLOCK: rv = iasecc_pin_reset(card, data, tries_left); break; case SC_PIN_CMD_GET_INFO: rv = iasecc_pin_get_policy(card, data); break; default: sc_log(ctx, "Other pin commands not supported yet: 0x%X", data->cmd); rv = SC_ERROR_NOT_SUPPORTED; } LOG_FUNC_RETURN(ctx, rv); } static int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial) { struct sc_context *ctx = card->ctx; struct sc_iin *iin = &card->serialnr.iin; struct sc_apdu apdu; unsigned char rbuf[0xC0]; size_t ii, offs; int rv; LOG_FUNC_CALLED(ctx); if (card->serialnr.len) goto end; memset(&card->serialnr, 0, sizeof(card->serialnr)); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0); apdu.le = sizeof(rbuf); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Get 'serial number' data failed"); if (rbuf[0] != ISO7812_PAN_SN_TAG) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "serial number parse error"); iin->mii = (rbuf[2] >> 4) & 0x0F; iin->country = 0; for (ii=5; ii<8; ii++) { iin->country *= 10; iin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F; } iin->issuer_id = 0; for (ii=8; ii<10; ii++) { iin->issuer_id *= 10; iin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F; } offs = rbuf[1] > 8 ? rbuf[1] - 8 : 0; if (card->type == SC_CARD_TYPE_IASECC_SAGEM) { /* 5A 0A 92 50 00 20 10 10 25 00 01 3F */ /* 00 02 01 01 02 50 00 13 */ for (ii=0; ii < rbuf[1] - offs; ii++) *(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4) + ((rbuf[ii + offs + 2] & 0xF0) >> 4) ; card->serialnr.len = ii; } else { for (ii=0; ii < rbuf[1] - offs; ii++) *(card->serialnr.value + ii) = rbuf[ii + offs + 2]; card->serialnr.len = ii; } do { char txt[0x200]; for (ii=0;ii<card->serialnr.len;ii++) sprintf(txt + ii*2, "%02X", *(card->serialnr.value + ii)); sc_log(ctx, "serial number '%s'; mii %i; country %i; issuer_id %li", txt, iin->mii, iin->country, iin->issuer_id); } while(0); end: if (serial) memcpy(serial, &card->serialnr, sizeof(*serial)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_sdo_create(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char *data = NULL, sdo_class = sdo->sdo_class; struct iasecc_sdo_update update; struct iasecc_extended_tlv *field = NULL; int rv = SC_ERROR_NOT_SUPPORTED, data_len; LOG_FUNC_CALLED(ctx); if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data"); sc_log(ctx, "iasecc_sdo_create(card:%p) %02X%02X%02X", card, IASECC_SDO_TAG_HEADER, sdo->sdo_class | 0x80, sdo->sdo_ref); data_len = iasecc_sdo_encode_create(ctx, sdo, &data); LOG_TEST_RET(ctx, data_len, "iasecc_sdo_create() cannot encode SDO create data"); sc_log(ctx, "iasecc_sdo_create() create data(%i):%s", data_len, sc_dump_hex(data, data_len)); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF); apdu.data = data; apdu.datalen = data_len; apdu.lc = data_len; apdu.flags |= SC_APDU_FLAGS_CHAINING; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "iasecc_sdo_create() SDO put data error"); memset(&update, 0, sizeof(update)); update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA; update.sdo_class = sdo->sdo_class; update.sdo_ref = sdo->sdo_ref; if (sdo_class == IASECC_SDO_CLASS_RSA_PRIVATE) { update.fields[0] = sdo->data.prv_key.compulsory; update.fields[0].parent_tag = IASECC_SDO_PRVKEY_TAG; field = &sdo->data.prv_key.compulsory; } else if (sdo_class == IASECC_SDO_CLASS_RSA_PUBLIC) { update.fields[0] = sdo->data.pub_key.compulsory; update.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG; field = &sdo->data.pub_key.compulsory; } else if (sdo_class == IASECC_SDO_CLASS_KEYSET) { update.fields[0] = sdo->data.keyset.compulsory; update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG; field = &sdo->data.keyset.compulsory; } if (update.fields[0].value && !update.fields[0].on_card) { rv = iasecc_sdo_put_data(card, &update); LOG_TEST_RET(ctx, rv, "failed to update 'Compulsory usage' data"); if (field) field->on_card = 1; } free(data); LOG_FUNC_RETURN(ctx, rv); } /* Oberthur's specific */ static int iasecc_sdo_delete(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char data[6] = { 0x70, 0x04, 0xBF, 0xFF, 0xFF, 0x00 }; int rv; LOG_FUNC_CALLED(ctx); if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data"); data[2] = IASECC_SDO_TAG_HEADER; data[3] = sdo->sdo_class | 0x80; data[4] = sdo->sdo_ref; sc_log(ctx, "delete SDO %02X%02X%02X", data[2], data[3], data[4]); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF); apdu.data = data; apdu.datalen = sizeof(data); apdu.lc = sizeof(data); apdu.flags |= SC_APDU_FLAGS_CHAINING; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "delete SDO error"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; int ii, rv; LOG_FUNC_CALLED(ctx); if (update->magic != SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO update data"); for(ii=0; update->fields[ii].tag && ii < IASECC_SDO_TAGS_UPDATE_MAX; ii++) { unsigned char *encoded = NULL; int encoded_len; encoded_len = iasecc_sdo_encode_update_field(ctx, update->sdo_class, update->sdo_ref, &update->fields[ii], &encoded); sc_log(ctx, "iasecc_sdo_put_data() encode[%i]; tag %X; encoded_len %i", ii, update->fields[ii].tag, encoded_len); LOG_TEST_RET(ctx, encoded_len, "Cannot encode update data"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF); apdu.data = encoded; apdu.datalen = encoded_len; apdu.lc = encoded_len; apdu.flags |= SC_APDU_FLAGS_CHAINING; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "SDO put data error"); free(encoded); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_sdo_key_rsa_put_data(struct sc_card *card, struct iasecc_sdo_rsa_update *update) { struct sc_context *ctx = card->ctx; unsigned char scb; int rv; LOG_FUNC_CALLED(ctx); if (update->sdo_prv_key) { sc_log(ctx, "encode private rsa in %p", &update->update_prv); rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_prv_key, update->p15_rsa, &update->update_prv); LOG_TEST_RET(ctx, rv, "failed to encode update of RSA private key"); } if (update->sdo_pub_key) { sc_log(ctx, "encode public rsa in %p", &update->update_pub); if (card->type == SC_CARD_TYPE_IASECC_SAGEM) { if (update->sdo_pub_key->data.pub_key.cha.value) { free(update->sdo_pub_key->data.pub_key.cha.value); memset(&update->sdo_pub_key->data.pub_key.cha, 0, sizeof(update->sdo_pub_key->data.pub_key.cha)); } } rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_pub_key, update->p15_rsa, &update->update_pub); LOG_TEST_RET(ctx, rv, "failed to encode update of RSA public key"); } if (update->sdo_prv_key) { sc_log(ctx, "reference of the private key to store: %X", update->sdo_prv_key->sdo_ref); if (update->sdo_prv_key->docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "extremely strange ... there are no ACLs"); scb = update->sdo_prv_key->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA]; sc_log(ctx, "'UPDATE PRIVATE RSA' scb 0x%X", scb); do { unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0; if ((scb & IASECC_SCB_METHOD_USER_AUTH) && !all_conditions) break; if (scb & IASECC_SCB_METHOD_EXT_AUTH) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet"); if (scb & IASECC_SCB_METHOD_SM) { #ifdef ENABLE_SM rv = iasecc_sm_rsa_update(card, scb & IASECC_SCB_METHOD_MASK_REF, update); LOG_FUNC_RETURN(ctx, rv); #else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "built without support of Secure-Messaging"); #endif } } while(0); rv = iasecc_sdo_put_data(card, &update->update_prv); LOG_TEST_RET(ctx, rv, "failed to update of RSA private key"); } if (update->sdo_pub_key) { sc_log(ctx, "reference of the public key to store: %X", update->sdo_pub_key->sdo_ref); rv = iasecc_sdo_put_data(card, &update->update_pub); LOG_TEST_RET(ctx, rv, "failed to update of RSA public key"); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_sdo_tag_from_class(unsigned sdo_class) { switch (sdo_class & ~IASECC_OBJECT_REF_LOCAL) { case IASECC_SDO_CLASS_CHV: return IASECC_SDO_CHV_TAG; case IASECC_SDO_CLASS_RSA_PRIVATE: return IASECC_SDO_PRVKEY_TAG; case IASECC_SDO_CLASS_RSA_PUBLIC: return IASECC_SDO_PUBKEY_TAG; case IASECC_SDO_CLASS_SE: return IASECC_SDO_CLASS_SE; case IASECC_SDO_CLASS_KEYSET: return IASECC_SDO_KEYSET_TAG; } return -1; } static int iasecc_sdo_get_tagged_data(struct sc_card *card, int sdo_tag, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char sbuf[0x100]; size_t offs = sizeof(sbuf) - 1; unsigned char rbuf[0x400]; int rv; LOG_FUNC_CALLED(ctx); sbuf[offs--] = 0x80; sbuf[offs--] = sdo_tag & 0xFF; if ((sdo_tag >> 8) & 0xFF) sbuf[offs--] = (sdo_tag >> 8) & 0xFF; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs--] = sdo->sdo_ref & 0x9F; sbuf[offs--] = sdo->sdo_class | IASECC_OBJECT_REF_LOCAL; sbuf[offs--] = IASECC_SDO_TAG_HEADER; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs--] = IASECC_SDO_TEMPLATE_TAG; sbuf[offs] = sizeof(sbuf) - offs - 1; offs--; sbuf[offs] = 0x4D; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF); apdu.data = sbuf + offs; apdu.datalen = sizeof(sbuf) - offs; apdu.lc = sizeof(sbuf) - offs; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "SDO get data error"); rv = iasecc_sdo_parse(card, apdu.resp, apdu.resplen, sdo); LOG_TEST_RET(ctx, rv, "cannot parse SDO data"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; int rv, sdo_tag; LOG_FUNC_CALLED(ctx); sdo_tag = iasecc_sdo_tag_from_class(sdo->sdo_class); rv = iasecc_sdo_get_tagged_data(card, sdo_tag, sdo); /* When there is no public data 'GET DATA' returns error */ if (rv != SC_ERROR_INCORRECT_PARAMETERS) LOG_TEST_RET(ctx, rv, "cannot parse ECC SDO data"); rv = iasecc_sdo_get_tagged_data(card, IASECC_DOCP_TAG, sdo); LOG_TEST_RET(ctx, rv, "cannot parse ECC DOCP data"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_sdo_generate(struct sc_card *card, struct iasecc_sdo *sdo) { struct sc_context *ctx = card->ctx; struct iasecc_sdo_update update_pubkey; struct sc_apdu apdu; unsigned char scb, sbuf[5], rbuf[0x400], exponent[3] = {0x01, 0x00, 0x01}; int offs = 0, rv = SC_ERROR_NOT_SUPPORTED; LOG_FUNC_CALLED(ctx); if (sdo->sdo_class != IASECC_SDO_CLASS_RSA_PRIVATE) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "For a moment, only RSA_PRIVATE class can be accepted for the SDO generation"); if (sdo->docp.acls_contact.size == 0) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs"); scb = sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE]; sc_log(ctx, "'generate RSA key' SCB 0x%X", scb); do { unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0; if (scb & IASECC_SCB_METHOD_USER_AUTH) if (!all_conditions) break; if (scb & IASECC_SCB_METHOD_EXT_AUTH) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet"); if (scb & IASECC_SCB_METHOD_SM) { rv = iasecc_sm_rsa_generate(card, scb & IASECC_SCB_METHOD_MASK_REF, sdo); LOG_FUNC_RETURN(ctx, rv); } } while(0); memset(&update_pubkey, 0, sizeof(update_pubkey)); update_pubkey.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA; update_pubkey.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC; update_pubkey.sdo_ref = sdo->sdo_ref; update_pubkey.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG; update_pubkey.fields[0].tag = IASECC_SDO_PUBKEY_TAG_E; update_pubkey.fields[0].value = exponent; update_pubkey.fields[0].size = sizeof(exponent); rv = iasecc_sdo_put_data(card, &update_pubkey); LOG_TEST_RET(ctx, rv, "iasecc_sdo_generate() update SDO public key failed"); offs = 0; sbuf[offs++] = IASECC_SDO_TEMPLATE_TAG; sbuf[offs++] = 0x03; sbuf[offs++] = IASECC_SDO_TAG_HEADER; sbuf[offs++] = IASECC_SDO_CLASS_RSA_PRIVATE | IASECC_OBJECT_REF_LOCAL; sbuf[offs++] = sdo->sdo_ref & ~IASECC_OBJECT_REF_LOCAL; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00); apdu.data = sbuf; apdu.datalen = offs; apdu.lc = offs; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "SDO get data error"); LOG_FUNC_RETURN(ctx, rv); } static int iasecc_get_chv_reference_from_se(struct sc_card *card, int *se_reference) { struct sc_context *ctx = card->ctx; struct iasecc_se_info se; struct sc_crt crt; int rv; LOG_FUNC_CALLED(ctx); if (!se_reference) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments"); memset(&se, 0, sizeof(se)); se.reference = *se_reference; rv = iasecc_se_get_info(card, &se); LOG_TEST_RET(ctx, rv, "get SE info error"); memset(&crt, 0, sizeof(crt)); crt.tag = IASECC_CRT_TAG_AT; crt.usage = IASECC_UQB_AT_USER_PASSWORD; rv = iasecc_se_get_crt(card, &se, &crt); LOG_TEST_RET(ctx, rv, "Cannot get 'USER PASSWORD' authentication template"); sc_file_free(se.df); LOG_FUNC_RETURN(ctx, crt.refs[0]); } static int iasecc_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr) { struct sc_context *ctx = card->ctx; struct iasecc_sdo *sdo = (struct iasecc_sdo *) ptr; switch (cmd) { case SC_CARDCTL_GET_SERIALNR: return iasecc_get_serialnr(card, (struct sc_serial_number *)ptr); case SC_CARDCTL_IASECC_SDO_CREATE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_CREATE: sdo_class %X", sdo->sdo_class); return iasecc_sdo_create(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_IASECC_SDO_DELETE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_DELETE: sdo_class %X", sdo->sdo_class); return iasecc_sdo_delete(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_IASECC_SDO_PUT_DATA: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_PUT_DATA: sdo_class %X", sdo->sdo_class); return iasecc_sdo_put_data(card, (struct iasecc_sdo_update *) ptr); case SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA"); return iasecc_sdo_key_rsa_put_data(card, (struct iasecc_sdo_rsa_update *) ptr); case SC_CARDCTL_IASECC_SDO_GET_DATA: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class); return iasecc_sdo_get_data(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_IASECC_SDO_GENERATE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class); return iasecc_sdo_generate(card, (struct iasecc_sdo *) ptr); case SC_CARDCTL_GET_SE_INFO: sc_log(ctx, "CMD SC_CARDCTL_GET_SE_INFO: sdo_class %X", sdo->sdo_class); return iasecc_se_get_info(card, (struct iasecc_se_info *) ptr); case SC_CARDCTL_GET_CHV_REFERENCE_IN_SE: sc_log(ctx, "CMD SC_CARDCTL_GET_CHV_REFERENCE_IN_SE"); return iasecc_get_chv_reference_from_se(card, (int *)ptr); case SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE: sc_log(ctx, "CMD SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE"); return iasecc_get_free_reference(card, (struct iasecc_ctl_get_free_reference *)ptr); } return SC_ERROR_NOT_SUPPORTED; } static int iasecc_decipher(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; struct sc_apdu apdu; unsigned char sbuf[0x200]; unsigned char resp[SC_MAX_APDU_BUFFER_SIZE]; size_t offs; int rv; LOG_FUNC_CALLED(ctx); sc_log(card->ctx, "crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u", in_len, out_len); if (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); offs = 0; sbuf[offs++] = 0x81; memcpy(sbuf + offs, in, in_len); offs += in_len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.flags |= SC_APDU_FLAGS_CHAINING; apdu.data = sbuf; apdu.datalen = offs; apdu.lc = offs; apdu.resp = resp; apdu.resplen = sizeof(resp); apdu.le = 256; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Card returned error"); if (out_len > apdu.resplen) out_len = apdu.resplen; memcpy(out, apdu.resp, out_len); rv = out_len; LOG_FUNC_RETURN(ctx, rv); } static int iasecc_qsign_data_sha1(struct sc_context *ctx, const unsigned char *in, size_t in_len, struct iasecc_qsign_data *out) { SHA_CTX sha; SHA_LONG pre_hash_Nl, *hh[5] = { &sha.h0, &sha.h1, &sha.h2, &sha.h3, &sha.h4 }; int jj, ii; int hh_size = sizeof(SHA_LONG), hh_num = SHA_DIGEST_LENGTH / sizeof(SHA_LONG); LOG_FUNC_CALLED(ctx); if (!in || !in_len || !out) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_log(ctx, "sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u", in_len); memset(out, 0, sizeof(struct iasecc_qsign_data)); SHA1_Init(&sha); SHA1_Update(&sha, in, in_len); for (jj=0; jj<hh_num; jj++) for(ii=0; ii<hh_size; ii++) out->pre_hash[jj*hh_size + ii] = ((*hh[jj] >> 8*(hh_size-1-ii)) & 0xFF); out->pre_hash_size = SHA_DIGEST_LENGTH; sc_log(ctx, "Pre SHA1:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size)); pre_hash_Nl = sha.Nl - (sha.Nl % (sizeof(sha.data) * 8)); for (ii=0; ii<hh_size; ii++) { out->counter[ii] = (sha.Nh >> 8*(hh_size-1-ii)) &0xFF; out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF; } for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++) out->counter_long = out->counter_long*0x100 + out->counter[ii]; sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter))); if (sha.num) { memcpy(out->last_block, in + in_len - sha.num, sha.num); out->last_block_size = sha.num; sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s", out->last_block_size, sc_dump_hex(out->last_block, out->last_block_size)); } SHA1_Final(out->hash, &sha); out->hash_size = SHA_DIGEST_LENGTH; sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } #if OPENSSL_VERSION_NUMBER >= 0x00908000L static int iasecc_qsign_data_sha256(struct sc_context *ctx, const unsigned char *in, size_t in_len, struct iasecc_qsign_data *out) { SHA256_CTX sha256; SHA_LONG pre_hash_Nl; int jj, ii; int hh_size = sizeof(SHA_LONG), hh_num = SHA256_DIGEST_LENGTH / sizeof(SHA_LONG); LOG_FUNC_CALLED(ctx); if (!in || !in_len || !out) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_log(ctx, "sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u", in_len); memset(out, 0, sizeof(struct iasecc_qsign_data)); SHA256_Init(&sha256); SHA256_Update(&sha256, in, in_len); for (jj=0; jj<hh_num; jj++) for(ii=0; ii<hh_size; ii++) out->pre_hash[jj*hh_size + ii] = ((sha256.h[jj] >> 8*(hh_size-1-ii)) & 0xFF); out->pre_hash_size = SHA256_DIGEST_LENGTH; sc_log(ctx, "Pre hash:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size)); pre_hash_Nl = sha256.Nl - (sha256.Nl % (sizeof(sha256.data) * 8)); for (ii=0; ii<hh_size; ii++) { out->counter[ii] = (sha256.Nh >> 8*(hh_size-1-ii)) &0xFF; out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF; } for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++) out->counter_long = out->counter_long*0x100 + out->counter[ii]; sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter))); if (sha256.num) { memcpy(out->last_block, in + in_len - sha256.num, sha256.num); out->last_block_size = sha256.num; sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s", out->last_block_size, sc_dump_hex(out->last_block, out->last_block_size)); } SHA256_Final(out->hash, &sha256); out->hash_size = SHA256_DIGEST_LENGTH; sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size)); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } #endif static int iasecc_compute_signature_dst(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_security_env *env = &prv->security_env; struct iasecc_qsign_data qsign_data; struct sc_apdu apdu; size_t offs = 0, hash_len = 0; unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE]; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int rv = SC_SUCCESS; LOG_FUNC_CALLED(ctx); sc_log(ctx, "iasecc_compute_signature_dst() input length %"SC_FORMAT_LEN_SIZE_T"u", in_len); if (env->operation != SC_SEC_OPERATION_SIGN) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_SIGN"); else if (!(prv->key_size & 0x1E0) || (prv->key_size & ~0x1E0)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid key size for SC_SEC_OPERATION_SIGN"); memset(&qsign_data, 0, sizeof(qsign_data)); if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) { rv = iasecc_qsign_data_sha1(card->ctx, in, in_len, &qsign_data); } else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) { #if OPENSSL_VERSION_NUMBER >= 0x00908000L rv = iasecc_qsign_data_sha256(card->ctx, in, in_len, &qsign_data); #else LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "SHA256 is not supported by OpenSSL previous to v0.9.8"); #endif } else LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA1 or RSA_HASH_SHA256 algorithm"); LOG_TEST_RET(ctx, rv, "Cannot get QSign data"); sc_log(ctx, "iasecc_compute_signature_dst() hash_len %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u", hash_len, prv->key_size); memset(sbuf, 0, sizeof(sbuf)); sbuf[offs++] = 0x90; if (qsign_data.counter_long) { sbuf[offs++] = qsign_data.hash_size + 8; memcpy(sbuf + offs, qsign_data.pre_hash, qsign_data.pre_hash_size); offs += qsign_data.pre_hash_size; memcpy(sbuf + offs, qsign_data.counter, sizeof(qsign_data.counter)); offs += sizeof(qsign_data.counter); } else { sbuf[offs++] = 0; } sbuf[offs++] = 0x80; sbuf[offs++] = qsign_data.last_block_size; memcpy(sbuf + offs, qsign_data.last_block, qsign_data.last_block_size); offs += qsign_data.last_block_size; sc_log(ctx, "iasecc_compute_signature_dst() offs %"SC_FORMAT_LEN_SIZE_T"u; OP(meth:%X,ref:%X)", offs, prv->op_method, prv->op_ref); if (prv->op_method == SC_AC_SCB && (prv->op_ref & IASECC_SCB_METHOD_SM)) LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2A, 0x90, 0xA0); apdu.data = sbuf; apdu.datalen = offs; apdu.lc = offs; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Compute signature failed"); sc_log(ctx, "iasecc_compute_signature_dst() partial hash OK"); sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x2A, 0x9E, 0x9A); apdu.resp = rbuf; apdu.resplen = prv->key_size; apdu.le = prv->key_size; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Compute signature failed"); sc_log(ctx, "iasecc_compute_signature_dst() DST resplen %"SC_FORMAT_LEN_SIZE_T"u", apdu.resplen); if (apdu.resplen > out_len) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Result buffer too small for the DST signature"); memcpy(out, apdu.resp, apdu.resplen); LOG_FUNC_RETURN(ctx, apdu.resplen); } static int iasecc_compute_signature_at(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data; struct sc_security_env *env = &prv->security_env; struct sc_apdu apdu; size_t offs = 0, sz = 0; unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE]; int rv; LOG_FUNC_CALLED(ctx); if (env->operation != SC_SEC_OPERATION_AUTHENTICATE) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_AUTHENTICATE"); sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x88, 0x00, 0x00); apdu.datalen = in_len; apdu.data = in; apdu.lc = in_len; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 0x100; rv = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, rv, "APDU transmit failed"); rv = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, rv, "Compute signature failed"); do { if (offs + apdu.resplen > out_len) LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to return signature"); memcpy(out + offs, rbuf, apdu.resplen); offs += apdu.resplen; if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) break; if (apdu.sw1 == 0x61) { sz = apdu.sw2 == 0x00 ? 0x100 : apdu.sw2; rv = iso_ops->get_response(card, &sz, rbuf); LOG_TEST_RET(ctx, rv, "Get response error"); apdu.resplen = rv; } else { LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Impossible error: SW1 is not 0x90 neither 0x61"); } } while(rv > 0); LOG_FUNC_RETURN(ctx, offs); } static int iasecc_compute_signature(struct sc_card *card, const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len) { struct sc_context *ctx; struct iasecc_private_data *prv; struct sc_security_env *env; if (!card || !in || !out) return SC_ERROR_INVALID_ARGUMENTS; ctx = card->ctx; prv = (struct iasecc_private_data *) card->drv_data; env = &prv->security_env; LOG_FUNC_CALLED(ctx); sc_log(ctx, "inlen %"SC_FORMAT_LEN_SIZE_T"u, outlen %"SC_FORMAT_LEN_SIZE_T"u", in_len, out_len); if (env->operation == SC_SEC_OPERATION_SIGN) return iasecc_compute_signature_dst(card, in, in_len, out, out_len); else if (env->operation == SC_SEC_OPERATION_AUTHENTICATE) return iasecc_compute_signature_at(card, in, in_len, out, out_len); LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); } static int iasecc_read_public_key(struct sc_card *card, unsigned type, struct sc_path *key_path, unsigned ref, unsigned size, unsigned char **out, size_t *out_len) { struct sc_context *ctx = card->ctx; struct iasecc_sdo sdo; struct sc_pkcs15_bignum bn[2]; struct sc_pkcs15_pubkey_rsa rsa_key; int rv; LOG_FUNC_CALLED(ctx); if (type != SC_ALGORITHM_RSA) LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); sc_log(ctx, "read public kay(ref:%i;size:%i)", ref, size); memset(&sdo, 0, sizeof(sdo)); sdo.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC; sdo.sdo_ref = ref & ~IASECC_OBJECT_REF_LOCAL; rv = iasecc_sdo_get_data(card, &sdo); LOG_TEST_RET(ctx, rv, "failed to read public key: cannot get RSA SDO data"); if (out) *out = NULL; if (out_len) *out_len = 0; bn[0].data = (unsigned char *) malloc(sdo.data.pub_key.n.size); if (!bn[0].data) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate modulus"); bn[0].len = sdo.data.pub_key.n.size; memcpy(bn[0].data, sdo.data.pub_key.n.value, sdo.data.pub_key.n.size); bn[1].data = (unsigned char *) malloc(sdo.data.pub_key.e.size); if (!bn[1].data) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate exponent"); bn[1].len = sdo.data.pub_key.e.size; memcpy(bn[1].data, sdo.data.pub_key.e.value, sdo.data.pub_key.e.size); rsa_key.modulus = bn[0]; rsa_key.exponent = bn[1]; rv = sc_pkcs15_encode_pubkey_rsa(ctx, &rsa_key, out, out_len); LOG_TEST_RET(ctx, rv, "failed to read public key: cannot encode RSA public key"); if (out && out_len) sc_log(ctx, "encoded public key: %s", sc_dump_hex(*out, *out_len)); if (bn[0].data) free(bn[0].data); if (bn[1].data) free(bn[1].data); iasecc_sdo_free_fields(card, &sdo); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data) { struct sc_context *ctx = card->ctx; struct iasecc_sdo *sdo = NULL; int idx, rv; LOG_FUNC_CALLED(ctx); if ((ctl_data->key_size % 0x40) || ctl_data->index < 1 || (ctl_data->index > IASECC_OBJECT_REF_MAX)) LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); sc_log(ctx, "get reference for key(index:%i,usage:%X,access:%X)", ctl_data->index, ctl_data->usage, ctl_data->access); /* TODO: when looking for the slot for the signature keys, check also PSO_SIGNATURE ACL */ for (idx = ctl_data->index; idx <= IASECC_OBJECT_REF_MAX; idx++) { unsigned char sdo_tag[3] = { IASECC_SDO_TAG_HEADER, IASECC_OBJECT_REF_LOCAL | IASECC_SDO_CLASS_RSA_PRIVATE, idx }; size_t sz; if (sdo) iasecc_sdo_free(card, sdo); rv = iasecc_sdo_allocate_and_parse(card, sdo_tag, 3, &sdo); LOG_TEST_RET(ctx, rv, "cannot parse SDO data"); rv = iasecc_sdo_get_data(card, sdo); if (rv == SC_ERROR_DATA_OBJECT_NOT_FOUND) { iasecc_sdo_free(card, sdo); sc_log(ctx, "found empty key slot %i", idx); break; } else LOG_TEST_RET(ctx, rv, "get new key reference failed"); sz = *(sdo->docp.size.value + 0) * 0x100 + *(sdo->docp.size.value + 1); sc_log(ctx, "SDO(idx:%i) size %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u", idx, sz, ctl_data->key_size); if (sz != ctl_data->key_size / 8) { sc_log(ctx, "key index %i ignored: different key sizes %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u", idx, sz, ctl_data->key_size / 8); continue; } if (sdo->docp.non_repudiation.value) { sc_log(ctx, "non repudiation flag %X", sdo->docp.non_repudiation.value[0]); if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && !(*sdo->docp.non_repudiation.value)) { sc_log(ctx, "key index %i ignored: need non repudiation", idx); continue; } if (!(ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && *sdo->docp.non_repudiation.value) { sc_log(ctx, "key index %i ignored: don't need non-repudiation", idx); continue; } } if (ctl_data->access & SC_PKCS15_PRKEY_ACCESS_LOCAL) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: GENERATE KEY not allowed", idx); continue; } } else { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: PUT DATA not allowed", idx); continue; } } if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN)) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_SIGN] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: PSO SIGN not allowed", idx); continue; } } else if (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_INTERNAL_AUTH] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: INTERNAL AUTHENTICATE not allowed", idx); continue; } } if (ctl_data->usage & (SC_PKCS15_PRKEY_USAGE_DECRYPT | SC_PKCS15_PRKEY_USAGE_UNWRAP)) { if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_DECIPHER] == IASECC_SCB_NEVER) { sc_log(ctx, "key index %i ignored: PSO DECIPHER not allowed", idx); continue; } } break; } ctl_data->index = idx; if (idx > IASECC_OBJECT_REF_MAX) LOG_FUNC_RETURN(ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static struct sc_card_driver * sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (!iso_ops) iso_ops = iso_drv->ops; iasecc_ops = *iso_ops; iasecc_ops.match_card = iasecc_match_card; iasecc_ops.init = iasecc_init; iasecc_ops.finish = iasecc_finish; iasecc_ops.read_binary = iasecc_read_binary; /* write_binary: ISO7816 implementation works */ /* update_binary: ISO7816 implementation works */ iasecc_ops.erase_binary = iasecc_erase_binary; /* resize_binary */ /* read_record: Untested */ /* write_record: Untested */ /* append_record: Untested */ /* update_record: Untested */ iasecc_ops.select_file = iasecc_select_file; /* get_response: Untested */ /* get_challenge: ISO7816 implementation works */ iasecc_ops.logout = iasecc_logout; /* restore_security_env */ iasecc_ops.set_security_env = iasecc_set_security_env; iasecc_ops.decipher = iasecc_decipher; iasecc_ops.compute_signature = iasecc_compute_signature; iasecc_ops.create_file = iasecc_create_file; iasecc_ops.delete_file = iasecc_delete_file; /* list_files */ iasecc_ops.check_sw = iasecc_check_sw; iasecc_ops.card_ctl = iasecc_card_ctl; iasecc_ops.process_fci = iasecc_process_fci; /* construct_fci: Not needed */ iasecc_ops.pin_cmd = iasecc_pin_cmd; /* get_data: Not implemented */ /* put_data: Not implemented */ /* delete_record: Not implemented */ iasecc_ops.read_public_key = iasecc_read_public_key; return &iasecc_drv; } struct sc_card_driver * sc_get_iasecc_driver(void) { return sc_get_driver(); } #else /* we need to define the functions below to export them */ #include "errors.h" int iasecc_se_get_info() { return SC_ERROR_NOT_SUPPORTED; } #endif /* ENABLE_OPENSSL */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_8
crossvul-cpp_data_bad_2688_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Address Resolution Protocol (ARP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "ether.h" #include "ethertype.h" #include "extract.h" static const char tstr[] = "[|ARP]"; /* * Address Resolution Protocol. * * See RFC 826 for protocol description. ARP packets are variable * in size; the arphdr structure defines the fixed-length portion. * Protocol type values are the same as those for 10 Mb/s Ethernet. * It is followed by the variable-sized fields ar_sha, arp_spa, * arp_tha and arp_tpa in that order, according to the lengths * specified. Field names used correspond to RFC 826. */ struct arp_pkthdr { u_short ar_hrd; /* format of hardware address */ #define ARPHRD_ETHER 1 /* ethernet hardware format */ #define ARPHRD_IEEE802 6 /* token-ring hardware format */ #define ARPHRD_ARCNET 7 /* arcnet hardware format */ #define ARPHRD_FRELAY 15 /* frame relay hardware format */ #define ARPHRD_ATM2225 19 /* ATM (RFC 2225) */ #define ARPHRD_STRIP 23 /* Ricochet Starmode Radio hardware format */ #define ARPHRD_IEEE1394 24 /* IEEE 1394 (FireWire) hardware format */ u_short ar_pro; /* format of protocol address */ u_char ar_hln; /* length of hardware address */ u_char ar_pln; /* length of protocol address */ u_short ar_op; /* one of: */ #define ARPOP_REQUEST 1 /* request to resolve address */ #define ARPOP_REPLY 2 /* response to previous request */ #define ARPOP_REVREQUEST 3 /* request protocol address given hardware */ #define ARPOP_REVREPLY 4 /* response giving protocol address */ #define ARPOP_INVREQUEST 8 /* request to identify peer */ #define ARPOP_INVREPLY 9 /* response identifying peer */ #define ARPOP_NAK 10 /* NAK - only valif for ATM ARP */ /* * The remaining fields are variable in size, * according to the sizes above. */ #ifdef COMMENT_ONLY u_char ar_sha[]; /* sender hardware address */ u_char ar_spa[]; /* sender protocol address */ u_char ar_tha[]; /* target hardware address */ u_char ar_tpa[]; /* target protocol address */ #endif #define ar_sha(ap) (((const u_char *)((ap)+1))+0) #define ar_spa(ap) (((const u_char *)((ap)+1))+ (ap)->ar_hln) #define ar_tha(ap) (((const u_char *)((ap)+1))+ (ap)->ar_hln+(ap)->ar_pln) #define ar_tpa(ap) (((const u_char *)((ap)+1))+2*(ap)->ar_hln+(ap)->ar_pln) }; #define ARP_HDRLEN 8 #define HRD(ap) EXTRACT_16BITS(&(ap)->ar_hrd) #define HRD_LEN(ap) ((ap)->ar_hln) #define PROTO_LEN(ap) ((ap)->ar_pln) #define OP(ap) EXTRACT_16BITS(&(ap)->ar_op) #define PRO(ap) EXTRACT_16BITS(&(ap)->ar_pro) #define SHA(ap) (ar_sha(ap)) #define SPA(ap) (ar_spa(ap)) #define THA(ap) (ar_tha(ap)) #define TPA(ap) (ar_tpa(ap)) static const struct tok arpop_values[] = { { ARPOP_REQUEST, "Request" }, { ARPOP_REPLY, "Reply" }, { ARPOP_REVREQUEST, "Reverse Request" }, { ARPOP_REVREPLY, "Reverse Reply" }, { ARPOP_INVREQUEST, "Inverse Request" }, { ARPOP_INVREPLY, "Inverse Reply" }, { ARPOP_NAK, "NACK Reply" }, { 0, NULL } }; static const struct tok arphrd_values[] = { { ARPHRD_ETHER, "Ethernet" }, { ARPHRD_IEEE802, "TokenRing" }, { ARPHRD_ARCNET, "ArcNet" }, { ARPHRD_FRELAY, "FrameRelay" }, { ARPHRD_STRIP, "Strip" }, { ARPHRD_IEEE1394, "IEEE 1394" }, { ARPHRD_ATM2225, "ATM" }, { 0, NULL } }; /* * ATM Address Resolution Protocol. * * See RFC 2225 for protocol description. ATMARP packets are similar * to ARP packets, except that there are no length fields for the * protocol address - instead, there are type/length fields for * the ATM number and subaddress - and the hardware addresses consist * of an ATM number and an ATM subaddress. */ struct atmarp_pkthdr { u_short aar_hrd; /* format of hardware address */ u_short aar_pro; /* format of protocol address */ u_char aar_shtl; /* length of source ATM number */ u_char aar_sstl; /* length of source ATM subaddress */ #define ATMARP_IS_E164 0x40 /* bit in type/length for E.164 format */ #define ATMARP_LEN_MASK 0x3F /* length of {sub}address in type/length */ u_short aar_op; /* same as regular ARP */ u_char aar_spln; /* length of source protocol address */ u_char aar_thtl; /* length of target ATM number */ u_char aar_tstl; /* length of target ATM subaddress */ u_char aar_tpln; /* length of target protocol address */ /* * The remaining fields are variable in size, * according to the sizes above. */ #ifdef COMMENT_ONLY u_char aar_sha[]; /* source ATM number */ u_char aar_ssa[]; /* source ATM subaddress */ u_char aar_spa[]; /* sender protocol address */ u_char aar_tha[]; /* target ATM number */ u_char aar_tsa[]; /* target ATM subaddress */ u_char aar_tpa[]; /* target protocol address */ #endif #define ATMHRD(ap) EXTRACT_16BITS(&(ap)->aar_hrd) #define ATMSHRD_LEN(ap) ((ap)->aar_shtl & ATMARP_LEN_MASK) #define ATMSSLN(ap) ((ap)->aar_sstl & ATMARP_LEN_MASK) #define ATMSPROTO_LEN(ap) ((ap)->aar_spln) #define ATMOP(ap) EXTRACT_16BITS(&(ap)->aar_op) #define ATMPRO(ap) EXTRACT_16BITS(&(ap)->aar_pro) #define ATMTHRD_LEN(ap) ((ap)->aar_thtl & ATMARP_LEN_MASK) #define ATMTSLN(ap) ((ap)->aar_tstl & ATMARP_LEN_MASK) #define ATMTPROTO_LEN(ap) ((ap)->aar_tpln) #define aar_sha(ap) ((const u_char *)((ap)+1)) #define aar_ssa(ap) (aar_sha(ap) + ATMSHRD_LEN(ap)) #define aar_spa(ap) (aar_ssa(ap) + ATMSSLN(ap)) #define aar_tha(ap) (aar_spa(ap) + ATMSPROTO_LEN(ap)) #define aar_tsa(ap) (aar_tha(ap) + ATMTHRD_LEN(ap)) #define aar_tpa(ap) (aar_tsa(ap) + ATMTSLN(ap)) }; #define ATMSHA(ap) (aar_sha(ap)) #define ATMSSA(ap) (aar_ssa(ap)) #define ATMSPA(ap) (aar_spa(ap)) #define ATMTHA(ap) (aar_tha(ap)) #define ATMTSA(ap) (aar_tsa(ap)) #define ATMTPA(ap) (aar_tpa(ap)) static int isnonzero(const u_char *a, size_t len) { while (len > 0) { if (*a != 0) return (1); a++; len--; } return (0); } static void atmarp_addr_print(netdissect_options *ndo, const u_char *ha, u_int ha_len, const u_char *srca, u_int srca_len) { if (ha_len == 0) ND_PRINT((ndo, "<No address>")); else { ND_PRINT((ndo, "%s", linkaddr_string(ndo, ha, LINKADDR_ATM, ha_len))); if (srca_len != 0) ND_PRINT((ndo, ",%s", linkaddr_string(ndo, srca, LINKADDR_ATM, srca_len))); } } static void atmarp_print(netdissect_options *ndo, const u_char *bp, u_int length, u_int caplen) { const struct atmarp_pkthdr *ap; u_short pro, hrd, op; ap = (const struct atmarp_pkthdr *)bp; ND_TCHECK(*ap); hrd = ATMHRD(ap); pro = ATMPRO(ap); op = ATMOP(ap); if (!ND_TTEST2(*aar_tpa(ap), ATMTPROTO_LEN(ap))) { ND_PRINT((ndo, "%s", tstr)); ND_DEFAULTPRINT((const u_char *)ap, length); return; } if (!ndo->ndo_eflag) { ND_PRINT((ndo, "ARP, ")); } if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) || ATMSPROTO_LEN(ap) != 4 || ATMTPROTO_LEN(ap) != 4 || ndo->ndo_vflag) { ND_PRINT((ndo, "%s, %s (len %u/%u)", tok2str(arphrd_values, "Unknown Hardware (%u)", hrd), tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro), ATMSPROTO_LEN(ap), ATMTPROTO_LEN(ap))); /* don't know know about the address formats */ if (!ndo->ndo_vflag) { goto out; } } /* print operation */ ND_PRINT((ndo, "%s%s ", ndo->ndo_vflag ? ", " : "", tok2str(arpop_values, "Unknown (%u)", op))); switch (op) { case ARPOP_REQUEST: ND_PRINT((ndo, "who-has %s", ipaddr_string(ndo, ATMTPA(ap)))); if (ATMTHRD_LEN(ap) != 0) { ND_PRINT((ndo, " (")); atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap), ATMTSA(ap), ATMTSLN(ap)); ND_PRINT((ndo, ")")); } ND_PRINT((ndo, "tell %s", ipaddr_string(ndo, ATMSPA(ap)))); break; case ARPOP_REPLY: ND_PRINT((ndo, "%s is-at ", ipaddr_string(ndo, ATMSPA(ap)))); atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap), ATMSSLN(ap)); break; case ARPOP_INVREQUEST: ND_PRINT((ndo, "who-is ")); atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap), ATMTSA(ap), ATMTSLN(ap)); ND_PRINT((ndo, " tell ")); atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap), ATMSSLN(ap)); break; case ARPOP_INVREPLY: atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap), ATMSSLN(ap)); ND_PRINT((ndo, "at %s", ipaddr_string(ndo, ATMSPA(ap)))); break; case ARPOP_NAK: ND_PRINT((ndo, "for %s", ipaddr_string(ndo, ATMSPA(ap)))); break; default: ND_DEFAULTPRINT((const u_char *)ap, caplen); return; } out: ND_PRINT((ndo, ", length %u", length)); return; trunc: ND_PRINT((ndo, "%s", tstr)); } void arp_print(netdissect_options *ndo, const u_char *bp, u_int length, u_int caplen) { const struct arp_pkthdr *ap; u_short pro, hrd, op, linkaddr; ap = (const struct arp_pkthdr *)bp; ND_TCHECK(*ap); hrd = HRD(ap); pro = PRO(ap); op = OP(ap); /* if its ATM then call the ATM ARP printer for Frame-relay ARP most of the fields are similar to Ethernet so overload the Ethernet Printer and set the linkaddr type for linkaddr_string(ndo, ) accordingly */ switch(hrd) { case ARPHRD_ATM2225: atmarp_print(ndo, bp, length, caplen); return; case ARPHRD_FRELAY: linkaddr = LINKADDR_FRELAY; break; default: linkaddr = LINKADDR_ETHER; break; } if (!ND_TTEST2(*ar_tpa(ap), PROTO_LEN(ap))) { ND_PRINT((ndo, "%s", tstr)); ND_DEFAULTPRINT((const u_char *)ap, length); return; } if (!ndo->ndo_eflag) { ND_PRINT((ndo, "ARP, ")); } /* print hardware type/len and proto type/len */ if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) || PROTO_LEN(ap) != 4 || HRD_LEN(ap) == 0 || ndo->ndo_vflag) { ND_PRINT((ndo, "%s (len %u), %s (len %u)", tok2str(arphrd_values, "Unknown Hardware (%u)", hrd), HRD_LEN(ap), tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro), PROTO_LEN(ap))); /* don't know know about the address formats */ if (!ndo->ndo_vflag) { goto out; } } /* print operation */ ND_PRINT((ndo, "%s%s ", ndo->ndo_vflag ? ", " : "", tok2str(arpop_values, "Unknown (%u)", op))); switch (op) { case ARPOP_REQUEST: ND_PRINT((ndo, "who-has %s", ipaddr_string(ndo, TPA(ap)))); if (isnonzero((const u_char *)THA(ap), HRD_LEN(ap))) ND_PRINT((ndo, " (%s)", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)))); ND_PRINT((ndo, " tell %s", ipaddr_string(ndo, SPA(ap)))); break; case ARPOP_REPLY: ND_PRINT((ndo, "%s is-at %s", ipaddr_string(ndo, SPA(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_REVREQUEST: ND_PRINT((ndo, "who-is %s tell %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_REVREPLY: ND_PRINT((ndo, "%s at %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), ipaddr_string(ndo, TPA(ap)))); break; case ARPOP_INVREQUEST: ND_PRINT((ndo, "who-is %s tell %s", linkaddr_string(ndo, THA(ap), linkaddr, HRD_LEN(ap)), linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)))); break; case ARPOP_INVREPLY: ND_PRINT((ndo,"%s at %s", linkaddr_string(ndo, SHA(ap), linkaddr, HRD_LEN(ap)), ipaddr_string(ndo, SPA(ap)))); break; default: ND_DEFAULTPRINT((const u_char *)ap, caplen); return; } out: ND_PRINT((ndo, ", length %u", length)); return; trunc: ND_PRINT((ndo, "%s", tstr)); } /* * Local Variables: * c-style: bsd * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2688_0
crossvul-cpp_data_bad_330_0
/* * Copyright (C) Arnaldo Carvalho de Melo 2004 * Copyright (C) Ian McDonald 2005 * Copyright (C) Yoshifumi Nishida 2005 * * This software may be distributed either under the terms of the * BSD-style license that accompanies tcpdump or the GNU GPL version 2 */ /* \summary: Datagram Congestion Control Protocol (DCCP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* RFC4340: Datagram Congestion Control Protocol (DCCP) */ /** * struct dccp_hdr - generic part of DCCP packet header, with a 24-bit * sequence number * * @dccph_sport - Relevant port on the endpoint that sent this packet * @dccph_dport - Relevant port on the other endpoint * @dccph_doff - Data Offset from the start of the DCCP header, in 32-bit words * @dccph_ccval - Used by the HC-Sender CCID * @dccph_cscov - Parts of the packet that are covered by the Checksum field * @dccph_checksum - Internet checksum, depends on dccph_cscov * @dccph_x - 0 = 24 bit sequence number, 1 = 48 * @dccph_type - packet type, see DCCP_PKT_ prefixed macros * @dccph_seq - 24-bit sequence number */ struct dccp_hdr { uint16_t dccph_sport, dccph_dport; uint8_t dccph_doff; uint8_t dccph_ccval_cscov; uint16_t dccph_checksum; uint8_t dccph_xtr; uint8_t dccph_seq[3]; } UNALIGNED; /** * struct dccp_hdr_ext - generic part of DCCP packet header, with a 48-bit * sequence number * * @dccph_sport - Relevant port on the endpoint that sent this packet * @dccph_dport - Relevant port on the other endpoint * @dccph_doff - Data Offset from the start of the DCCP header, in 32-bit words * @dccph_ccval - Used by the HC-Sender CCID * @dccph_cscov - Parts of the packet that are covered by the Checksum field * @dccph_checksum - Internet checksum, depends on dccph_cscov * @dccph_x - 0 = 24 bit sequence number, 1 = 48 * @dccph_type - packet type, see DCCP_PKT_ prefixed macros * @dccph_seq - 48-bit sequence number */ struct dccp_hdr_ext { uint16_t dccph_sport, dccph_dport; uint8_t dccph_doff; uint8_t dccph_ccval_cscov; uint16_t dccph_checksum; uint8_t dccph_xtr; uint8_t reserved; uint8_t dccph_seq[6]; } UNALIGNED; #define DCCPH_CCVAL(dh) (((dh)->dccph_ccval_cscov >> 4) & 0xF) #define DCCPH_CSCOV(dh) (((dh)->dccph_ccval_cscov) & 0xF) #define DCCPH_X(dh) ((dh)->dccph_xtr & 1) #define DCCPH_TYPE(dh) (((dh)->dccph_xtr >> 1) & 0xF) /** * struct dccp_hdr_request - Conection initiation request header * * @dccph_req_service - Service to which the client app wants to connect */ struct dccp_hdr_request { uint32_t dccph_req_service; } UNALIGNED; /** * struct dccp_hdr_response - Conection initiation response header * * @dccph_resp_ack - 48 bit ack number, contains GSR * @dccph_resp_service - Echoes the Service Code on a received DCCP-Request */ struct dccp_hdr_response { uint8_t dccph_resp_ack[8]; /* always 8 bytes */ uint32_t dccph_resp_service; } UNALIGNED; /** * struct dccp_hdr_reset - Unconditionally shut down a connection * * @dccph_resp_ack - 48 bit ack number * @dccph_reset_service - Echoes the Service Code on a received DCCP-Request */ struct dccp_hdr_reset { uint8_t dccph_reset_ack[8]; /* always 8 bytes */ uint8_t dccph_reset_code, dccph_reset_data[3]; } UNALIGNED; enum dccp_pkt_type { DCCP_PKT_REQUEST = 0, DCCP_PKT_RESPONSE, DCCP_PKT_DATA, DCCP_PKT_ACK, DCCP_PKT_DATAACK, DCCP_PKT_CLOSEREQ, DCCP_PKT_CLOSE, DCCP_PKT_RESET, DCCP_PKT_SYNC, DCCP_PKT_SYNCACK }; static const struct tok dccp_pkt_type_str[] = { { DCCP_PKT_REQUEST, "DCCP-Request" }, { DCCP_PKT_RESPONSE, "DCCP-Response" }, { DCCP_PKT_DATA, "DCCP-Data" }, { DCCP_PKT_ACK, "DCCP-Ack" }, { DCCP_PKT_DATAACK, "DCCP-DataAck" }, { DCCP_PKT_CLOSEREQ, "DCCP-CloseReq" }, { DCCP_PKT_CLOSE, "DCCP-Close" }, { DCCP_PKT_RESET, "DCCP-Reset" }, { DCCP_PKT_SYNC, "DCCP-Sync" }, { DCCP_PKT_SYNCACK, "DCCP-SyncAck" }, { 0, NULL} }; enum dccp_reset_codes { DCCP_RESET_CODE_UNSPECIFIED = 0, DCCP_RESET_CODE_CLOSED, DCCP_RESET_CODE_ABORTED, DCCP_RESET_CODE_NO_CONNECTION, DCCP_RESET_CODE_PACKET_ERROR, DCCP_RESET_CODE_OPTION_ERROR, DCCP_RESET_CODE_MANDATORY_ERROR, DCCP_RESET_CODE_CONNECTION_REFUSED, DCCP_RESET_CODE_BAD_SERVICE_CODE, DCCP_RESET_CODE_TOO_BUSY, DCCP_RESET_CODE_BAD_INIT_COOKIE, DCCP_RESET_CODE_AGGRESSION_PENALTY, __DCCP_RESET_CODE_LAST }; static const char tstr[] = "[|dccp]"; static const char *dccp_reset_codes[] = { "unspecified", "closed", "aborted", "no_connection", "packet_error", "option_error", "mandatory_error", "connection_refused", "bad_service_code", "too_busy", "bad_init_cookie", "aggression_penalty", }; static const char *dccp_feature_nums[] = { "reserved", "ccid", "allow_short_seqno", "sequence_window", "ecn_incapable", "ack_ratio", "send_ack_vector", "send_ndp_count", "minimum checksum coverage", "check data checksum", }; static inline u_int dccp_csum_coverage(const struct dccp_hdr* dh, u_int len) { u_int cov; if (DCCPH_CSCOV(dh) == 0) return len; cov = (dh->dccph_doff + DCCPH_CSCOV(dh) - 1) * sizeof(uint32_t); return (cov > len)? len : cov; } static int dccp_cksum(netdissect_options *ndo, const struct ip *ip, const struct dccp_hdr *dh, u_int len) { return nextproto4_cksum(ndo, ip, (const uint8_t *)(const void *)dh, len, dccp_csum_coverage(dh, len), IPPROTO_DCCP); } static int dccp6_cksum(netdissect_options *ndo, const struct ip6_hdr *ip6, const struct dccp_hdr *dh, u_int len) { return nextproto6_cksum(ndo, ip6, (const uint8_t *)(const void *)dh, len, dccp_csum_coverage(dh, len), IPPROTO_DCCP); } static const char *dccp_reset_code(uint8_t code) { if (code >= __DCCP_RESET_CODE_LAST) return "invalid"; return dccp_reset_codes[code]; } static uint64_t dccp_seqno(const u_char *bp) { const struct dccp_hdr *dh = (const struct dccp_hdr *)bp; uint64_t seqno; if (DCCPH_X(dh) != 0) { const struct dccp_hdr_ext *dhx = (const struct dccp_hdr_ext *)bp; seqno = EXTRACT_48BITS(dhx->dccph_seq); } else { seqno = EXTRACT_24BITS(dh->dccph_seq); } return seqno; } static inline unsigned int dccp_basic_hdr_len(const struct dccp_hdr *dh) { return DCCPH_X(dh) ? sizeof(struct dccp_hdr_ext) : sizeof(struct dccp_hdr); } static void dccp_print_ack_no(netdissect_options *ndo, const u_char *bp) { const struct dccp_hdr *dh = (const struct dccp_hdr *)bp; const u_char *ackp = bp + dccp_basic_hdr_len(dh); uint64_t ackno; if (DCCPH_X(dh) != 0) { ND_TCHECK2(*ackp, 8); ackno = EXTRACT_48BITS(ackp + 2); } else { ND_TCHECK2(*ackp, 4); ackno = EXTRACT_24BITS(ackp + 1); } ND_PRINT((ndo, "(ack=%" PRIu64 ") ", ackno)); trunc: return; } static int dccp_print_option(netdissect_options *, const u_char *, u_int); /** * dccp_print - show dccp packet * @bp - beginning of dccp packet * @data2 - beginning of enclosing * @len - lenght of ip packet */ void dccp_print(netdissect_options *ndo, const u_char *bp, const u_char *data2, u_int len) { const struct dccp_hdr *dh; const struct ip *ip; const struct ip6_hdr *ip6; const u_char *cp; u_short sport, dport; u_int hlen; u_int fixed_hdrlen; uint8_t dccph_type; dh = (const struct dccp_hdr *)bp; ip = (const struct ip *)data2; if (IP_V(ip) == 6) ip6 = (const struct ip6_hdr *)data2; else ip6 = NULL; /* make sure we have enough data to look at the X bit */ cp = (const u_char *)(dh + 1); if (cp > ndo->ndo_snapend) { ND_PRINT((ndo, "[Invalid packet|dccp]")); return; } if (len < sizeof(struct dccp_hdr)) { ND_PRINT((ndo, "truncated-dccp - %u bytes missing!", len - (u_int)sizeof(struct dccp_hdr))); return; } /* get the length of the generic header */ fixed_hdrlen = dccp_basic_hdr_len(dh); if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-dccp - %u bytes missing!", len - fixed_hdrlen)); return; } ND_TCHECK2(*dh, fixed_hdrlen); sport = EXTRACT_16BITS(&dh->dccph_sport); dport = EXTRACT_16BITS(&dh->dccph_dport); hlen = dh->dccph_doff * 4; if (ip6) { ND_PRINT((ndo, "%s.%d > %s.%d: ", ip6addr_string(ndo, &ip6->ip6_src), sport, ip6addr_string(ndo, &ip6->ip6_dst), dport)); } else { ND_PRINT((ndo, "%s.%d > %s.%d: ", ipaddr_string(ndo, &ip->ip_src), sport, ipaddr_string(ndo, &ip->ip_dst), dport)); } ND_PRINT((ndo, "DCCP")); if (ndo->ndo_qflag) { ND_PRINT((ndo, " %d", len - hlen)); if (hlen > len) { ND_PRINT((ndo, " [bad hdr length %u - too long, > %u]", hlen, len)); } return; } /* other variables in generic header */ if (ndo->ndo_vflag) { ND_PRINT((ndo, " (CCVal %d, CsCov %d, ", DCCPH_CCVAL(dh), DCCPH_CSCOV(dh))); } /* checksum calculation */ if (ndo->ndo_vflag && ND_TTEST2(bp[0], len)) { uint16_t sum = 0, dccp_sum; dccp_sum = EXTRACT_16BITS(&dh->dccph_checksum); ND_PRINT((ndo, "cksum 0x%04x ", dccp_sum)); if (IP_V(ip) == 4) sum = dccp_cksum(ndo, ip, dh, len); else if (IP_V(ip) == 6) sum = dccp6_cksum(ndo, ip6, dh, len); if (sum != 0) ND_PRINT((ndo, "(incorrect -> 0x%04x)",in_cksum_shouldbe(dccp_sum, sum))); else ND_PRINT((ndo, "(correct)")); } if (ndo->ndo_vflag) ND_PRINT((ndo, ")")); ND_PRINT((ndo, " ")); dccph_type = DCCPH_TYPE(dh); switch (dccph_type) { case DCCP_PKT_REQUEST: { const struct dccp_hdr_request *dhr = (const struct dccp_hdr_request *)(bp + fixed_hdrlen); fixed_hdrlen += 4; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_TCHECK(*dhr); ND_PRINT((ndo, "%s (service=%d) ", tok2str(dccp_pkt_type_str, "", dccph_type), EXTRACT_32BITS(&dhr->dccph_req_service))); break; } case DCCP_PKT_RESPONSE: { const struct dccp_hdr_response *dhr = (const struct dccp_hdr_response *)(bp + fixed_hdrlen); fixed_hdrlen += 12; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_TCHECK(*dhr); ND_PRINT((ndo, "%s (service=%d) ", tok2str(dccp_pkt_type_str, "", dccph_type), EXTRACT_32BITS(&dhr->dccph_resp_service))); break; } case DCCP_PKT_DATA: ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type))); break; case DCCP_PKT_ACK: { fixed_hdrlen += 8; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type))); break; } case DCCP_PKT_DATAACK: { fixed_hdrlen += 8; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type))); break; } case DCCP_PKT_CLOSEREQ: fixed_hdrlen += 8; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type))); break; case DCCP_PKT_CLOSE: fixed_hdrlen += 8; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type))); break; case DCCP_PKT_RESET: { const struct dccp_hdr_reset *dhr = (const struct dccp_hdr_reset *)(bp + fixed_hdrlen); fixed_hdrlen += 12; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_TCHECK(*dhr); ND_PRINT((ndo, "%s (code=%s) ", tok2str(dccp_pkt_type_str, "", dccph_type), dccp_reset_code(dhr->dccph_reset_code))); break; } case DCCP_PKT_SYNC: fixed_hdrlen += 8; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type))); break; case DCCP_PKT_SYNCACK: fixed_hdrlen += 8; if (len < fixed_hdrlen) { ND_PRINT((ndo, "truncated-%s - %u bytes missing!", tok2str(dccp_pkt_type_str, "", dccph_type), len - fixed_hdrlen)); return; } ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type))); break; default: ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "unknown-type-%u", dccph_type))); break; } if ((DCCPH_TYPE(dh) != DCCP_PKT_DATA) && (DCCPH_TYPE(dh) != DCCP_PKT_REQUEST)) dccp_print_ack_no(ndo, bp); if (ndo->ndo_vflag < 2) return; ND_PRINT((ndo, "seq %" PRIu64, dccp_seqno(bp))); /* process options */ if (hlen > fixed_hdrlen){ u_int optlen; cp = bp + fixed_hdrlen; ND_PRINT((ndo, " <")); hlen -= fixed_hdrlen; while(1){ optlen = dccp_print_option(ndo, cp, hlen); if (!optlen) break; if (hlen <= optlen) break; hlen -= optlen; cp += optlen; ND_PRINT((ndo, ", ")); } ND_PRINT((ndo, ">")); } return; trunc: ND_PRINT((ndo, "%s", tstr)); return; } static const struct tok dccp_option_values[] = { { 0, "nop" }, { 1, "mandatory" }, { 2, "slowreceiver" }, { 32, "change_l" }, { 33, "confirm_l" }, { 34, "change_r" }, { 35, "confirm_r" }, { 36, "initcookie" }, { 37, "ndp_count" }, { 38, "ack_vector0" }, { 39, "ack_vector1" }, { 40, "data_dropped" }, { 41, "timestamp" }, { 42, "timestamp_echo" }, { 43, "elapsed_time" }, { 44, "data_checksum" }, { 0, NULL } }; static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen) { uint8_t optlen, i; ND_TCHECK(*option); if (*option >= 32) { ND_TCHECK(*(option+1)); optlen = *(option +1); if (optlen < 2) { if (*option >= 128) ND_PRINT((ndo, "CCID option %u optlen too short", *option)); else ND_PRINT((ndo, "%s optlen too short", tok2str(dccp_option_values, "Option %u", *option))); return 0; } } else optlen = 1; if (hlen < optlen) { if (*option >= 128) ND_PRINT((ndo, "CCID option %u optlen goes past header length", *option)); else ND_PRINT((ndo, "%s optlen goes past header length", tok2str(dccp_option_values, "Option %u", *option))); return 0; } ND_TCHECK2(*option, optlen); if (*option >= 128) { ND_PRINT((ndo, "CCID option %d", *option)); switch (optlen) { case 4: ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2))); break; case 6: ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); break; default: break; } } else { ND_PRINT((ndo, "%s", tok2str(dccp_option_values, "Option %u", *option))); switch (*option) { case 32: case 33: case 34: case 35: if (optlen < 3) { ND_PRINT((ndo, " optlen too short")); return optlen; } if (*(option + 2) < 10){ ND_PRINT((ndo, " %s", dccp_feature_nums[*(option + 2)])); for (i = 0; i < optlen - 3; i++) ND_PRINT((ndo, " %d", *(option + 3 + i))); } break; case 36: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 37: for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, " %d", *(option + 2 + i))); break; case 38: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 39: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 40: if (optlen > 2) { ND_PRINT((ndo, " 0x")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; case 41: if (optlen == 4) ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); else ND_PRINT((ndo, " optlen != 4")); break; case 42: if (optlen == 4) ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); else ND_PRINT((ndo, " optlen != 4")); break; case 43: if (optlen == 6) ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2))); else if (optlen == 4) ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2))); else ND_PRINT((ndo, " optlen != 4 or 6")); break; case 44: if (optlen > 2) { ND_PRINT((ndo, " ")); for (i = 0; i < optlen - 2; i++) ND_PRINT((ndo, "%02x", *(option + 2 + i))); } break; } } return optlen; trunc: ND_PRINT((ndo, "%s", tstr)); return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_330_0
crossvul-cpp_data_bad_2443_0
/* * plistutil.c * Simple tool to convert a plist into different formats * * Copyright (c) 2009-2015 Martin Szulecki All Rights Reserved. * Copyright (c) 2008 Zach C. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plist/plist.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #ifdef _MSC_VER #pragma warning(disable:4996) #endif typedef struct _options { char *in_file, *out_file; uint8_t debug, in_fmt, out_fmt; } options_t; static void print_usage(int argc, char *argv[]) { char *name = NULL; name = strrchr(argv[0], '/'); printf("Usage: %s -i|--infile FILE [-o|--outfile FILE] [-d|--debug]\n", (name ? name + 1: argv[0])); printf("Convert a plist FILE from binary to XML format or vice-versa.\n\n"); printf(" -i, --infile FILE\tThe FILE to convert from\n"); printf(" -o, --outfile FILE\tOptional FILE to convert to or stdout if not used\n"); printf(" -d, --debug\t\tEnable extended debug output\n"); printf("\n"); } static options_t *parse_arguments(int argc, char *argv[]) { int i = 0; options_t *options = (options_t *) malloc(sizeof(options_t)); memset(options, 0, sizeof(options_t)); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "--infile") || !strcmp(argv[i], "-i")) { if ((i + 1) == argc) { free(options); return NULL; } options->in_file = argv[i + 1]; i++; continue; } if (!strcmp(argv[i], "--outfile") || !strcmp(argv[i], "-o")) { if ((i + 1) == argc) { free(options); return NULL; } options->out_file = argv[i + 1]; i++; continue; } if (!strcmp(argv[i], "--debug") || !strcmp(argv[i], "-d")) { options->debug = 1; } if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { free(options); return NULL; } } if (!options->in_file) { free(options); return NULL; } return options; } int main(int argc, char *argv[]) { FILE *iplist = NULL; plist_t root_node = NULL; char *plist_out = NULL; uint32_t size = 0; int read_size = 0; char *plist_entire = NULL; struct stat filestats; options_t *options = parse_arguments(argc, argv); if (!options) { print_usage(argc, argv); return 0; } // read input file iplist = fopen(options->in_file, "rb"); if (!iplist) { free(options); return 1; } stat(options->in_file, &filestats); plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); fclose(iplist); // convert from binary to xml or vice-versa if (memcmp(plist_entire, "bplist00", 8) == 0) { plist_from_bin(plist_entire, read_size, &root_node); plist_to_xml(root_node, &plist_out, &size); } else { plist_from_xml(plist_entire, read_size, &root_node); plist_to_bin(root_node, &plist_out, &size); } plist_free(root_node); free(plist_entire); if (plist_out) { if (options->out_file != NULL) { FILE *oplist = fopen(options->out_file, "wb"); if (!oplist) { free(options); return 1; } fwrite(plist_out, size, sizeof(char), oplist); fclose(oplist); } // if no output file specified, write to stdout else fwrite(plist_out, size, sizeof(char), stdout); free(plist_out); } else printf("ERROR: Failed to convert input file.\n"); free(options); return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2443_0
crossvul-cpp_data_bad_2729_0
/* * Copyright (C) 1999 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 /* draft-ietf-idr-shutdown-07 */ #define BGP_NOTIFY_MINOR_CEASE_SHUT 2 #define BGP_NOTIFY_MINOR_CEASE_RESET 4 #define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"}, { 3, "Peer Unconfigured"}, { BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 0, "Unspecified Error"}, { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (0 == plen) { snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; plen-=32; /* adjust prefix length */ if (64 < plen) return -1; memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[1], (plen + 7) / 8); memcpy(&route_target, &pptr[1], (plen + 7) / 8); if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, { 0, NULL} }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN + 4; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (tptr < pptr + len) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; ND_TCHECK2(tptr[0], 5); tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; tlen = len; while (tlen >= 3) { ND_TCHECK2(tptr[0], 3); type = *tptr; length = EXTRACT_16BITS(tptr+1); tptr += 3; tlen -= 3; ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); if (length < 3) goto trunc; length -= 3; /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length); switch (type) { case BGP_AIGP_TLV: if (length < 8) goto trunc; ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr,"\n\t ", length); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; uint8_t shutdown_comm_length; uint8_t remainder_offset; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } /* * draft-ietf-idr-shutdown describes a method to send a communication * intended for human consumption regarding the Administrative Shutdown */ if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT || bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) && length >= BGP_NOTIFICATION_SIZE + 1) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 1); shutdown_comm_length = *(tptr); remainder_offset = 0; /* garbage, hexdump it all */ if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN || shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) { ND_PRINT((ndo, ", invalid Shutdown Communication length")); } else if (shutdown_comm_length == 0) { ND_PRINT((ndo, ", empty Shutdown Communication")); remainder_offset += 1; } /* a proper shutdown communication */ else { ND_TCHECK2(*(tptr+1), shutdown_comm_length); ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length)); (void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL); ND_PRINT((ndo, "\"")); remainder_offset += shutdown_comm_length + 1; } /* if there is trailing data, hexdump it */ if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) { ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE))); hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE)); } } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2729_0
crossvul-cpp_data_good_2712_0
/* * Copyright (c) 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * OSPF support contributed by Jeffrey Honig (jch@mitchell.cit.cornell.edu) */ /* \summary: IPv6 Open Shortest Path First (OSPFv3) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ospf.h" #define OSPF_TYPE_HELLO 1 /* Hello */ #define OSPF_TYPE_DD 2 /* Database Description */ #define OSPF_TYPE_LS_REQ 3 /* Link State Request */ #define OSPF_TYPE_LS_UPDATE 4 /* Link State Update */ #define OSPF_TYPE_LS_ACK 5 /* Link State Ack */ /* Options *_options */ #define OSPF6_OPTION_V6 0x01 /* V6 bit: A bit for peeping tom */ #define OSPF6_OPTION_E 0x02 /* E bit: External routes advertised */ #define OSPF6_OPTION_MC 0x04 /* MC bit: Multicast capable */ #define OSPF6_OPTION_N 0x08 /* N bit: For type-7 LSA */ #define OSPF6_OPTION_R 0x10 /* R bit: Router bit */ #define OSPF6_OPTION_DC 0x20 /* DC bit: Demand circuits */ /* The field is actually 24-bit (RFC5340 Section A.2). */ #define OSPF6_OPTION_AF 0x0100 /* AF bit: Multiple address families */ #define OSPF6_OPTION_L 0x0200 /* L bit: Link-local signaling (LLS) */ #define OSPF6_OPTION_AT 0x0400 /* AT bit: Authentication trailer */ /* db_flags */ #define OSPF6_DB_INIT 0x04 /* */ #define OSPF6_DB_MORE 0x02 #define OSPF6_DB_MASTER 0x01 #define OSPF6_DB_M6 0x10 /* IPv6 MTU */ /* ls_type */ #define LS_TYPE_ROUTER 1 /* router link */ #define LS_TYPE_NETWORK 2 /* network link */ #define LS_TYPE_INTER_AP 3 /* Inter-Area-Prefix */ #define LS_TYPE_INTER_AR 4 /* Inter-Area-Router */ #define LS_TYPE_ASE 5 /* ASE */ #define LS_TYPE_GROUP 6 /* Group membership */ #define LS_TYPE_NSSA 7 /* NSSA */ #define LS_TYPE_LINK 8 /* Link LSA */ #define LS_TYPE_INTRA_AP 9 /* Intra-Area-Prefix */ #define LS_TYPE_INTRA_ATE 10 /* Intra-Area-TE */ #define LS_TYPE_GRACE 11 /* Grace LSA */ #define LS_TYPE_RI 12 /* Router information */ #define LS_TYPE_INTER_ASTE 13 /* Inter-AS-TE */ #define LS_TYPE_L1VPN 14 /* L1VPN */ #define LS_TYPE_MASK 0x1fff #define LS_SCOPE_LINKLOCAL 0x0000 #define LS_SCOPE_AREA 0x2000 #define LS_SCOPE_AS 0x4000 #define LS_SCOPE_MASK 0x6000 #define LS_SCOPE_U 0x8000 /* rla_link.link_type */ #define RLA_TYPE_ROUTER 1 /* point-to-point to another router */ #define RLA_TYPE_TRANSIT 2 /* connection to transit network */ #define RLA_TYPE_VIRTUAL 4 /* virtual link */ /* rla_flags */ #define RLA_FLAG_B 0x01 #define RLA_FLAG_E 0x02 #define RLA_FLAG_V 0x04 #define RLA_FLAG_W 0x08 #define RLA_FLAG_N 0x10 /* lsa_prefix options */ #define LSA_PREFIX_OPT_NU 0x01 #define LSA_PREFIX_OPT_LA 0x02 #define LSA_PREFIX_OPT_MC 0x04 #define LSA_PREFIX_OPT_P 0x08 #define LSA_PREFIX_OPT_DN 0x10 /* sla_tosmetric breakdown */ #define SLA_MASK_TOS 0x7f000000 #define SLA_MASK_METRIC 0x00ffffff #define SLA_SHIFT_TOS 24 /* asla_metric */ #define ASLA_FLAG_FWDADDR 0x02000000 #define ASLA_FLAG_ROUTETAG 0x01000000 #define ASLA_MASK_METRIC 0x00ffffff /* RFC6506 Section 4.1 */ #define OSPF6_AT_HDRLEN 16U #define OSPF6_AUTH_TYPE_HMAC 0x0001 typedef uint32_t rtrid_t; /* link state advertisement header */ struct lsa6_hdr { uint16_t ls_age; uint16_t ls_type; rtrid_t ls_stateid; rtrid_t ls_router; uint32_t ls_seq; uint16_t ls_chksum; uint16_t ls_length; }; /* Length of an IPv6 address, in bytes. */ #define IPV6_ADDR_LEN_BYTES (128/8) struct lsa6_prefix { uint8_t lsa_p_len; uint8_t lsa_p_opt; uint16_t lsa_p_metric; uint8_t lsa_p_prefix[IPV6_ADDR_LEN_BYTES]; /* maximum length */ }; /* link state advertisement */ struct lsa6 { struct lsa6_hdr ls_hdr; /* Link state types */ union { /* Router links advertisements */ struct { union { uint8_t flg; uint32_t opt; } rla_flgandopt; #define rla_flags rla_flgandopt.flg #define rla_options rla_flgandopt.opt struct rlalink6 { uint8_t link_type; uint8_t link_zero[1]; uint16_t link_metric; uint32_t link_ifid; uint32_t link_nifid; rtrid_t link_nrtid; } rla_link[1]; /* may repeat */ } un_rla; /* Network links advertisements */ struct { uint32_t nla_options; rtrid_t nla_router[1]; /* may repeat */ } un_nla; /* Inter Area Prefix LSA */ struct { uint32_t inter_ap_metric; struct lsa6_prefix inter_ap_prefix[1]; } un_inter_ap; /* AS external links advertisements */ struct { uint32_t asla_metric; struct lsa6_prefix asla_prefix[1]; /* some optional fields follow */ } un_asla; #if 0 /* Summary links advertisements */ struct { struct in_addr sla_mask; uint32_t sla_tosmetric[1]; /* may repeat */ } un_sla; /* Multicast group membership */ struct mcla { uint32_t mcla_vtype; struct in_addr mcla_vid; } un_mcla[1]; #endif /* Type 7 LSA */ /* Link LSA */ struct llsa { union { uint8_t pri; uint32_t opt; } llsa_priandopt; #define llsa_priority llsa_priandopt.pri #define llsa_options llsa_priandopt.opt struct in6_addr llsa_lladdr; uint32_t llsa_nprefix; struct lsa6_prefix llsa_prefix[1]; } un_llsa; /* Intra-Area-Prefix */ struct { uint16_t intra_ap_nprefix; uint16_t intra_ap_lstype; rtrid_t intra_ap_lsid; rtrid_t intra_ap_rtid; struct lsa6_prefix intra_ap_prefix[1]; } un_intra_ap; } lsa_un; }; /* * the main header */ struct ospf6hdr { uint8_t ospf6_version; uint8_t ospf6_type; uint16_t ospf6_len; rtrid_t ospf6_routerid; rtrid_t ospf6_areaid; uint16_t ospf6_chksum; uint8_t ospf6_instanceid; uint8_t ospf6_rsvd; }; /* * The OSPF6 header length is 16 bytes, regardless of how your compiler * might choose to pad the above structure. */ #define OSPF6HDR_LEN 16 /* Hello packet */ struct hello6 { uint32_t hello_ifid; union { uint8_t pri; uint32_t opt; } hello_priandopt; #define hello_priority hello_priandopt.pri #define hello_options hello_priandopt.opt uint16_t hello_helloint; uint16_t hello_deadint; rtrid_t hello_dr; rtrid_t hello_bdr; rtrid_t hello_neighbor[1]; /* may repeat */ }; /* Database Description packet */ struct dd6 { uint32_t db_options; uint16_t db_mtu; uint8_t db_mbz; uint8_t db_flags; uint32_t db_seq; struct lsa6_hdr db_lshdr[1]; /* may repeat */ }; /* Link State Request */ struct lsr6 { uint16_t ls_mbz; uint16_t ls_type; rtrid_t ls_stateid; rtrid_t ls_router; }; /* Link State Update */ struct lsu6 { uint32_t lsu_count; struct lsa6 lsu_lsa[1]; /* may repeat */ }; static const char tstr[] = " [|ospf3]"; static const struct tok ospf6_option_values[] = { { OSPF6_OPTION_V6, "V6" }, { OSPF6_OPTION_E, "External" }, { OSPF6_OPTION_MC, "Deprecated" }, { OSPF6_OPTION_N, "NSSA" }, { OSPF6_OPTION_R, "Router" }, { OSPF6_OPTION_DC, "Demand Circuit" }, { OSPF6_OPTION_AF, "AFs Support" }, { OSPF6_OPTION_L, "LLS" }, { OSPF6_OPTION_AT, "Authentication Trailer" }, { 0, NULL } }; static const struct tok ospf6_rla_flag_values[] = { { RLA_FLAG_B, "ABR" }, { RLA_FLAG_E, "External" }, { RLA_FLAG_V, "Virtual-Link Endpoint" }, { RLA_FLAG_W, "Wildcard Receiver" }, { RLA_FLAG_N, "NSSA Translator" }, { 0, NULL } }; static const struct tok ospf6_asla_flag_values[] = { { ASLA_FLAG_EXTERNAL, "External Type 2" }, { ASLA_FLAG_FWDADDR, "Forwarding" }, { ASLA_FLAG_ROUTETAG, "Tag" }, { 0, NULL } }; static const struct tok ospf6_type_values[] = { { OSPF_TYPE_HELLO, "Hello" }, { OSPF_TYPE_DD, "Database Description" }, { OSPF_TYPE_LS_REQ, "LS-Request" }, { OSPF_TYPE_LS_UPDATE, "LS-Update" }, { OSPF_TYPE_LS_ACK, "LS-Ack" }, { 0, NULL } }; static const struct tok ospf6_lsa_values[] = { { LS_TYPE_ROUTER, "Router" }, { LS_TYPE_NETWORK, "Network" }, { LS_TYPE_INTER_AP, "Inter-Area Prefix" }, { LS_TYPE_INTER_AR, "Inter-Area Router" }, { LS_TYPE_ASE, "External" }, { LS_TYPE_GROUP, "Deprecated" }, { LS_TYPE_NSSA, "NSSA" }, { LS_TYPE_LINK, "Link" }, { LS_TYPE_INTRA_AP, "Intra-Area Prefix" }, { LS_TYPE_INTRA_ATE, "Intra-Area TE" }, { LS_TYPE_GRACE, "Grace" }, { LS_TYPE_RI, "Router Information" }, { LS_TYPE_INTER_ASTE, "Inter-AS-TE" }, { LS_TYPE_L1VPN, "Layer 1 VPN" }, { 0, NULL } }; static const struct tok ospf6_ls_scope_values[] = { { LS_SCOPE_LINKLOCAL, "Link Local" }, { LS_SCOPE_AREA, "Area Local" }, { LS_SCOPE_AS, "Domain Wide" }, { 0, NULL } }; static const struct tok ospf6_dd_flag_values[] = { { OSPF6_DB_INIT, "Init" }, { OSPF6_DB_MORE, "More" }, { OSPF6_DB_MASTER, "Master" }, { OSPF6_DB_M6, "IPv6 MTU" }, { 0, NULL } }; static const struct tok ospf6_lsa_prefix_option_values[] = { { LSA_PREFIX_OPT_NU, "No Unicast" }, { LSA_PREFIX_OPT_LA, "Local address" }, { LSA_PREFIX_OPT_MC, "Deprecated" }, { LSA_PREFIX_OPT_P, "Propagate" }, { LSA_PREFIX_OPT_DN, "Down" }, { 0, NULL } }; static const struct tok ospf6_auth_type_str[] = { { OSPF6_AUTH_TYPE_HMAC, "HMAC" }, { 0, NULL } }; static void ospf6_print_ls_type(netdissect_options *ndo, register u_int ls_type, register const rtrid_t *ls_stateid) { ND_PRINT((ndo, "\n\t %s LSA (%d), %s Scope%s, LSA-ID %s", tok2str(ospf6_lsa_values, "Unknown", ls_type & LS_TYPE_MASK), ls_type & LS_TYPE_MASK, tok2str(ospf6_ls_scope_values, "Unknown", ls_type & LS_SCOPE_MASK), ls_type &0x8000 ? ", transitive" : "", /* U-bit */ ipaddr_string(ndo, ls_stateid))); } static int ospf6_print_lshdr(netdissect_options *ndo, register const struct lsa6_hdr *lshp, const u_char *dataend) { if ((const u_char *)(lshp + 1) > dataend) goto trunc; ND_TCHECK(lshp->ls_type); ND_TCHECK(lshp->ls_seq); ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u", ipaddr_string(ndo, &lshp->ls_router), EXTRACT_32BITS(&lshp->ls_seq), EXTRACT_16BITS(&lshp->ls_age), EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid); return (0); trunc: return (1); } static int ospf6_print_lsaprefix(netdissect_options *ndo, const uint8_t *tptr, u_int lsa_length) { const struct lsa6_prefix *lsapp = (const struct lsa6_prefix *)tptr; u_int wordlen; struct in6_addr prefix; if (lsa_length < sizeof (*lsapp) - IPV6_ADDR_LEN_BYTES) goto trunc; lsa_length -= sizeof (*lsapp) - IPV6_ADDR_LEN_BYTES; ND_TCHECK2(*lsapp, sizeof (*lsapp) - IPV6_ADDR_LEN_BYTES); wordlen = (lsapp->lsa_p_len + 31) / 32; if (wordlen * 4 > sizeof(struct in6_addr)) { ND_PRINT((ndo, " bogus prefixlen /%d", lsapp->lsa_p_len)); goto trunc; } if (lsa_length < wordlen * 4) goto trunc; lsa_length -= wordlen * 4; ND_TCHECK2(lsapp->lsa_p_prefix, wordlen * 4); memset(&prefix, 0, sizeof(prefix)); memcpy(&prefix, lsapp->lsa_p_prefix, wordlen * 4); ND_PRINT((ndo, "\n\t\t%s/%d", ip6addr_string(ndo, &prefix), lsapp->lsa_p_len)); if (lsapp->lsa_p_opt) { ND_PRINT((ndo, ", Options [%s]", bittok2str(ospf6_lsa_prefix_option_values, "none", lsapp->lsa_p_opt))); } ND_PRINT((ndo, ", metric %u", EXTRACT_16BITS(&lsapp->lsa_p_metric))); return sizeof(*lsapp) - IPV6_ADDR_LEN_BYTES + wordlen * 4; trunc: return -1; } /* * Print a single link state advertisement. If truncated return 1, else 0. */ static int ospf6_print_lsa(netdissect_options *ndo, register const struct lsa6 *lsap, const u_char *dataend) { register const struct rlalink6 *rlp; #if 0 register const struct tos_metric *tosp; #endif register const rtrid_t *ap; #if 0 register const struct aslametric *almp; register const struct mcla *mcp; #endif register const struct llsa *llsap; register const struct lsa6_prefix *lsapp; #if 0 register const uint32_t *lp; #endif register u_int prefixes; register int bytelen; register u_int length, lsa_length; uint32_t flags32; const uint8_t *tptr; if (ospf6_print_lshdr(ndo, &lsap->ls_hdr, dataend)) return (1); ND_TCHECK(lsap->ls_hdr.ls_length); length = EXTRACT_16BITS(&lsap->ls_hdr.ls_length); /* * The LSA length includes the length of the header; * it must have a value that's at least that length. * If it does, find the length of what follows the * header. */ if (length < sizeof(struct lsa6_hdr) || (const u_char *)lsap + length > dataend) return (1); lsa_length = length - sizeof(struct lsa6_hdr); tptr = (const uint8_t *)lsap+sizeof(struct lsa6_hdr); switch (EXTRACT_16BITS(&lsap->ls_hdr.ls_type)) { case LS_TYPE_ROUTER | LS_SCOPE_AREA: if (lsa_length < sizeof (lsap->lsa_un.un_rla.rla_options)) return (1); lsa_length -= sizeof (lsap->lsa_un.un_rla.rla_options); ND_TCHECK(lsap->lsa_un.un_rla.rla_options); ND_PRINT((ndo, "\n\t Options [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&lsap->lsa_un.un_rla.rla_options)))); ND_PRINT((ndo, ", RLA-Flags [%s]", bittok2str(ospf6_rla_flag_values, "none", lsap->lsa_un.un_rla.rla_flags))); rlp = lsap->lsa_un.un_rla.rla_link; while (lsa_length != 0) { if (lsa_length < sizeof (*rlp)) return (1); lsa_length -= sizeof (*rlp); ND_TCHECK(*rlp); switch (rlp->link_type) { case RLA_TYPE_VIRTUAL: ND_PRINT((ndo, "\n\t Virtual Link: Neighbor Router-ID %s" "\n\t Neighbor Interface-ID %s, Interface %s", ipaddr_string(ndo, &rlp->link_nrtid), ipaddr_string(ndo, &rlp->link_nifid), ipaddr_string(ndo, &rlp->link_ifid))); break; case RLA_TYPE_ROUTER: ND_PRINT((ndo, "\n\t Neighbor Router-ID %s" "\n\t Neighbor Interface-ID %s, Interface %s", ipaddr_string(ndo, &rlp->link_nrtid), ipaddr_string(ndo, &rlp->link_nifid), ipaddr_string(ndo, &rlp->link_ifid))); break; case RLA_TYPE_TRANSIT: ND_PRINT((ndo, "\n\t Neighbor Network-ID %s" "\n\t Neighbor Interface-ID %s, Interface %s", ipaddr_string(ndo, &rlp->link_nrtid), ipaddr_string(ndo, &rlp->link_nifid), ipaddr_string(ndo, &rlp->link_ifid))); break; default: ND_PRINT((ndo, "\n\t Unknown Router Links Type 0x%02x", rlp->link_type)); return (0); } ND_PRINT((ndo, ", metric %d", EXTRACT_16BITS(&rlp->link_metric))); rlp++; } break; case LS_TYPE_NETWORK | LS_SCOPE_AREA: if (lsa_length < sizeof (lsap->lsa_un.un_nla.nla_options)) return (1); lsa_length -= sizeof (lsap->lsa_un.un_nla.nla_options); ND_TCHECK(lsap->lsa_un.un_nla.nla_options); ND_PRINT((ndo, "\n\t Options [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&lsap->lsa_un.un_nla.nla_options)))); ND_PRINT((ndo, "\n\t Connected Routers:")); ap = lsap->lsa_un.un_nla.nla_router; while (lsa_length != 0) { if (lsa_length < sizeof (*ap)) return (1); lsa_length -= sizeof (*ap); ND_TCHECK(*ap); ND_PRINT((ndo, "\n\t\t%s", ipaddr_string(ndo, ap))); ++ap; } break; case LS_TYPE_INTER_AP | LS_SCOPE_AREA: if (lsa_length < sizeof (lsap->lsa_un.un_inter_ap.inter_ap_metric)) return (1); lsa_length -= sizeof (lsap->lsa_un.un_inter_ap.inter_ap_metric); ND_TCHECK(lsap->lsa_un.un_inter_ap.inter_ap_metric); ND_PRINT((ndo, ", metric %u", EXTRACT_32BITS(&lsap->lsa_un.un_inter_ap.inter_ap_metric) & SLA_MASK_METRIC)); tptr = (const uint8_t *)lsap->lsa_un.un_inter_ap.inter_ap_prefix; while (lsa_length != 0) { bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length); if (bytelen < 0) goto trunc; lsa_length -= bytelen; tptr += bytelen; } break; case LS_TYPE_ASE | LS_SCOPE_AS: if (lsa_length < sizeof (lsap->lsa_un.un_asla.asla_metric)) return (1); lsa_length -= sizeof (lsap->lsa_un.un_asla.asla_metric); ND_TCHECK(lsap->lsa_un.un_asla.asla_metric); flags32 = EXTRACT_32BITS(&lsap->lsa_un.un_asla.asla_metric); ND_PRINT((ndo, "\n\t Flags [%s]", bittok2str(ospf6_asla_flag_values, "none", flags32))); ND_PRINT((ndo, " metric %u", EXTRACT_32BITS(&lsap->lsa_un.un_asla.asla_metric) & ASLA_MASK_METRIC)); tptr = (const uint8_t *)lsap->lsa_un.un_asla.asla_prefix; lsapp = (const struct lsa6_prefix *)tptr; bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length); if (bytelen < 0) goto trunc; lsa_length -= bytelen; tptr += bytelen; if ((flags32 & ASLA_FLAG_FWDADDR) != 0) { const struct in6_addr *fwdaddr6; fwdaddr6 = (const struct in6_addr *)tptr; if (lsa_length < sizeof (*fwdaddr6)) return (1); lsa_length -= sizeof (*fwdaddr6); ND_TCHECK(*fwdaddr6); ND_PRINT((ndo, " forward %s", ip6addr_string(ndo, fwdaddr6))); tptr += sizeof(*fwdaddr6); } if ((flags32 & ASLA_FLAG_ROUTETAG) != 0) { if (lsa_length < sizeof (uint32_t)) return (1); lsa_length -= sizeof (uint32_t); ND_TCHECK(*(const uint32_t *)tptr); ND_PRINT((ndo, " tag %s", ipaddr_string(ndo, (const uint32_t *)tptr))); tptr += sizeof(uint32_t); } if (lsapp->lsa_p_metric) { if (lsa_length < sizeof (uint32_t)) return (1); lsa_length -= sizeof (uint32_t); ND_TCHECK(*(const uint32_t *)tptr); ND_PRINT((ndo, " RefLSID: %s", ipaddr_string(ndo, (const uint32_t *)tptr))); tptr += sizeof(uint32_t); } break; case LS_TYPE_LINK: /* Link LSA */ llsap = &lsap->lsa_un.un_llsa; if (lsa_length < sizeof (llsap->llsa_priandopt)) return (1); lsa_length -= sizeof (llsap->llsa_priandopt); ND_TCHECK(llsap->llsa_priandopt); ND_PRINT((ndo, "\n\t Options [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&llsap->llsa_options)))); if (lsa_length < sizeof (llsap->llsa_lladdr) + sizeof (llsap->llsa_nprefix)) return (1); lsa_length -= sizeof (llsap->llsa_lladdr) + sizeof (llsap->llsa_nprefix); prefixes = EXTRACT_32BITS(&llsap->llsa_nprefix); ND_PRINT((ndo, "\n\t Priority %d, Link-local address %s, Prefixes %d:", llsap->llsa_priority, ip6addr_string(ndo, &llsap->llsa_lladdr), prefixes)); tptr = (const uint8_t *)llsap->llsa_prefix; while (prefixes > 0) { bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length); if (bytelen < 0) goto trunc; prefixes--; lsa_length -= bytelen; tptr += bytelen; } break; case LS_TYPE_INTRA_AP | LS_SCOPE_AREA: /* Intra-Area-Prefix LSA */ if (lsa_length < sizeof (lsap->lsa_un.un_intra_ap.intra_ap_rtid)) return (1); lsa_length -= sizeof (lsap->lsa_un.un_intra_ap.intra_ap_rtid); ND_TCHECK(lsap->lsa_un.un_intra_ap.intra_ap_rtid); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lsap->lsa_un.un_intra_ap.intra_ap_lstype), &lsap->lsa_un.un_intra_ap.intra_ap_lsid); if (lsa_length < sizeof (lsap->lsa_un.un_intra_ap.intra_ap_nprefix)) return (1); lsa_length -= sizeof (lsap->lsa_un.un_intra_ap.intra_ap_nprefix); ND_TCHECK(lsap->lsa_un.un_intra_ap.intra_ap_nprefix); prefixes = EXTRACT_16BITS(&lsap->lsa_un.un_intra_ap.intra_ap_nprefix); ND_PRINT((ndo, "\n\t Prefixes %d:", prefixes)); tptr = (const uint8_t *)lsap->lsa_un.un_intra_ap.intra_ap_prefix; while (prefixes > 0) { bytelen = ospf6_print_lsaprefix(ndo, tptr, lsa_length); if (bytelen < 0) goto trunc; prefixes--; lsa_length -= bytelen; tptr += bytelen; } break; case LS_TYPE_GRACE | LS_SCOPE_LINKLOCAL: if (ospf_print_grace_lsa(ndo, tptr, lsa_length) == -1) { return 1; } break; case LS_TYPE_INTRA_ATE | LS_SCOPE_LINKLOCAL: if (ospf_print_te_lsa(ndo, tptr, lsa_length) == -1) { return 1; } break; default: if(!print_unknown_data(ndo,tptr, "\n\t ", lsa_length)) { return (1); } break; } return (0); trunc: return (1); } static int ospf6_decode_v3(netdissect_options *ndo, register const struct ospf6hdr *op, register const u_char *dataend) { register const rtrid_t *ap; register const struct lsr6 *lsrp; register const struct lsa6_hdr *lshp; register const struct lsa6 *lsap; register int i; switch (op->ospf6_type) { case OSPF_TYPE_HELLO: { register const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK_32BITS(&hellop->hello_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&hellop->hello_options)))); ND_TCHECK(hellop->hello_deadint); ND_PRINT((ndo, "\n\t Hello Timer %us, Dead Timer %us, Interface-ID %s, Priority %u", EXTRACT_16BITS(&hellop->hello_helloint), EXTRACT_16BITS(&hellop->hello_deadint), ipaddr_string(ndo, &hellop->hello_ifid), hellop->hello_priority)); ND_TCHECK(hellop->hello_dr); if (EXTRACT_32BITS(&hellop->hello_dr) != 0) ND_PRINT((ndo, "\n\t Designated Router %s", ipaddr_string(ndo, &hellop->hello_dr))); ND_TCHECK(hellop->hello_bdr); if (EXTRACT_32BITS(&hellop->hello_bdr) != 0) ND_PRINT((ndo, ", Backup Designated Router %s", ipaddr_string(ndo, &hellop->hello_bdr))); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, "\n\t Neighbor List:")); ap = hellop->hello_neighbor; while ((const u_char *)ap < dataend) { ND_TCHECK(*ap); ND_PRINT((ndo, "\n\t %s", ipaddr_string(ndo, ap))); ++ap; } } break; /* HELLO */ } case OSPF_TYPE_DD: { register const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(ddp->db_options); ND_PRINT((ndo, "\n\tOptions [%s]", bittok2str(ospf6_option_values, "none", EXTRACT_32BITS(&ddp->db_options)))); ND_TCHECK(ddp->db_flags); ND_PRINT((ndo, ", DD Flags [%s]", bittok2str(ospf6_dd_flag_values,"none",ddp->db_flags))); ND_TCHECK(ddp->db_seq); ND_PRINT((ndo, ", MTU %u, DD-Sequence 0x%08x", EXTRACT_16BITS(&ddp->db_mtu), EXTRACT_32BITS(&ddp->db_seq))); if (ndo->ndo_vflag > 1) { /* Print all the LS adv's */ lshp = ddp->db_lshdr; while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; } case OSPF_TYPE_LS_REQ: if (ndo->ndo_vflag > 1) { lsrp = (const struct lsr6 *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lsrp < dataend) { ND_TCHECK(*lsrp); ND_PRINT((ndo, "\n\t Advertising Router %s", ipaddr_string(ndo, &lsrp->ls_router))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lsrp->ls_type), &lsrp->ls_stateid); ++lsrp; } } break; case OSPF_TYPE_LS_UPDATE: if (ndo->ndo_vflag > 1) { register const struct lsu6 *lsup = (const struct lsu6 *)((const uint8_t *)op + OSPF6HDR_LEN); ND_TCHECK(lsup->lsu_count); i = EXTRACT_32BITS(&lsup->lsu_count); lsap = lsup->lsu_lsa; while ((const u_char *)lsap < dataend && i--) { if (ospf6_print_lsa(ndo, lsap, dataend)) goto trunc; lsap = (const struct lsa6 *)((const u_char *)lsap + EXTRACT_16BITS(&lsap->ls_hdr.ls_length)); } } break; case OSPF_TYPE_LS_ACK: if (ndo->ndo_vflag > 1) { lshp = (const struct lsa6_hdr *)((const uint8_t *)op + OSPF6HDR_LEN); while ((const u_char *)lshp < dataend) { if (ospf6_print_lshdr(ndo, lshp++, dataend)) goto trunc; } } break; default: break; } return (0); trunc: return (1); } /* RFC5613 Section 2.2 (w/o the TLVs) */ static int ospf6_print_lls(netdissect_options *ndo, const u_char *cp, const u_int len) { uint16_t llsdatalen; if (len == 0) return 0; if (len < OSPF_LLS_HDRLEN) goto trunc; /* Checksum */ ND_TCHECK2(*cp, 2); ND_PRINT((ndo, "\n\tLLS Checksum 0x%04x", EXTRACT_16BITS(cp))); cp += 2; /* LLS Data Length */ ND_TCHECK2(*cp, 2); llsdatalen = EXTRACT_16BITS(cp); ND_PRINT((ndo, ", Data Length %u", llsdatalen)); if (llsdatalen < OSPF_LLS_HDRLEN || llsdatalen > len) goto trunc; cp += 2; /* LLS TLVs */ ND_TCHECK2(*cp, llsdatalen - OSPF_LLS_HDRLEN); /* FIXME: code in print-ospf.c can be reused to decode the TLVs */ return llsdatalen; trunc: return -1; } /* RFC6506 Section 4.1 */ static int ospf6_decode_at(netdissect_options *ndo, const u_char *cp, const u_int len) { uint16_t authdatalen; if (len == 0) return 0; if (len < OSPF6_AT_HDRLEN) goto trunc; /* Authentication Type */ ND_TCHECK2(*cp, 2); ND_PRINT((ndo, "\n\tAuthentication Type %s", tok2str(ospf6_auth_type_str, "unknown (0x%04x)", EXTRACT_16BITS(cp)))); cp += 2; /* Auth Data Len */ ND_TCHECK2(*cp, 2); authdatalen = EXTRACT_16BITS(cp); ND_PRINT((ndo, ", Length %u", authdatalen)); if (authdatalen < OSPF6_AT_HDRLEN || authdatalen > len) goto trunc; cp += 2; /* Reserved */ ND_TCHECK2(*cp, 2); cp += 2; /* Security Association ID */ ND_TCHECK2(*cp, 2); ND_PRINT((ndo, ", SAID %u", EXTRACT_16BITS(cp))); cp += 2; /* Cryptographic Sequence Number (High-Order 32 Bits) */ ND_TCHECK2(*cp, 4); ND_PRINT((ndo, ", CSN 0x%08x", EXTRACT_32BITS(cp))); cp += 4; /* Cryptographic Sequence Number (Low-Order 32 Bits) */ ND_TCHECK2(*cp, 4); ND_PRINT((ndo, ":%08x", EXTRACT_32BITS(cp))); cp += 4; /* Authentication Data */ ND_TCHECK2(*cp, authdatalen - OSPF6_AT_HDRLEN); if (ndo->ndo_vflag > 1) print_unknown_data(ndo,cp, "\n\tAuthentication Data ", authdatalen - OSPF6_AT_HDRLEN); return 0; trunc: return 1; } /* The trailing data may include LLS and/or AT data (in this specific order). * LLS data may be present only in Hello and DBDesc packets with the L-bit set. * AT data may be present in Hello and DBDesc packets with the AT-bit set or in * any other packet type, thus decode the AT data regardless of the AT-bit. */ static int ospf6_decode_v3_trailer(netdissect_options *ndo, const struct ospf6hdr *op, const u_char *cp, const unsigned len) { int llslen = 0; int lls_hello = 0; int lls_dd = 0; if (op->ospf6_type == OSPF_TYPE_HELLO) { const struct hello6 *hellop = (const struct hello6 *)((const uint8_t *)op + OSPF6HDR_LEN); if (EXTRACT_32BITS(&hellop->hello_options) & OSPF6_OPTION_L) lls_hello = 1; } else if (op->ospf6_type == OSPF_TYPE_DD) { const struct dd6 *ddp = (const struct dd6 *)((const uint8_t *)op + OSPF6HDR_LEN); if (EXTRACT_32BITS(&ddp->db_options) & OSPF6_OPTION_L) lls_dd = 1; } if ((lls_hello || lls_dd) && (llslen = ospf6_print_lls(ndo, cp, len)) < 0) goto trunc; return ospf6_decode_at(ndo, cp + llslen, len - llslen); trunc: return 1; } void ospf6_print(netdissect_options *ndo, register const u_char *bp, register u_int length) { register const struct ospf6hdr *op; register const u_char *dataend; register const char *cp; uint16_t datalen; op = (const struct ospf6hdr *)bp; /* If the type is valid translate it, or just print the type */ /* value. If it's not valid, say so and return */ ND_TCHECK(op->ospf6_type); cp = tok2str(ospf6_type_values, "unknown packet type (%u)", op->ospf6_type); ND_PRINT((ndo, "OSPFv%u, %s, length %d", op->ospf6_version, cp, length)); if (*cp == 'u') { return; } if(!ndo->ndo_vflag) { /* non verbose - so lets bail out here */ return; } /* OSPFv3 data always comes first and optional trailing data may follow. */ ND_TCHECK(op->ospf6_len); datalen = EXTRACT_16BITS(&op->ospf6_len); if (datalen > length) { ND_PRINT((ndo, " [len %d]", datalen)); return; } dataend = bp + datalen; ND_TCHECK(op->ospf6_routerid); ND_PRINT((ndo, "\n\tRouter-ID %s", ipaddr_string(ndo, &op->ospf6_routerid))); ND_TCHECK(op->ospf6_areaid); if (EXTRACT_32BITS(&op->ospf6_areaid) != 0) ND_PRINT((ndo, ", Area %s", ipaddr_string(ndo, &op->ospf6_areaid))); else ND_PRINT((ndo, ", Backbone Area")); ND_TCHECK(op->ospf6_instanceid); if (op->ospf6_instanceid) ND_PRINT((ndo, ", Instance %u", op->ospf6_instanceid)); /* Do rest according to version. */ switch (op->ospf6_version) { case 3: /* ospf version 3 */ if (ospf6_decode_v3(ndo, op, dataend) || ospf6_decode_v3_trailer(ndo, op, dataend, length - datalen)) goto trunc; break; } /* end switch on version */ return; trunc: ND_PRINT((ndo, "%s", tstr)); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2712_0
crossvul-cpp_data_bad_3068_0
/* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/opensslconf.h> #include <openssl/crypto.h> #include <openssl/evp.h> #include <openssl/err.h> #include <string.h> #include <assert.h> #include <openssl/aes.h> #include "internal/evp_int.h" #include "modes_lcl.h" #include <openssl/rand.h> #include "evp_locl.h" typedef struct { union { double align; AES_KEY ks; } ks; block128_f block; union { cbc128_f cbc; ctr128_f ctr; } stream; } EVP_AES_KEY; typedef struct { union { double align; AES_KEY ks; } ks; /* AES key schedule to use */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ GCM128_CONTEXT gcm; unsigned char *iv; /* Temporary IV store */ int ivlen; /* IV length */ int taglen; int iv_gen; /* It is OK to generate IVs */ int tls_aad_len; /* TLS AAD length */ ctr128_f ctr; } EVP_AES_GCM_CTX; typedef struct { union { double align; AES_KEY ks; } ks1, ks2; /* AES key schedules to use */ XTS128_CONTEXT xts; void (*stream) (const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); } EVP_AES_XTS_CTX; typedef struct { union { double align; AES_KEY ks; } ks; /* AES key schedule to use */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ int tag_set; /* Set if tag is valid */ int len_set; /* Set if message length set */ int L, M; /* L and M parameters from RFC3610 */ int tls_aad_len; /* TLS AAD length */ CCM128_CONTEXT ccm; ccm128_f str; } EVP_AES_CCM_CTX; #ifndef OPENSSL_NO_OCB typedef struct { union { double align; AES_KEY ks; } ksenc; /* AES key schedule to use for encryption */ union { double align; AES_KEY ks; } ksdec; /* AES key schedule to use for decryption */ int key_set; /* Set if key initialised */ int iv_set; /* Set if an iv is set */ OCB128_CONTEXT ocb; unsigned char *iv; /* Temporary IV store */ unsigned char tag[16]; unsigned char data_buf[16]; /* Store partial data blocks */ unsigned char aad_buf[16]; /* Store partial AAD blocks */ int data_buf_len; int aad_buf_len; int ivlen; /* IV length */ int taglen; } EVP_AES_OCB_CTX; #endif #define MAXBITCHUNK ((size_t)1<<(sizeof(size_t)*8-4)) #ifdef VPAES_ASM int vpaes_set_encrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); int vpaes_set_decrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); void vpaes_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); void vpaes_decrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); void vpaes_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key, unsigned char *ivec, int enc); #endif #ifdef BSAES_ASM void bsaes_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key, unsigned char ivec[16], int enc); void bsaes_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, const unsigned char ivec[16]); void bsaes_xts_encrypt(const unsigned char *inp, unsigned char *out, size_t len, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); void bsaes_xts_decrypt(const unsigned char *inp, unsigned char *out, size_t len, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); #endif #ifdef AES_CTR_ASM void AES_ctr32_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key, const unsigned char ivec[AES_BLOCK_SIZE]); #endif #ifdef AES_XTS_ASM void AES_xts_encrypt(const char *inp, char *out, size_t len, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); void AES_xts_decrypt(const char *inp, char *out, size_t len, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); #endif #if defined(OPENSSL_CPUID_OBJ) && (defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC)) # include "ppc_arch.h" # ifdef VPAES_ASM # define VPAES_CAPABLE (OPENSSL_ppccap_P & PPC_ALTIVEC) # endif # define HWAES_CAPABLE (OPENSSL_ppccap_P & PPC_CRYPTO207) # define HWAES_set_encrypt_key aes_p8_set_encrypt_key # define HWAES_set_decrypt_key aes_p8_set_decrypt_key # define HWAES_encrypt aes_p8_encrypt # define HWAES_decrypt aes_p8_decrypt # define HWAES_cbc_encrypt aes_p8_cbc_encrypt # define HWAES_ctr32_encrypt_blocks aes_p8_ctr32_encrypt_blocks # define HWAES_xts_encrypt aes_p8_xts_encrypt # define HWAES_xts_decrypt aes_p8_xts_decrypt #endif #if defined(AES_ASM) && !defined(I386_ONLY) && ( \ ((defined(__i386) || defined(__i386__) || \ defined(_M_IX86)) && defined(OPENSSL_IA32_SSE2))|| \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) ) extern unsigned int OPENSSL_ia32cap_P[]; # ifdef VPAES_ASM # define VPAES_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(41-32))) # endif # ifdef BSAES_ASM # define BSAES_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(41-32))) # endif /* * AES-NI section */ # define AESNI_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(57-32))) int aesni_set_encrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); int aesni_set_decrypt_key(const unsigned char *userKey, int bits, AES_KEY *key); void aesni_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); void aesni_decrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); void aesni_ecb_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key, int enc); void aesni_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key, unsigned char *ivec, int enc); void aesni_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out, size_t blocks, const void *key, const unsigned char *ivec); void aesni_xts_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); void aesni_xts_decrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); void aesni_ccm64_encrypt_blocks(const unsigned char *in, unsigned char *out, size_t blocks, const void *key, const unsigned char ivec[16], unsigned char cmac[16]); void aesni_ccm64_decrypt_blocks(const unsigned char *in, unsigned char *out, size_t blocks, const void *key, const unsigned char ivec[16], unsigned char cmac[16]); # if defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64) size_t aesni_gcm_encrypt(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], u64 *Xi); # define AES_gcm_encrypt aesni_gcm_encrypt size_t aesni_gcm_decrypt(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], u64 *Xi); # define AES_gcm_decrypt aesni_gcm_decrypt void gcm_ghash_avx(u64 Xi[2], const u128 Htable[16], const u8 *in, size_t len); # define AES_GCM_ASM(gctx) (gctx->ctr==aesni_ctr32_encrypt_blocks && \ gctx->gcm.ghash==gcm_ghash_avx) # define AES_GCM_ASM2(gctx) (gctx->gcm.block==(block128_f)aesni_encrypt && \ gctx->gcm.ghash==gcm_ghash_avx) # undef AES_GCM_ASM2 /* minor size optimization */ # endif static int aesni_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); mode = EVP_CIPHER_CTX_mode(ctx); if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { ret = aesni_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) aesni_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aesni_cbc_encrypt : NULL; } else { ret = aesni_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) aesni_encrypt; if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aesni_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aesni_ctr32_encrypt_blocks; else dat->stream.cbc = NULL; } if (ret < 0) { EVPerr(EVP_F_AESNI_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED); return 0; } return 1; } static int aesni_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { aesni_cbc_encrypt(in, out, len, &EVP_C_DATA(EVP_AES_KEY,ctx)->ks.ks, EVP_CIPHER_CTX_iv_noconst(ctx), EVP_CIPHER_CTX_encrypting(ctx)); return 1; } static int aesni_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { size_t bl = EVP_CIPHER_CTX_block_size(ctx); if (len < bl) return 1; aesni_ecb_encrypt(in, out, len, &EVP_C_DATA(EVP_AES_KEY,ctx)->ks.ks, EVP_CIPHER_CTX_encrypting(ctx)); return 1; } # define aesni_ofb_cipher aes_ofb_cipher static int aesni_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_cfb_cipher aes_cfb_cipher static int aesni_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_cfb8_cipher aes_cfb8_cipher static int aesni_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_cfb1_cipher aes_cfb1_cipher static int aesni_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aesni_ctr_cipher aes_ctr_cipher static int aesni_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aesni_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); if (!iv && !key) return 1; if (key) { aesni_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aesni_encrypt); gctx->ctr = (ctr128_f) aesni_ctr32_encrypt_blocks; /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } # define aesni_gcm_cipher aes_gcm_cipher static int aesni_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aesni_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (!iv && !key) return 1; if (key) { /* key_len is two AES keys */ if (enc) { aesni_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aesni_encrypt; xctx->stream = aesni_xts_encrypt; } else { aesni_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aesni_decrypt; xctx->stream = aesni_xts_decrypt; } aesni_set_encrypt_key(key + EVP_CIPHER_CTX_key_length(ctx) / 2, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) aesni_encrypt; xctx->xts.key1 = &xctx->ks1; } if (iv) { xctx->xts.key2 = &xctx->ks2; memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, 16); } return 1; } # define aesni_xts_cipher aes_xts_cipher static int aesni_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aesni_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); if (!iv && !key) return 1; if (key) { aesni_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) aesni_encrypt); cctx->str = enc ? (ccm128_f) aesni_ccm64_encrypt_blocks : (ccm128_f) aesni_ccm64_decrypt_blocks; cctx->key_set = 1; } if (iv) { memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, 15 - cctx->L); cctx->iv_set = 1; } return 1; } # define aesni_ccm_cipher aes_ccm_cipher static int aesni_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # ifndef OPENSSL_NO_OCB void aesni_ocb_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const void *key, size_t start_block_num, unsigned char offset_i[16], const unsigned char L_[][16], unsigned char checksum[16]); void aesni_ocb_decrypt(const unsigned char *in, unsigned char *out, size_t blocks, const void *key, size_t start_block_num, unsigned char offset_i[16], const unsigned char L_[][16], unsigned char checksum[16]); static int aesni_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); if (!iv && !key) return 1; if (key) { do { /* * We set both the encrypt and decrypt key here because decrypt * needs both. We could possibly optimise to remove setting the * decrypt for an encryption operation. */ aesni_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksenc.ks); aesni_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) aesni_encrypt, (block128_f) aesni_decrypt, enc ? aesni_ocb_encrypt : aesni_ocb_decrypt)) return 0; } while (0); /* * If we have an iv we can set it directly, otherwise use saved IV. */ if (iv == NULL && octx->iv_set) iv = octx->iv; if (iv) { if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen) != 1) return 0; octx->iv_set = 1; } octx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (octx->key_set) CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen); else memcpy(octx->iv, iv, octx->ivlen); octx->iv_set = 1; } return 1; } # define aesni_ocb_cipher aes_ocb_cipher static int aesni_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # endif /* OPENSSL_NO_OCB */ # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER aesni_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aesni_init_key, \ aesni_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize, \ keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_init_key, \ aes_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; } # define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \ static const EVP_CIPHER aesni_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aesni_##mode##_init_key, \ aesni_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_##mode##_init_key, \ aes_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return AESNI_CAPABLE?&aesni_##keylen##_##mode:&aes_##keylen##_##mode; } #elif defined(AES_ASM) && (defined(__sparc) || defined(__sparc__)) # include "sparc_arch.h" extern unsigned int OPENSSL_sparcv9cap_P[]; /* * Initial Fujitsu SPARC64 X support */ # define HWAES_CAPABLE (OPENSSL_sparcv9cap_P[0] & SPARCV9_FJAESX) # define HWAES_set_encrypt_key aes_fx_set_encrypt_key # define HWAES_set_decrypt_key aes_fx_set_decrypt_key # define HWAES_encrypt aes_fx_encrypt # define HWAES_decrypt aes_fx_decrypt # define HWAES_cbc_encrypt aes_fx_cbc_encrypt # define HWAES_ctr32_encrypt_blocks aes_fx_ctr32_encrypt_blocks # define SPARC_AES_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_AES) void aes_t4_set_encrypt_key(const unsigned char *key, int bits, AES_KEY *ks); void aes_t4_set_decrypt_key(const unsigned char *key, int bits, AES_KEY *ks); void aes_t4_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); void aes_t4_decrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); /* * Key-length specific subroutines were chosen for following reason. * Each SPARC T4 core can execute up to 8 threads which share core's * resources. Loading as much key material to registers allows to * minimize references to shared memory interface, as well as amount * of instructions in inner loops [much needed on T4]. But then having * non-key-length specific routines would require conditional branches * either in inner loops or on subroutines' entries. Former is hardly * acceptable, while latter means code size increase to size occupied * by multiple key-length specific subroutines, so why fight? */ void aes128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec); void aes128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec); void aes192_t4_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec); void aes192_t4_cbc_decrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec); void aes256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec); void aes256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec); void aes128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key, unsigned char *ivec); void aes192_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key, unsigned char *ivec); void aes256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key, unsigned char *ivec); void aes128_t4_xts_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key1, const AES_KEY *key2, const unsigned char *ivec); void aes128_t4_xts_decrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key1, const AES_KEY *key2, const unsigned char *ivec); void aes256_t4_xts_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key1, const AES_KEY *key2, const unsigned char *ivec); void aes256_t4_xts_decrypt(const unsigned char *in, unsigned char *out, size_t blocks, const AES_KEY *key1, const AES_KEY *key2, const unsigned char *ivec); static int aes_t4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode, bits; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); mode = EVP_CIPHER_CTX_mode(ctx); bits = EVP_CIPHER_CTX_key_length(ctx) * 8; if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { ret = 0; aes_t4_set_decrypt_key(key, bits, &dat->ks.ks); dat->block = (block128_f) aes_t4_decrypt; switch (bits) { case 128: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aes128_t4_cbc_decrypt : NULL; break; case 192: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aes192_t4_cbc_decrypt : NULL; break; case 256: dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) aes256_t4_cbc_decrypt : NULL; break; default: ret = -1; } } else { ret = 0; aes_t4_set_encrypt_key(key, bits, &dat->ks.ks); dat->block = (block128_f) aes_t4_encrypt; switch (bits) { case 128: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aes128_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aes128_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; case 192: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aes192_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aes192_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; case 256: if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) aes256_t4_cbc_encrypt; else if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) aes256_t4_ctr32_encrypt; else dat->stream.cbc = NULL; break; default: ret = -1; } } if (ret < 0) { EVPerr(EVP_F_AES_T4_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED); return 0; } return 1; } # define aes_t4_cbc_cipher aes_cbc_cipher static int aes_t4_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_ecb_cipher aes_ecb_cipher static int aes_t4_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_ofb_cipher aes_ofb_cipher static int aes_t4_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_cfb_cipher aes_cfb_cipher static int aes_t4_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_cfb8_cipher aes_cfb8_cipher static int aes_t4_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_cfb1_cipher aes_cfb1_cipher static int aes_t4_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # define aes_t4_ctr_cipher aes_ctr_cipher static int aes_t4_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aes_t4_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); if (!iv && !key) return 1; if (key) { int bits = EVP_CIPHER_CTX_key_length(ctx) * 8; aes_t4_set_encrypt_key(key, bits, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aes_t4_encrypt); switch (bits) { case 128: gctx->ctr = (ctr128_f) aes128_t4_ctr32_encrypt; break; case 192: gctx->ctr = (ctr128_f) aes192_t4_ctr32_encrypt; break; case 256: gctx->ctr = (ctr128_f) aes256_t4_ctr32_encrypt; break; default: return 0; } /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } # define aes_t4_gcm_cipher aes_gcm_cipher static int aes_t4_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aes_t4_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (!iv && !key) return 1; if (key) { int bits = EVP_CIPHER_CTX_key_length(ctx) * 4; xctx->stream = NULL; /* key_len is two AES keys */ if (enc) { aes_t4_set_encrypt_key(key, bits, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aes_t4_encrypt; switch (bits) { case 128: xctx->stream = aes128_t4_xts_encrypt; break; case 256: xctx->stream = aes256_t4_xts_encrypt; break; default: return 0; } } else { aes_t4_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) aes_t4_decrypt; switch (bits) { case 128: xctx->stream = aes128_t4_xts_decrypt; break; case 256: xctx->stream = aes256_t4_xts_decrypt; break; default: return 0; } } aes_t4_set_encrypt_key(key + EVP_CIPHER_CTX_key_length(ctx) / 2, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) aes_t4_encrypt; xctx->xts.key1 = &xctx->ks1; } if (iv) { xctx->xts.key2 = &xctx->ks2; memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, 16); } return 1; } # define aes_t4_xts_cipher aes_xts_cipher static int aes_t4_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); static int aes_t4_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); if (!iv && !key) return 1; if (key) { int bits = EVP_CIPHER_CTX_key_length(ctx) * 8; aes_t4_set_encrypt_key(key, bits, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) aes_t4_encrypt); cctx->str = NULL; cctx->key_set = 1; } if (iv) { memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, 15 - cctx->L); cctx->iv_set = 1; } return 1; } # define aes_t4_ccm_cipher aes_ccm_cipher static int aes_t4_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # ifndef OPENSSL_NO_OCB static int aes_t4_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); if (!iv && !key) return 1; if (key) { do { /* * We set both the encrypt and decrypt key here because decrypt * needs both. We could possibly optimise to remove setting the * decrypt for an encryption operation. */ aes_t4_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksenc.ks); aes_t4_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) aes_t4_encrypt, (block128_f) aes_t4_decrypt, NULL)) return 0; } while (0); /* * If we have an iv we can set it directly, otherwise use saved IV. */ if (iv == NULL && octx->iv_set) iv = octx->iv; if (iv) { if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen) != 1) return 0; octx->iv_set = 1; } octx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (octx->key_set) CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen); else memcpy(octx->iv, iv, octx->ivlen); octx->iv_set = 1; } return 1; } # define aes_t4_ocb_cipher aes_ocb_cipher static int aes_t4_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len); # endif /* OPENSSL_NO_OCB */ # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER aes_t4_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_t4_init_key, \ aes_t4_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize, \ keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_init_key, \ aes_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; } # define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \ static const EVP_CIPHER aes_t4_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_t4_##mode##_init_key, \ aes_t4_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_##mode##_init_key, \ aes_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return SPARC_AES_CAPABLE?&aes_t4_##keylen##_##mode:&aes_##keylen##_##mode; } #else # define BLOCK_CIPHER_generic(nid,keylen,blocksize,ivlen,nmode,mode,MODE,flags) \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##nmode,blocksize,keylen/8,ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_init_key, \ aes_##mode##_cipher, \ NULL, \ sizeof(EVP_AES_KEY), \ NULL,NULL,NULL,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return &aes_##keylen##_##mode; } # define BLOCK_CIPHER_custom(nid,keylen,blocksize,ivlen,mode,MODE,flags) \ static const EVP_CIPHER aes_##keylen##_##mode = { \ nid##_##keylen##_##mode,blocksize, \ (EVP_CIPH_##MODE##_MODE==EVP_CIPH_XTS_MODE?2:1)*keylen/8, ivlen, \ flags|EVP_CIPH_##MODE##_MODE, \ aes_##mode##_init_key, \ aes_##mode##_cipher, \ aes_##mode##_cleanup, \ sizeof(EVP_AES_##MODE##_CTX), \ NULL,NULL,aes_##mode##_ctrl,NULL }; \ const EVP_CIPHER *EVP_aes_##keylen##_##mode(void) \ { return &aes_##keylen##_##mode; } #endif #if defined(OPENSSL_CPUID_OBJ) && (defined(__arm__) || defined(__arm) || defined(__aarch64__)) # include "arm_arch.h" # if __ARM_MAX_ARCH__>=7 # if defined(BSAES_ASM) # define BSAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON) # endif # if defined(VPAES_ASM) # define VPAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON) # endif # define HWAES_CAPABLE (OPENSSL_armcap_P & ARMV8_AES) # define HWAES_set_encrypt_key aes_v8_set_encrypt_key # define HWAES_set_decrypt_key aes_v8_set_decrypt_key # define HWAES_encrypt aes_v8_encrypt # define HWAES_decrypt aes_v8_decrypt # define HWAES_cbc_encrypt aes_v8_cbc_encrypt # define HWAES_ctr32_encrypt_blocks aes_v8_ctr32_encrypt_blocks # endif #endif #if defined(HWAES_CAPABLE) int HWAES_set_encrypt_key(const unsigned char *userKey, const int bits, AES_KEY *key); int HWAES_set_decrypt_key(const unsigned char *userKey, const int bits, AES_KEY *key); void HWAES_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); void HWAES_decrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); void HWAES_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t length, const AES_KEY *key, unsigned char *ivec, const int enc); void HWAES_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, const unsigned char ivec[16]); void HWAES_xts_encrypt(const unsigned char *inp, unsigned char *out, size_t len, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); void HWAES_xts_decrypt(const unsigned char *inp, unsigned char *out, size_t len, const AES_KEY *key1, const AES_KEY *key2, const unsigned char iv[16]); #endif #define BLOCK_CIPHER_generic_pack(nid,keylen,flags) \ BLOCK_CIPHER_generic(nid,keylen,16,16,cbc,cbc,CBC,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,16,0,ecb,ecb,ECB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,ofb128,ofb,OFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb128,cfb,CFB,flags|EVP_CIPH_FLAG_DEFAULT_ASN1) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb1,cfb1,CFB,flags) \ BLOCK_CIPHER_generic(nid,keylen,1,16,cfb8,cfb8,CFB,flags) \ BLOCK_CIPHER_generic(nid,keylen,1,16,ctr,ctr,CTR,flags) static int aes_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { int ret, mode; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); mode = EVP_CIPHER_CTX_mode(ctx); if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE) && !enc) { #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { ret = HWAES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) HWAES_decrypt; dat->stream.cbc = NULL; # ifdef HWAES_cbc_encrypt if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt; # endif } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE && mode == EVP_CIPH_CBC_MODE) { ret = AES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) AES_decrypt; dat->stream.cbc = (cbc128_f) bsaes_cbc_encrypt; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { ret = vpaes_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) vpaes_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) vpaes_cbc_encrypt : NULL; } else #endif { ret = AES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) AES_decrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) AES_cbc_encrypt : NULL; } } else #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { ret = HWAES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) HWAES_encrypt; dat->stream.cbc = NULL; # ifdef HWAES_cbc_encrypt if (mode == EVP_CIPH_CBC_MODE) dat->stream.cbc = (cbc128_f) HWAES_cbc_encrypt; else # endif # ifdef HWAES_ctr32_encrypt_blocks if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks; else # endif (void)0; /* terminate potentially open 'else' */ } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE && mode == EVP_CIPH_CTR_MODE) { ret = AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) AES_encrypt; dat->stream.ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { ret = vpaes_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) vpaes_encrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) vpaes_cbc_encrypt : NULL; } else #endif { ret = AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &dat->ks.ks); dat->block = (block128_f) AES_encrypt; dat->stream.cbc = mode == EVP_CIPH_CBC_MODE ? (cbc128_f) AES_cbc_encrypt : NULL; #ifdef AES_CTR_ASM if (mode == EVP_CIPH_CTR_MODE) dat->stream.ctr = (ctr128_f) AES_ctr32_encrypt; #endif } if (ret < 0) { EVPerr(EVP_F_AES_INIT_KEY, EVP_R_AES_KEY_SETUP_FAILED); return 0; } return 1; } static int aes_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (dat->stream.cbc) (*dat->stream.cbc) (in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), EVP_CIPHER_CTX_encrypting(ctx)); else if (EVP_CIPHER_CTX_encrypting(ctx)) CRYPTO_cbc128_encrypt(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), dat->block); else CRYPTO_cbc128_decrypt(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), dat->block); return 1; } static int aes_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { size_t bl = EVP_CIPHER_CTX_block_size(ctx); size_t i; EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (len < bl) return 1; for (i = 0, len -= bl; i <= len; i += bl) (*dat->block) (in + i, out + i, &dat->ks); return 1; } static int aes_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); int num = EVP_CIPHER_CTX_num(ctx); CRYPTO_ofb128_encrypt(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int aes_cfb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); int num = EVP_CIPHER_CTX_num(ctx); CRYPTO_cfb128_encrypt(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), &num, EVP_CIPHER_CTX_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int aes_cfb8_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); int num = EVP_CIPHER_CTX_num(ctx); CRYPTO_cfb128_8_encrypt(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), &num, EVP_CIPHER_CTX_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } static int aes_cfb1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) { int num = EVP_CIPHER_CTX_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), &num, EVP_CIPHER_CTX_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } while (len >= MAXBITCHUNK) { int num = EVP_CIPHER_CTX_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, MAXBITCHUNK * 8, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), &num, EVP_CIPHER_CTX_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); len -= MAXBITCHUNK; } if (len) { int num = EVP_CIPHER_CTX_num(ctx); CRYPTO_cfb128_1_encrypt(in, out, len * 8, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), &num, EVP_CIPHER_CTX_encrypting(ctx), dat->block); EVP_CIPHER_CTX_set_num(ctx, num); } return 1; } static int aes_ctr_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { unsigned int num = EVP_CIPHER_CTX_num(ctx); EVP_AES_KEY *dat = EVP_C_DATA(EVP_AES_KEY,ctx); if (dat->stream.ctr) CRYPTO_ctr128_encrypt_ctr32(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->stream.ctr); else CRYPTO_ctr128_encrypt(in, out, len, &dat->ks, EVP_CIPHER_CTX_iv_noconst(ctx), EVP_CIPHER_CTX_buf_noconst(ctx), &num, dat->block); EVP_CIPHER_CTX_set_num(ctx, num); return 1; } BLOCK_CIPHER_generic_pack(NID_aes, 128, 0) BLOCK_CIPHER_generic_pack(NID_aes, 192, 0) BLOCK_CIPHER_generic_pack(NID_aes, 256, 0) static int aes_gcm_cleanup(EVP_CIPHER_CTX *c) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); OPENSSL_cleanse(&gctx->gcm, sizeof(gctx->gcm)); if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c)) OPENSSL_free(gctx->iv); return 1; } /* increment counter (64-bit int) by 1 */ static void ctr64_inc(unsigned char *counter) { int n = 8; unsigned char c; do { --n; c = counter[n]; ++c; counter[n] = c; if (c) return; } while (n); } static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = EVP_CIPHER_CTX_iv_length(c); gctx->iv = EVP_CIPHER_CTX_iv_noconst(c); gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; /* Allocate memory for IV if needed */ if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) { if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c)) OPENSSL_free(gctx->iv); gctx->iv = OPENSSL_malloc(arg); if (gctx->iv == NULL) return 0; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c) || gctx->taglen < 0) return 0; memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); if (EVP_CIPHER_CTX_encrypting(c) && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: if (gctx->iv_gen == 0 || gctx->key_set == 0 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->tls_aad_len = arg; { unsigned int len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= EVP_GCM_TLS_TAG_LEN; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out); if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) return 0; gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c)) gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out); else { gctx_out->iv = OPENSSL_malloc(gctx->ivlen); if (gctx_out->iv == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } } static int aes_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); if (!iv && !key) return 1; if (key) { do { #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { HWAES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) HWAES_encrypt); # ifdef HWAES_ctr32_encrypt_blocks gctx->ctr = (ctr128_f) HWAES_ctr32_encrypt_blocks; # else gctx->ctr = NULL; # endif break; } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE) { AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) AES_encrypt); gctx->ctr = (ctr128_f) bsaes_ctr32_encrypt_blocks; break; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { vpaes_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) vpaes_encrypt); gctx->ctr = NULL; break; } else #endif (void)0; /* terminate potentially open 'else' */ AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) AES_encrypt); #ifdef AES_CTR_ASM gctx->ctr = (ctr128_f) AES_ctr32_encrypt; #else gctx->ctr = NULL; #endif } while (0); /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } /* * Handle TLS GCM packet format. This consists of the last portion of the IV * followed by the payload and finally the tag. On encrypt generate IV, * encrypt payload and write the tag. On verify retrieve IV, decrypt payload * and verify tag. */ static int aes_gcm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); int rv = -1; /* Encrypt/decrypt must be performed in place */ if (out != in || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN)) return -1; /* * Set IV from start of buffer or generate IV and write to start of * buffer. */ if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CIPHER_CTX_encrypting(ctx) ? EVP_CTRL_GCM_IV_GEN : EVP_CTRL_GCM_SET_IV_INV, EVP_GCM_TLS_EXPLICIT_IV_LEN, out) <= 0) goto err; /* Use saved AAD */ if (CRYPTO_gcm128_aad(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), gctx->tls_aad_len)) goto err; /* Fix buffer and length to point to payload */ in += EVP_GCM_TLS_EXPLICIT_IV_LEN; out += EVP_GCM_TLS_EXPLICIT_IV_LEN; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; if (EVP_CIPHER_CTX_encrypting(ctx)) { /* Encrypt payload */ if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 32 && AES_GCM_ASM(gctx)) { if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_encrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) goto err; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 32 && AES_GCM_ASM2(gctx)) { if (CRYPTO_gcm128_encrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_encrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_encrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) goto err; } out += len; /* Finally write tag */ CRYPTO_gcm128_tag(&gctx->gcm, out, EVP_GCM_TLS_TAG_LEN); rv = len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN; } else { /* Decrypt */ if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 16 && AES_GCM_ASM(gctx)) { if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_decrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) goto err; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 16 && AES_GCM_ASM2(gctx)) { if (CRYPTO_gcm128_decrypt(&gctx->gcm, NULL, NULL, 0)) return -1; bulk = AES_gcm_decrypt(in, out, len, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; } #endif if (CRYPTO_gcm128_decrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) goto err; } /* Retrieve tag */ CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), EVP_GCM_TLS_TAG_LEN); /* If tag mismatch wipe buffer */ if (CRYPTO_memcmp(EVP_CIPHER_CTX_buf_noconst(ctx), in + len, EVP_GCM_TLS_TAG_LEN)) { OPENSSL_cleanse(out, len); goto err; } rv = len; } err: gctx->iv_set = 0; gctx->tls_aad_len = -1; return rv; } static int aes_gcm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); /* If not set up, return error */ if (!gctx->key_set) return -1; if (gctx->tls_aad_len >= 0) return aes_gcm_tls_cipher(ctx, out, in, len); if (!gctx->iv_set) return -1; if (in) { if (out == NULL) { if (CRYPTO_gcm128_aad(&gctx->gcm, in, len)) return -1; } else if (EVP_CIPHER_CTX_encrypting(ctx)) { if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 32 && AES_GCM_ASM(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_encrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_encrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) return -1; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 32 && AES_GCM_ASM2(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_encrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_encrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_encrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) return -1; } } else { if (gctx->ctr) { size_t bulk = 0; #if defined(AES_GCM_ASM) if (len >= 16 && AES_GCM_ASM(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_decrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_decrypt_ctr32(&gctx->gcm, in + bulk, out + bulk, len - bulk, gctx->ctr)) return -1; } else { size_t bulk = 0; #if defined(AES_GCM_ASM2) if (len >= 16 && AES_GCM_ASM2(gctx)) { size_t res = (16 - gctx->gcm.mres) % 16; if (CRYPTO_gcm128_decrypt(&gctx->gcm, in, out, res)) return -1; bulk = AES_gcm_decrypt(in + res, out + res, len - res, gctx->gcm.key, gctx->gcm.Yi.c, gctx->gcm.Xi.u); gctx->gcm.len.u[1] += bulk; bulk += res; } #endif if (CRYPTO_gcm128_decrypt(&gctx->gcm, in + bulk, out + bulk, len - bulk)) return -1; } } return len; } else { if (!EVP_CIPHER_CTX_encrypting(ctx)) { if (gctx->taglen < 0) return -1; if (CRYPTO_gcm128_finish(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), gctx->taglen) != 0) return -1; gctx->iv_set = 0; return 0; } CRYPTO_gcm128_tag(&gctx->gcm, EVP_CIPHER_CTX_buf_noconst(ctx), 16); gctx->taglen = 16; /* Don't reuse the IV */ gctx->iv_set = 0; return 0; } } #define CUSTOM_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 \ | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \ | EVP_CIPH_CUSTOM_COPY) BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, gcm, GCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, gcm, GCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, gcm, GCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) static int aes_xts_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,c); if (type == EVP_CTRL_COPY) { EVP_CIPHER_CTX *out = ptr; EVP_AES_XTS_CTX *xctx_out = EVP_C_DATA(EVP_AES_XTS_CTX,out); if (xctx->xts.key1) { if (xctx->xts.key1 != &xctx->ks1) return 0; xctx_out->xts.key1 = &xctx_out->ks1; } if (xctx->xts.key2) { if (xctx->xts.key2 != &xctx->ks2) return 0; xctx_out->xts.key2 = &xctx_out->ks2; } return 1; } else if (type != EVP_CTRL_INIT) return -1; /* key1 and key2 are used as an indicator both key and IV are set */ xctx->xts.key1 = NULL; xctx->xts.key2 = NULL; return 1; } static int aes_xts_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (!iv && !key) return 1; if (key) do { #ifdef AES_XTS_ASM xctx->stream = enc ? AES_xts_encrypt : AES_xts_decrypt; #else xctx->stream = NULL; #endif /* key_len is two AES keys */ #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { if (enc) { HWAES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) HWAES_encrypt; # ifdef HWAES_xts_encrypt xctx->stream = HWAES_xts_encrypt; # endif } else { HWAES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) HWAES_decrypt; # ifdef HWAES_xts_decrypt xctx->stream = HWAES_xts_decrypt; #endif } HWAES_set_encrypt_key(key + EVP_CIPHER_CTX_key_length(ctx) / 2, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) HWAES_encrypt; xctx->xts.key1 = &xctx->ks1; break; } else #endif #ifdef BSAES_CAPABLE if (BSAES_CAPABLE) xctx->stream = enc ? bsaes_xts_encrypt : bsaes_xts_decrypt; else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { if (enc) { vpaes_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) vpaes_encrypt; } else { vpaes_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) vpaes_decrypt; } vpaes_set_encrypt_key(key + EVP_CIPHER_CTX_key_length(ctx) / 2, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) vpaes_encrypt; xctx->xts.key1 = &xctx->ks1; break; } else #endif (void)0; /* terminate potentially open 'else' */ if (enc) { AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) AES_encrypt; } else { AES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks1.ks); xctx->xts.block1 = (block128_f) AES_decrypt; } AES_set_encrypt_key(key + EVP_CIPHER_CTX_key_length(ctx) / 2, EVP_CIPHER_CTX_key_length(ctx) * 4, &xctx->ks2.ks); xctx->xts.block2 = (block128_f) AES_encrypt; xctx->xts.key1 = &xctx->ks1; } while (0); if (iv) { xctx->xts.key2 = &xctx->ks2; memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, 16); } return 1; } static int aes_xts_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,ctx); if (!xctx->xts.key1 || !xctx->xts.key2) return 0; if (!out || !in || len < AES_BLOCK_SIZE) return 0; if (xctx->stream) (*xctx->stream) (in, out, len, xctx->xts.key1, xctx->xts.key2, EVP_CIPHER_CTX_iv_noconst(ctx)); else if (CRYPTO_xts128_encrypt(&xctx->xts, EVP_CIPHER_CTX_iv_noconst(ctx), in, out, len, EVP_CIPHER_CTX_encrypting(ctx))) return 0; return 1; } #define aes_xts_cleanup NULL #define XTS_FLAGS (EVP_CIPH_FLAG_DEFAULT_ASN1 | EVP_CIPH_CUSTOM_IV \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_CTRL_INIT \ | EVP_CIPH_CUSTOM_COPY) BLOCK_CIPHER_custom(NID_aes, 128, 1, 16, xts, XTS, XTS_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 1, 16, xts, XTS, XTS_FLAGS) static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= cctx->M; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } } static int aes_ccm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); if (!iv && !key) return 1; if (key) do { #ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { HWAES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) HWAES_encrypt); cctx->str = NULL; cctx->key_set = 1; break; } else #endif #ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { vpaes_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) vpaes_encrypt); cctx->str = NULL; cctx->key_set = 1; break; } #endif AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &cctx->ks.ks); CRYPTO_ccm128_init(&cctx->ccm, cctx->M, cctx->L, &cctx->ks, (block128_f) AES_encrypt); cctx->str = NULL; cctx->key_set = 1; } while (0); if (iv) { memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, 15 - cctx->L); cctx->iv_set = 1; } return 1; } static int aes_ccm_tls_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); CCM128_CONTEXT *ccm = &cctx->ccm; /* Encrypt/decrypt must be performed in place */ if (out != in || len < (EVP_CCM_TLS_EXPLICIT_IV_LEN + (size_t)cctx->M)) return -1; /* If encrypting set explicit IV from sequence number (start of AAD) */ if (EVP_CIPHER_CTX_encrypting(ctx)) memcpy(out, EVP_CIPHER_CTX_buf_noconst(ctx), EVP_CCM_TLS_EXPLICIT_IV_LEN); /* Get rest of IV from explicit IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(ctx) + EVP_CCM_TLS_FIXED_IV_LEN, in, EVP_CCM_TLS_EXPLICIT_IV_LEN); /* Correct length value */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; if (CRYPTO_ccm128_setiv(ccm, EVP_CIPHER_CTX_iv_noconst(ctx), 15 - cctx->L, len)) return -1; /* Use saved AAD */ CRYPTO_ccm128_aad(ccm, EVP_CIPHER_CTX_buf_noconst(ctx), cctx->tls_aad_len); /* Fix buffer to point to payload */ in += EVP_CCM_TLS_EXPLICIT_IV_LEN; out += EVP_CCM_TLS_EXPLICIT_IV_LEN; if (EVP_CIPHER_CTX_encrypting(ctx)) { if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len, cctx->str) : CRYPTO_ccm128_encrypt(ccm, in, out, len)) return -1; if (!CRYPTO_ccm128_tag(ccm, out + len, cctx->M)) return -1; return len + EVP_CCM_TLS_EXPLICIT_IV_LEN + cctx->M; } else { if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len, cctx->str) : !CRYPTO_ccm128_decrypt(ccm, in, out, len)) { unsigned char tag[16]; if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) { if (!CRYPTO_memcmp(tag, in + len, cctx->M)) return len; } } OPENSSL_cleanse(out, len); return -1; } } static int aes_ccm_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,ctx); CCM128_CONTEXT *ccm = &cctx->ccm; /* If not set up, return error */ if (!cctx->key_set) return -1; if (cctx->tls_aad_len >= 0) return aes_ccm_tls_cipher(ctx, out, in, len); if (!cctx->iv_set) return -1; if (!EVP_CIPHER_CTX_encrypting(ctx) && !cctx->tag_set) return -1; if (!out) { if (!in) { if (CRYPTO_ccm128_setiv(ccm, EVP_CIPHER_CTX_iv_noconst(ctx), 15 - cctx->L, len)) return -1; cctx->len_set = 1; return len; } /* If have AAD need message length */ if (!cctx->len_set && len) return -1; CRYPTO_ccm128_aad(ccm, in, len); return len; } /* EVP_*Final() doesn't return any data */ if (!in) return 0; /* If not set length yet do it */ if (!cctx->len_set) { if (CRYPTO_ccm128_setiv(ccm, EVP_CIPHER_CTX_iv_noconst(ctx), 15 - cctx->L, len)) return -1; cctx->len_set = 1; } if (EVP_CIPHER_CTX_encrypting(ctx)) { if (cctx->str ? CRYPTO_ccm128_encrypt_ccm64(ccm, in, out, len, cctx->str) : CRYPTO_ccm128_encrypt(ccm, in, out, len)) return -1; cctx->tag_set = 1; return len; } else { int rv = -1; if (cctx->str ? !CRYPTO_ccm128_decrypt_ccm64(ccm, in, out, len, cctx->str) : !CRYPTO_ccm128_decrypt(ccm, in, out, len)) { unsigned char tag[16]; if (CRYPTO_ccm128_tag(ccm, tag, cctx->M)) { if (!CRYPTO_memcmp(tag, EVP_CIPHER_CTX_buf_noconst(ctx), cctx->M)) rv = len; } } if (rv == -1) OPENSSL_cleanse(out, len); cctx->iv_set = 0; cctx->tag_set = 0; cctx->len_set = 0; return rv; } } #define aes_ccm_cleanup NULL BLOCK_CIPHER_custom(NID_aes, 128, 1, 12, ccm, CCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 192, 1, 12, ccm, CCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 1, 12, ccm, CCM, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) typedef struct { union { double align; AES_KEY ks; } ks; /* Indicates if IV has been set */ unsigned char *iv; } EVP_AES_WRAP_CTX; static int aes_wrap_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_WRAP_CTX *wctx = EVP_C_DATA(EVP_AES_WRAP_CTX,ctx); if (!iv && !key) return 1; if (key) { if (EVP_CIPHER_CTX_encrypting(ctx)) AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &wctx->ks.ks); else AES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &wctx->ks.ks); if (!iv) wctx->iv = NULL; } if (iv) { memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, EVP_CIPHER_CTX_iv_length(ctx)); wctx->iv = EVP_CIPHER_CTX_iv_noconst(ctx); } return 1; } static int aes_wrap_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inlen) { EVP_AES_WRAP_CTX *wctx = EVP_C_DATA(EVP_AES_WRAP_CTX,ctx); size_t rv; /* AES wrap with padding has IV length of 4, without padding 8 */ int pad = EVP_CIPHER_CTX_iv_length(ctx) == 4; /* No final operation so always return zero length */ if (!in) return 0; /* Input length must always be non-zero */ if (!inlen) return -1; /* If decrypting need at least 16 bytes and multiple of 8 */ if (!EVP_CIPHER_CTX_encrypting(ctx) && (inlen < 16 || inlen & 0x7)) return -1; /* If not padding input must be multiple of 8 */ if (!pad && inlen & 0x7) return -1; if (is_partially_overlapping(out, in, inlen)) { EVPerr(EVP_F_AES_WRAP_CIPHER, EVP_R_PARTIALLY_OVERLAPPING); return 0; } if (!out) { if (EVP_CIPHER_CTX_encrypting(ctx)) { /* If padding round up to multiple of 8 */ if (pad) inlen = (inlen + 7) / 8 * 8; /* 8 byte prefix */ return inlen + 8; } else { /* * If not padding output will be exactly 8 bytes smaller than * input. If padding it will be at least 8 bytes smaller but we * don't know how much. */ return inlen - 8; } } if (pad) { if (EVP_CIPHER_CTX_encrypting(ctx)) rv = CRYPTO_128_wrap_pad(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_encrypt); else rv = CRYPTO_128_unwrap_pad(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_decrypt); } else { if (EVP_CIPHER_CTX_encrypting(ctx)) rv = CRYPTO_128_wrap(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_encrypt); else rv = CRYPTO_128_unwrap(&wctx->ks.ks, wctx->iv, out, in, inlen, (block128_f) AES_decrypt); } return rv ? (int)rv : -1; } #define WRAP_FLAGS (EVP_CIPH_WRAP_MODE \ | EVP_CIPH_CUSTOM_IV | EVP_CIPH_FLAG_CUSTOM_CIPHER \ | EVP_CIPH_ALWAYS_CALL_INIT | EVP_CIPH_FLAG_DEFAULT_ASN1) static const EVP_CIPHER aes_128_wrap = { NID_id_aes128_wrap, 8, 16, 8, WRAP_FLAGS, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_128_wrap(void) { return &aes_128_wrap; } static const EVP_CIPHER aes_192_wrap = { NID_id_aes192_wrap, 8, 24, 8, WRAP_FLAGS, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_192_wrap(void) { return &aes_192_wrap; } static const EVP_CIPHER aes_256_wrap = { NID_id_aes256_wrap, 8, 32, 8, WRAP_FLAGS, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_256_wrap(void) { return &aes_256_wrap; } static const EVP_CIPHER aes_128_wrap_pad = { NID_id_aes128_wrap_pad, 8, 16, 4, WRAP_FLAGS, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_128_wrap_pad(void) { return &aes_128_wrap_pad; } static const EVP_CIPHER aes_192_wrap_pad = { NID_id_aes192_wrap_pad, 8, 24, 4, WRAP_FLAGS, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_192_wrap_pad(void) { return &aes_192_wrap_pad; } static const EVP_CIPHER aes_256_wrap_pad = { NID_id_aes256_wrap_pad, 8, 32, 4, WRAP_FLAGS, aes_wrap_init_key, aes_wrap_cipher, NULL, sizeof(EVP_AES_WRAP_CTX), NULL, NULL, NULL, NULL }; const EVP_CIPHER *EVP_aes_256_wrap_pad(void) { return &aes_256_wrap_pad; } #ifndef OPENSSL_NO_OCB static int aes_ocb_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,c); EVP_CIPHER_CTX *newc; EVP_AES_OCB_CTX *new_octx; switch (type) { case EVP_CTRL_INIT: octx->key_set = 0; octx->iv_set = 0; octx->ivlen = EVP_CIPHER_CTX_iv_length(c); octx->iv = EVP_CIPHER_CTX_iv_noconst(c); octx->taglen = 16; octx->data_buf_len = 0; octx->aad_buf_len = 0; return 1; case EVP_CTRL_AEAD_SET_IVLEN: /* IV len must be 1 to 15 */ if (arg <= 0 || arg > 15) return 0; octx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (!ptr) { /* Tag len must be 0 to 16 */ if (arg < 0 || arg > 16) return 0; octx->taglen = arg; return 1; } if (arg != octx->taglen || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(octx->tag, ptr, arg); return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg != octx->taglen || !EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(ptr, octx->tag, arg); return 1; case EVP_CTRL_COPY: newc = (EVP_CIPHER_CTX *)ptr; new_octx = EVP_C_DATA(EVP_AES_OCB_CTX,newc); return CRYPTO_ocb128_copy_ctx(&new_octx->ocb, &octx->ocb, &new_octx->ksenc.ks, &new_octx->ksdec.ks); default: return -1; } } # ifdef HWAES_CAPABLE # ifdef HWAES_ocb_encrypt void HWAES_ocb_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const void *key, size_t start_block_num, unsigned char offset_i[16], const unsigned char L_[][16], unsigned char checksum[16]); # else # define HWAES_ocb_encrypt ((ocb128_f)NULL) # endif # ifdef HWAES_ocb_decrypt void HWAES_ocb_decrypt(const unsigned char *in, unsigned char *out, size_t blocks, const void *key, size_t start_block_num, unsigned char offset_i[16], const unsigned char L_[][16], unsigned char checksum[16]); # else # define HWAES_ocb_decrypt ((ocb128_f)NULL) # endif # endif static int aes_ocb_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); if (!iv && !key) return 1; if (key) { do { /* * We set both the encrypt and decrypt key here because decrypt * needs both. We could possibly optimise to remove setting the * decrypt for an encryption operation. */ # ifdef HWAES_CAPABLE if (HWAES_CAPABLE) { HWAES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksenc.ks); HWAES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) HWAES_encrypt, (block128_f) HWAES_decrypt, enc ? HWAES_ocb_encrypt : HWAES_ocb_decrypt)) return 0; break; } # endif # ifdef VPAES_CAPABLE if (VPAES_CAPABLE) { vpaes_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksenc.ks); vpaes_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) vpaes_encrypt, (block128_f) vpaes_decrypt, NULL)) return 0; break; } # endif AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksenc.ks); AES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &octx->ksdec.ks); if (!CRYPTO_ocb128_init(&octx->ocb, &octx->ksenc.ks, &octx->ksdec.ks, (block128_f) AES_encrypt, (block128_f) AES_decrypt, NULL)) return 0; } while (0); /* * If we have an iv we can set it directly, otherwise use saved IV. */ if (iv == NULL && octx->iv_set) iv = octx->iv; if (iv) { if (CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen) != 1) return 0; octx->iv_set = 1; } octx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (octx->key_set) CRYPTO_ocb128_setiv(&octx->ocb, iv, octx->ivlen, octx->taglen); else memcpy(octx->iv, iv, octx->ivlen); octx->iv_set = 1; } return 1; } static int aes_ocb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { unsigned char *buf; int *buf_len; int written_len = 0; size_t trailing_len; EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,ctx); /* If IV or Key not set then return error */ if (!octx->iv_set) return -1; if (!octx->key_set) return -1; if (in != NULL) { /* * Need to ensure we are only passing full blocks to low level OCB * routines. We do it here rather than in EVP_EncryptUpdate/ * EVP_DecryptUpdate because we need to pass full blocks of AAD too * and those routines don't support that */ /* Are we dealing with AAD or normal data here? */ if (out == NULL) { buf = octx->aad_buf; buf_len = &(octx->aad_buf_len); } else { buf = octx->data_buf; buf_len = &(octx->data_buf_len); if (is_partially_overlapping(out + *buf_len, in, len)) { EVPerr(EVP_F_AES_OCB_CIPHER, EVP_R_PARTIALLY_OVERLAPPING); return 0; } } /* * If we've got a partially filled buffer from a previous call then * use that data first */ if (*buf_len > 0) { unsigned int remaining; remaining = AES_BLOCK_SIZE - (*buf_len); if (remaining > len) { memcpy(buf + (*buf_len), in, len); *(buf_len) += len; return 0; } memcpy(buf + (*buf_len), in, remaining); /* * If we get here we've filled the buffer, so process it */ len -= remaining; in += remaining; if (out == NULL) { if (!CRYPTO_ocb128_aad(&octx->ocb, buf, AES_BLOCK_SIZE)) return -1; } else if (EVP_CIPHER_CTX_encrypting(ctx)) { if (!CRYPTO_ocb128_encrypt(&octx->ocb, buf, out, AES_BLOCK_SIZE)) return -1; } else { if (!CRYPTO_ocb128_decrypt(&octx->ocb, buf, out, AES_BLOCK_SIZE)) return -1; } written_len = AES_BLOCK_SIZE; *buf_len = 0; if (out != NULL) out += AES_BLOCK_SIZE; } /* Do we have a partial block to handle at the end? */ trailing_len = len % AES_BLOCK_SIZE; /* * If we've got some full blocks to handle, then process these first */ if (len != trailing_len) { if (out == NULL) { if (!CRYPTO_ocb128_aad(&octx->ocb, in, len - trailing_len)) return -1; } else if (EVP_CIPHER_CTX_encrypting(ctx)) { if (!CRYPTO_ocb128_encrypt (&octx->ocb, in, out, len - trailing_len)) return -1; } else { if (!CRYPTO_ocb128_decrypt (&octx->ocb, in, out, len - trailing_len)) return -1; } written_len += len - trailing_len; in += len - trailing_len; } /* Handle any trailing partial block */ if (trailing_len > 0) { memcpy(buf, in, trailing_len); *buf_len = trailing_len; } return written_len; } else { /* * First of all empty the buffer of any partial block that we might * have been provided - both for data and AAD */ if (octx->data_buf_len > 0) { if (EVP_CIPHER_CTX_encrypting(ctx)) { if (!CRYPTO_ocb128_encrypt(&octx->ocb, octx->data_buf, out, octx->data_buf_len)) return -1; } else { if (!CRYPTO_ocb128_decrypt(&octx->ocb, octx->data_buf, out, octx->data_buf_len)) return -1; } written_len = octx->data_buf_len; octx->data_buf_len = 0; } if (octx->aad_buf_len > 0) { if (!CRYPTO_ocb128_aad (&octx->ocb, octx->aad_buf, octx->aad_buf_len)) return -1; octx->aad_buf_len = 0; } /* If decrypting then verify */ if (!EVP_CIPHER_CTX_encrypting(ctx)) { if (octx->taglen < 0) return -1; if (CRYPTO_ocb128_finish(&octx->ocb, octx->tag, octx->taglen) != 0) return -1; octx->iv_set = 0; return written_len; } /* If encrypting then just get the tag */ if (CRYPTO_ocb128_tag(&octx->ocb, octx->tag, 16) != 1) return -1; /* Don't reuse the IV */ octx->iv_set = 0; return written_len; } } static int aes_ocb_cleanup(EVP_CIPHER_CTX *c) { EVP_AES_OCB_CTX *octx = EVP_C_DATA(EVP_AES_OCB_CTX,c); CRYPTO_ocb128_cleanup(&octx->ocb); return 1; } BLOCK_CIPHER_custom(NID_aes, 128, 16, 12, ocb, OCB, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 192, 16, 12, ocb, OCB, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) BLOCK_CIPHER_custom(NID_aes, 256, 16, 12, ocb, OCB, EVP_CIPH_FLAG_AEAD_CIPHER | CUSTOM_FLAGS) #endif /* OPENSSL_NO_OCB */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3068_0
crossvul-cpp_data_bad_5501_0
/* * Copyright (C) 2001 MandrakeSoft S.A. * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * MandrakeSoft S.A. * 43, rue d'Aboukir * 75002 Paris - France * http://www.linux-mandrake.com/ * http://www.mandrakesoft.com/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Yunhong Jiang <yunhong.jiang@intel.com> * Yaozu (Eddie) Dong <eddie.dong@intel.com> * Based on Xen 3.1 code. */ #include <linux/kvm_host.h> #include <linux/kvm.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/smp.h> #include <linux/hrtimer.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/export.h> #include <asm/processor.h> #include <asm/page.h> #include <asm/current.h> #include <trace/events/kvm.h> #include "ioapic.h" #include "lapic.h" #include "irq.h" #if 0 #define ioapic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg) #else #define ioapic_debug(fmt, arg...) #endif static int ioapic_service(struct kvm_ioapic *vioapic, int irq, bool line_status); static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic, unsigned long addr, unsigned long length) { unsigned long result = 0; switch (ioapic->ioregsel) { case IOAPIC_REG_VERSION: result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16) | (IOAPIC_VERSION_ID & 0xff)); break; case IOAPIC_REG_APIC_ID: case IOAPIC_REG_ARB_ID: result = ((ioapic->id & 0xf) << 24); break; default: { u32 redir_index = (ioapic->ioregsel - 0x10) >> 1; u64 redir_content; if (redir_index < IOAPIC_NUM_PINS) redir_content = ioapic->redirtbl[redir_index].bits; else redir_content = ~0ULL; result = (ioapic->ioregsel & 0x1) ? (redir_content >> 32) & 0xffffffff : redir_content & 0xffffffff; break; } } return result; } static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic) { ioapic->rtc_status.pending_eoi = 0; bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPUS); } static void kvm_rtc_eoi_tracking_restore_all(struct kvm_ioapic *ioapic); static void rtc_status_pending_eoi_check_valid(struct kvm_ioapic *ioapic) { if (WARN_ON(ioapic->rtc_status.pending_eoi < 0)) kvm_rtc_eoi_tracking_restore_all(ioapic); } static void __rtc_irq_eoi_tracking_restore_one(struct kvm_vcpu *vcpu) { bool new_val, old_val; struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic; struct dest_map *dest_map = &ioapic->rtc_status.dest_map; union kvm_ioapic_redirect_entry *e; e = &ioapic->redirtbl[RTC_GSI]; if (!kvm_apic_match_dest(vcpu, NULL, 0, e->fields.dest_id, e->fields.dest_mode)) return; new_val = kvm_apic_pending_eoi(vcpu, e->fields.vector); old_val = test_bit(vcpu->vcpu_id, dest_map->map); if (new_val == old_val) return; if (new_val) { __set_bit(vcpu->vcpu_id, dest_map->map); dest_map->vectors[vcpu->vcpu_id] = e->fields.vector; ioapic->rtc_status.pending_eoi++; } else { __clear_bit(vcpu->vcpu_id, dest_map->map); ioapic->rtc_status.pending_eoi--; rtc_status_pending_eoi_check_valid(ioapic); } } void kvm_rtc_eoi_tracking_restore_one(struct kvm_vcpu *vcpu) { struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic; spin_lock(&ioapic->lock); __rtc_irq_eoi_tracking_restore_one(vcpu); spin_unlock(&ioapic->lock); } static void kvm_rtc_eoi_tracking_restore_all(struct kvm_ioapic *ioapic) { struct kvm_vcpu *vcpu; int i; if (RTC_GSI >= IOAPIC_NUM_PINS) return; rtc_irq_eoi_tracking_reset(ioapic); kvm_for_each_vcpu(i, vcpu, ioapic->kvm) __rtc_irq_eoi_tracking_restore_one(vcpu); } static void rtc_irq_eoi(struct kvm_ioapic *ioapic, struct kvm_vcpu *vcpu) { if (test_and_clear_bit(vcpu->vcpu_id, ioapic->rtc_status.dest_map.map)) { --ioapic->rtc_status.pending_eoi; rtc_status_pending_eoi_check_valid(ioapic); } } static bool rtc_irq_check_coalesced(struct kvm_ioapic *ioapic) { if (ioapic->rtc_status.pending_eoi > 0) return true; /* coalesced */ return false; } static int ioapic_set_irq(struct kvm_ioapic *ioapic, unsigned int irq, int irq_level, bool line_status) { union kvm_ioapic_redirect_entry entry; u32 mask = 1 << irq; u32 old_irr; int edge, ret; entry = ioapic->redirtbl[irq]; edge = (entry.fields.trig_mode == IOAPIC_EDGE_TRIG); if (!irq_level) { ioapic->irr &= ~mask; ret = 1; goto out; } /* * Return 0 for coalesced interrupts; for edge-triggered interrupts, * this only happens if a previous edge has not been delivered due * do masking. For level interrupts, the remote_irr field tells * us if the interrupt is waiting for an EOI. * * RTC is special: it is edge-triggered, but userspace likes to know * if it has been already ack-ed via EOI because coalesced RTC * interrupts lead to time drift in Windows guests. So we track * EOI manually for the RTC interrupt. */ if (irq == RTC_GSI && line_status && rtc_irq_check_coalesced(ioapic)) { ret = 0; goto out; } old_irr = ioapic->irr; ioapic->irr |= mask; if (edge) ioapic->irr_delivered &= ~mask; if ((edge && old_irr == ioapic->irr) || (!edge && entry.fields.remote_irr)) { ret = 0; goto out; } ret = ioapic_service(ioapic, irq, line_status); out: trace_kvm_ioapic_set_irq(entry.bits, irq, ret == 0); return ret; } static void kvm_ioapic_inject_all(struct kvm_ioapic *ioapic, unsigned long irr) { u32 idx; rtc_irq_eoi_tracking_reset(ioapic); for_each_set_bit(idx, &irr, IOAPIC_NUM_PINS) ioapic_set_irq(ioapic, idx, 1, true); kvm_rtc_eoi_tracking_restore_all(ioapic); } void kvm_ioapic_scan_entry(struct kvm_vcpu *vcpu, ulong *ioapic_handled_vectors) { struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic; struct dest_map *dest_map = &ioapic->rtc_status.dest_map; union kvm_ioapic_redirect_entry *e; int index; spin_lock(&ioapic->lock); /* Make sure we see any missing RTC EOI */ if (test_bit(vcpu->vcpu_id, dest_map->map)) __set_bit(dest_map->vectors[vcpu->vcpu_id], ioapic_handled_vectors); for (index = 0; index < IOAPIC_NUM_PINS; index++) { e = &ioapic->redirtbl[index]; if (e->fields.trig_mode == IOAPIC_LEVEL_TRIG || kvm_irq_has_notifier(ioapic->kvm, KVM_IRQCHIP_IOAPIC, index) || index == RTC_GSI) { if (kvm_apic_match_dest(vcpu, NULL, 0, e->fields.dest_id, e->fields.dest_mode) || (e->fields.trig_mode == IOAPIC_EDGE_TRIG && kvm_apic_pending_eoi(vcpu, e->fields.vector))) __set_bit(e->fields.vector, ioapic_handled_vectors); } } spin_unlock(&ioapic->lock); } void kvm_vcpu_request_scan_ioapic(struct kvm *kvm) { struct kvm_ioapic *ioapic = kvm->arch.vioapic; if (!ioapic) return; kvm_make_scan_ioapic_request(kvm); } static void ioapic_write_indirect(struct kvm_ioapic *ioapic, u32 val) { unsigned index; bool mask_before, mask_after; union kvm_ioapic_redirect_entry *e; switch (ioapic->ioregsel) { case IOAPIC_REG_VERSION: /* Writes are ignored. */ break; case IOAPIC_REG_APIC_ID: ioapic->id = (val >> 24) & 0xf; break; case IOAPIC_REG_ARB_ID: break; default: index = (ioapic->ioregsel - 0x10) >> 1; ioapic_debug("change redir index %x val %x\n", index, val); if (index >= IOAPIC_NUM_PINS) return; e = &ioapic->redirtbl[index]; mask_before = e->fields.mask; if (ioapic->ioregsel & 1) { e->bits &= 0xffffffff; e->bits |= (u64) val << 32; } else { e->bits &= ~0xffffffffULL; e->bits |= (u32) val; e->fields.remote_irr = 0; } mask_after = e->fields.mask; if (mask_before != mask_after) kvm_fire_mask_notifiers(ioapic->kvm, KVM_IRQCHIP_IOAPIC, index, mask_after); if (e->fields.trig_mode == IOAPIC_LEVEL_TRIG && ioapic->irr & (1 << index)) ioapic_service(ioapic, index, false); kvm_vcpu_request_scan_ioapic(ioapic->kvm); break; } } static int ioapic_service(struct kvm_ioapic *ioapic, int irq, bool line_status) { union kvm_ioapic_redirect_entry *entry = &ioapic->redirtbl[irq]; struct kvm_lapic_irq irqe; int ret; if (entry->fields.mask) return -1; ioapic_debug("dest=%x dest_mode=%x delivery_mode=%x " "vector=%x trig_mode=%x\n", entry->fields.dest_id, entry->fields.dest_mode, entry->fields.delivery_mode, entry->fields.vector, entry->fields.trig_mode); irqe.dest_id = entry->fields.dest_id; irqe.vector = entry->fields.vector; irqe.dest_mode = entry->fields.dest_mode; irqe.trig_mode = entry->fields.trig_mode; irqe.delivery_mode = entry->fields.delivery_mode << 8; irqe.level = 1; irqe.shorthand = 0; irqe.msi_redir_hint = false; if (irqe.trig_mode == IOAPIC_EDGE_TRIG) ioapic->irr_delivered |= 1 << irq; if (irq == RTC_GSI && line_status) { /* * pending_eoi cannot ever become negative (see * rtc_status_pending_eoi_check_valid) and the caller * ensures that it is only called if it is >= zero, namely * if rtc_irq_check_coalesced returns false). */ BUG_ON(ioapic->rtc_status.pending_eoi != 0); ret = kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe, &ioapic->rtc_status.dest_map); ioapic->rtc_status.pending_eoi = (ret < 0 ? 0 : ret); } else ret = kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe, NULL); if (ret && irqe.trig_mode == IOAPIC_LEVEL_TRIG) entry->fields.remote_irr = 1; return ret; } int kvm_ioapic_set_irq(struct kvm_ioapic *ioapic, int irq, int irq_source_id, int level, bool line_status) { int ret, irq_level; BUG_ON(irq < 0 || irq >= IOAPIC_NUM_PINS); spin_lock(&ioapic->lock); irq_level = __kvm_irq_line_state(&ioapic->irq_states[irq], irq_source_id, level); ret = ioapic_set_irq(ioapic, irq, irq_level, line_status); spin_unlock(&ioapic->lock); return ret; } void kvm_ioapic_clear_all(struct kvm_ioapic *ioapic, int irq_source_id) { int i; spin_lock(&ioapic->lock); for (i = 0; i < KVM_IOAPIC_NUM_PINS; i++) __clear_bit(irq_source_id, &ioapic->irq_states[i]); spin_unlock(&ioapic->lock); } static void kvm_ioapic_eoi_inject_work(struct work_struct *work) { int i; struct kvm_ioapic *ioapic = container_of(work, struct kvm_ioapic, eoi_inject.work); spin_lock(&ioapic->lock); for (i = 0; i < IOAPIC_NUM_PINS; i++) { union kvm_ioapic_redirect_entry *ent = &ioapic->redirtbl[i]; if (ent->fields.trig_mode != IOAPIC_LEVEL_TRIG) continue; if (ioapic->irr & (1 << i) && !ent->fields.remote_irr) ioapic_service(ioapic, i, false); } spin_unlock(&ioapic->lock); } #define IOAPIC_SUCCESSIVE_IRQ_MAX_COUNT 10000 static void __kvm_ioapic_update_eoi(struct kvm_vcpu *vcpu, struct kvm_ioapic *ioapic, int vector, int trigger_mode) { struct dest_map *dest_map = &ioapic->rtc_status.dest_map; struct kvm_lapic *apic = vcpu->arch.apic; int i; /* RTC special handling */ if (test_bit(vcpu->vcpu_id, dest_map->map) && vector == dest_map->vectors[vcpu->vcpu_id]) rtc_irq_eoi(ioapic, vcpu); for (i = 0; i < IOAPIC_NUM_PINS; i++) { union kvm_ioapic_redirect_entry *ent = &ioapic->redirtbl[i]; if (ent->fields.vector != vector) continue; /* * We are dropping lock while calling ack notifiers because ack * notifier callbacks for assigned devices call into IOAPIC * recursively. Since remote_irr is cleared only after call * to notifiers if the same vector will be delivered while lock * is dropped it will be put into irr and will be delivered * after ack notifier returns. */ spin_unlock(&ioapic->lock); kvm_notify_acked_irq(ioapic->kvm, KVM_IRQCHIP_IOAPIC, i); spin_lock(&ioapic->lock); if (trigger_mode != IOAPIC_LEVEL_TRIG || kvm_lapic_get_reg(apic, APIC_SPIV) & APIC_SPIV_DIRECTED_EOI) continue; ASSERT(ent->fields.trig_mode == IOAPIC_LEVEL_TRIG); ent->fields.remote_irr = 0; if (!ent->fields.mask && (ioapic->irr & (1 << i))) { ++ioapic->irq_eoi[i]; if (ioapic->irq_eoi[i] == IOAPIC_SUCCESSIVE_IRQ_MAX_COUNT) { /* * Real hardware does not deliver the interrupt * immediately during eoi broadcast, and this * lets a buggy guest make slow progress * even if it does not correctly handle a * level-triggered interrupt. Emulate this * behavior if we detect an interrupt storm. */ schedule_delayed_work(&ioapic->eoi_inject, HZ / 100); ioapic->irq_eoi[i] = 0; trace_kvm_ioapic_delayed_eoi_inj(ent->bits); } else { ioapic_service(ioapic, i, false); } } else { ioapic->irq_eoi[i] = 0; } } } void kvm_ioapic_update_eoi(struct kvm_vcpu *vcpu, int vector, int trigger_mode) { struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic; spin_lock(&ioapic->lock); __kvm_ioapic_update_eoi(vcpu, ioapic, vector, trigger_mode); spin_unlock(&ioapic->lock); } static inline struct kvm_ioapic *to_ioapic(struct kvm_io_device *dev) { return container_of(dev, struct kvm_ioapic, dev); } static inline int ioapic_in_range(struct kvm_ioapic *ioapic, gpa_t addr) { return ((addr >= ioapic->base_address && (addr < ioapic->base_address + IOAPIC_MEM_LENGTH))); } static int ioapic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this, gpa_t addr, int len, void *val) { struct kvm_ioapic *ioapic = to_ioapic(this); u32 result; if (!ioapic_in_range(ioapic, addr)) return -EOPNOTSUPP; ioapic_debug("addr %lx\n", (unsigned long)addr); ASSERT(!(addr & 0xf)); /* check alignment */ addr &= 0xff; spin_lock(&ioapic->lock); switch (addr) { case IOAPIC_REG_SELECT: result = ioapic->ioregsel; break; case IOAPIC_REG_WINDOW: result = ioapic_read_indirect(ioapic, addr, len); break; default: result = 0; break; } spin_unlock(&ioapic->lock); switch (len) { case 8: *(u64 *) val = result; break; case 1: case 2: case 4: memcpy(val, (char *)&result, len); break; default: printk(KERN_WARNING "ioapic: wrong length %d\n", len); } return 0; } static int ioapic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this, gpa_t addr, int len, const void *val) { struct kvm_ioapic *ioapic = to_ioapic(this); u32 data; if (!ioapic_in_range(ioapic, addr)) return -EOPNOTSUPP; ioapic_debug("ioapic_mmio_write addr=%p len=%d val=%p\n", (void*)addr, len, val); ASSERT(!(addr & 0xf)); /* check alignment */ switch (len) { case 8: case 4: data = *(u32 *) val; break; case 2: data = *(u16 *) val; break; case 1: data = *(u8 *) val; break; default: printk(KERN_WARNING "ioapic: Unsupported size %d\n", len); return 0; } addr &= 0xff; spin_lock(&ioapic->lock); switch (addr) { case IOAPIC_REG_SELECT: ioapic->ioregsel = data & 0xFF; /* 8-bit register */ break; case IOAPIC_REG_WINDOW: ioapic_write_indirect(ioapic, data); break; default: break; } spin_unlock(&ioapic->lock); return 0; } static void kvm_ioapic_reset(struct kvm_ioapic *ioapic) { int i; cancel_delayed_work_sync(&ioapic->eoi_inject); for (i = 0; i < IOAPIC_NUM_PINS; i++) ioapic->redirtbl[i].fields.mask = 1; ioapic->base_address = IOAPIC_DEFAULT_BASE_ADDRESS; ioapic->ioregsel = 0; ioapic->irr = 0; ioapic->irr_delivered = 0; ioapic->id = 0; memset(ioapic->irq_eoi, 0x00, sizeof(ioapic->irq_eoi)); rtc_irq_eoi_tracking_reset(ioapic); } static const struct kvm_io_device_ops ioapic_mmio_ops = { .read = ioapic_mmio_read, .write = ioapic_mmio_write, }; int kvm_ioapic_init(struct kvm *kvm) { struct kvm_ioapic *ioapic; int ret; ioapic = kzalloc(sizeof(struct kvm_ioapic), GFP_KERNEL); if (!ioapic) return -ENOMEM; spin_lock_init(&ioapic->lock); INIT_DELAYED_WORK(&ioapic->eoi_inject, kvm_ioapic_eoi_inject_work); kvm->arch.vioapic = ioapic; kvm_ioapic_reset(ioapic); kvm_iodevice_init(&ioapic->dev, &ioapic_mmio_ops); ioapic->kvm = kvm; mutex_lock(&kvm->slots_lock); ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, ioapic->base_address, IOAPIC_MEM_LENGTH, &ioapic->dev); mutex_unlock(&kvm->slots_lock); if (ret < 0) { kvm->arch.vioapic = NULL; kfree(ioapic); return ret; } kvm_vcpu_request_scan_ioapic(kvm); return ret; } void kvm_ioapic_destroy(struct kvm *kvm) { struct kvm_ioapic *ioapic = kvm->arch.vioapic; cancel_delayed_work_sync(&ioapic->eoi_inject); kvm_io_bus_unregister_dev(kvm, KVM_MMIO_BUS, &ioapic->dev); kvm->arch.vioapic = NULL; kfree(ioapic); } int kvm_get_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state) { struct kvm_ioapic *ioapic = ioapic_irqchip(kvm); if (!ioapic) return -EINVAL; spin_lock(&ioapic->lock); memcpy(state, ioapic, sizeof(struct kvm_ioapic_state)); state->irr &= ~ioapic->irr_delivered; spin_unlock(&ioapic->lock); return 0; } int kvm_set_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state) { struct kvm_ioapic *ioapic = ioapic_irqchip(kvm); if (!ioapic) return -EINVAL; spin_lock(&ioapic->lock); memcpy(ioapic, state, sizeof(struct kvm_ioapic_state)); ioapic->irr = 0; ioapic->irr_delivered = 0; kvm_vcpu_request_scan_ioapic(kvm); kvm_ioapic_inject_all(ioapic, state->irr); spin_unlock(&ioapic->lock); return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5501_0
crossvul-cpp_data_good_932_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; size_t number_channels; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; number_channels=MagickMin(MagickMin(MagickMin( Ar_image->number_channels,Ai_image->number_channels),MagickMin( Br_image->number_channels,Bi_image->number_channels)),MagickMin( Cr_image->number_channels,Ci_image->number_channels)); Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L) #endif for (y=0; y < (ssize_t) Cr_image->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) Cr_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_channels; i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]); Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]); Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register Quantum *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register Quantum *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_932_0
crossvul-cpp_data_bad_486_4
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. CredSSP layer and Kerberos support. Copyright 2012-2017 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gssapi/gssapi.h> #include "rdesktop.h" extern RD_BOOL g_use_password_as_pin; extern char *g_sc_csp_name; extern char *g_sc_reader_name; extern char *g_sc_card_name; extern char *g_sc_container_name; static gss_OID_desc _gss_spnego_krb5_mechanism_oid_desc = { 9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" }; static STREAM ber_wrap_hdr_data(int tagval, STREAM in) { STREAM out; int size = s_length(in) + 16; out = xmalloc(sizeof(struct stream)); memset(out, 0, sizeof(struct stream)); out->data = xmalloc(size); out->size = size; out->p = out->data; ber_out_header(out, tagval, s_length(in)); out_uint8p(out, in->data, s_length(in)); s_mark_end(out); return out; } static void cssp_gss_report_error(OM_uint32 code, char *str, OM_uint32 major_status, OM_uint32 minor_status) { OM_uint32 msgctx = 0, ms; gss_buffer_desc status_string; logger(Core, Debug, "GSS error [%d:%d:%d]: %s", (major_status & 0xff000000) >> 24, // Calling error (major_status & 0xff0000) >> 16, // Routine error major_status & 0xffff, // Supplementary info bits str); do { ms = gss_display_status(&minor_status, major_status, code, GSS_C_NULL_OID, &msgctx, &status_string); if (ms != GSS_S_COMPLETE) continue; logger(Core, Debug, " - %s", status_string.value); } while (ms == GSS_S_COMPLETE && msgctx); } static RD_BOOL cssp_gss_mech_available(gss_OID mech) { int mech_found; OM_uint32 major_status, minor_status; gss_OID_set mech_set; mech_found = 0; if (mech == GSS_C_NO_OID) return True; major_status = gss_indicate_mechs(&minor_status, &mech_set); if (!mech_set) return False; if (GSS_ERROR(major_status)) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to get available mechs on system", major_status, minor_status); return False; } gss_test_oid_set_member(&minor_status, mech, mech_set, &mech_found); if (GSS_ERROR(major_status)) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to match mechanism in set", major_status, minor_status); return False; } if (!mech_found) return False; return True; } static RD_BOOL cssp_gss_get_service_name(char *server, gss_name_t * name) { gss_buffer_desc output; OM_uint32 major_status, minor_status; const char service_name[] = "TERMSRV"; gss_OID type = (gss_OID) GSS_C_NT_HOSTBASED_SERVICE; int size = (strlen(service_name) + 1 + strlen(server) + 1); output.value = malloc(size); snprintf(output.value, size, "%s@%s", service_name, server); output.length = strlen(output.value) + 1; major_status = gss_import_name(&minor_status, &output, type, name); if (GSS_ERROR(major_status)) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to create service principal name", major_status, minor_status); return False; } gss_release_buffer(&minor_status, &output); return True; } static RD_BOOL cssp_gss_wrap(gss_ctx_id_t ctx, STREAM in, STREAM out) { int conf_state; OM_uint32 major_status; OM_uint32 minor_status; gss_buffer_desc inbuf, outbuf; inbuf.value = in->data; inbuf.length = s_length(in); major_status = gss_wrap(&minor_status, ctx, True, GSS_C_QOP_DEFAULT, &inbuf, &conf_state, &outbuf); if (major_status != GSS_S_COMPLETE) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to encrypt and sign message", major_status, minor_status); return False; } if (!conf_state) { logger(Core, Error, "cssp_gss_wrap(), GSS Confidentiality failed, no encryption of message performed."); return False; } // write enc data to out stream out->data = out->p = xmalloc(outbuf.length); out->size = outbuf.length; out_uint8p(out, outbuf.value, outbuf.length); s_mark_end(out); gss_release_buffer(&minor_status, &outbuf); return True; } static RD_BOOL cssp_gss_unwrap(gss_ctx_id_t ctx, STREAM in, STREAM out) { OM_uint32 major_status; OM_uint32 minor_status; gss_qop_t qop_state; gss_buffer_desc inbuf, outbuf; int conf_state; inbuf.value = in->data; inbuf.length = s_length(in); major_status = gss_unwrap(&minor_status, ctx, &inbuf, &outbuf, &conf_state, &qop_state); if (major_status != GSS_S_COMPLETE) { cssp_gss_report_error(GSS_C_GSS_CODE, "Failed to decrypt message", major_status, minor_status); return False; } out->data = out->p = xmalloc(outbuf.length); out->size = outbuf.length; out_uint8p(out, outbuf.value, outbuf.length); s_mark_end(out); gss_release_buffer(&minor_status, &outbuf); return True; } static STREAM cssp_encode_tspasswordcreds(char *username, char *password, char *domain) { STREAM out, h1, h2; struct stream tmp = { 0 }; struct stream message = { 0 }; memset(&tmp, 0, sizeof(tmp)); memset(&message, 0, sizeof(message)); s_realloc(&tmp, 512 * 4); // domainName [0] s_reset(&tmp); out_utf16s(&tmp, domain); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // userName [1] s_reset(&tmp); out_utf16s(&tmp, username); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // password [2] s_reset(&tmp); out_utf16s(&tmp, password); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // build message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup xfree(tmp.data); xfree(message.data); return out; } /* KeySpecs from wincrypt.h */ #define AT_KEYEXCHANGE 1 #define AT_SIGNATURE 2 static STREAM cssp_encode_tscspdatadetail(unsigned char keyspec, char *card, char *reader, char *container, char *csp) { STREAM out; STREAM h1, h2; struct stream tmp = { 0 }; struct stream message = { 0 }; s_realloc(&tmp, 512 * 4); // keySpec [0] s_reset(&tmp); out_uint8(&tmp, keyspec); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // cardName [1] if (card) { s_reset(&tmp); out_utf16s(&tmp, card); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // readerName [2] if (reader) { s_reset(&tmp); out_utf16s(&tmp, reader); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // containerName [3] if (container) { s_reset(&tmp); out_utf16s(&tmp, container); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // cspName [4] if (csp) { s_reset(&tmp); out_utf16s(&tmp, csp); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 4, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } s_mark_end(&message); // build message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup free(tmp.data); free(message.data); return out; } static STREAM cssp_encode_tssmartcardcreds(char *username, char *password, char *domain) { STREAM out, h1, h2; struct stream tmp = { 0 }; struct stream message = { 0 }; s_realloc(&tmp, 512 * 4); // pin [0] s_reset(&tmp); out_utf16s(&tmp, password); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // cspData [1] h2 = cssp_encode_tscspdatadetail(AT_KEYEXCHANGE, g_sc_card_name, g_sc_reader_name, g_sc_container_name, g_sc_csp_name); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // userHint [2] if (username && strlen(username)) { s_reset(&tmp); out_utf16s(&tmp, username); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } // domainHint [3] if (domain && strlen(domain)) { s_reset(&tmp); out_utf16s(&tmp, domain); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } s_mark_end(&message); // build message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup free(tmp.data); free(message.data); return out; } STREAM cssp_encode_tscredentials(char *username, char *password, char *domain) { STREAM out; STREAM h1, h2, h3; struct stream tmp = { 0 }; struct stream message = { 0 }; // credType [0] s_realloc(&tmp, sizeof(uint8)); s_reset(&tmp); if (g_use_password_as_pin == False) { out_uint8(&tmp, 1); // TSPasswordCreds } else { out_uint8(&tmp, 2); // TSSmartCardCreds } s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // credentials [1] if (g_use_password_as_pin == False) { h3 = cssp_encode_tspasswordcreds(username, password, domain); } else { h3 = cssp_encode_tssmartcardcreds(username, password, domain); } h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, h3); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h3); s_free(h2); s_free(h1); // Construct ASN.1 message out = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); // cleanup xfree(message.data); xfree(tmp.data); return out; } RD_BOOL cssp_send_tsrequest(STREAM token, STREAM auth, STREAM pubkey) { STREAM s; STREAM h1, h2, h3, h4, h5; struct stream tmp = { 0 }; struct stream message = { 0 }; memset(&message, 0, sizeof(message)); memset(&tmp, 0, sizeof(tmp)); // version [0] s_realloc(&tmp, sizeof(uint8)); s_reset(&tmp); out_uint8(&tmp, 2); s_mark_end(&tmp); h2 = ber_wrap_hdr_data(BER_TAG_INTEGER, &tmp); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); // negoToken [1] if (token && s_length(token)) { h5 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, token); h4 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0, h5); h3 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, h4); h2 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, h3); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h5); s_free(h4); s_free(h3); s_free(h2); s_free(h1); } // authInfo [2] if (auth && s_length(auth)) { h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, auth); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 2, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_free(h2); s_free(h1); } // pubKeyAuth [3] if (pubkey && s_length(pubkey)) { h2 = ber_wrap_hdr_data(BER_TAG_OCTET_STRING, pubkey); h1 = ber_wrap_hdr_data(BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3, h2); s_realloc(&message, s_length(&message) + s_length(h1)); out_uint8p(&message, h1->data, s_length(h1)); s_mark_end(&message); s_free(h2); s_free(h1); } s_mark_end(&message); // Construct ASN.1 Message // Todo: can h1 be send directly instead of tcp_init() approach h1 = ber_wrap_hdr_data(BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED, &message); s = tcp_init(s_length(h1)); out_uint8p(s, h1->data, s_length(h1)); s_mark_end(s); s_free(h1); tcp_send(s); // cleanup xfree(message.data); xfree(tmp.data); return True; } RD_BOOL cssp_read_tsrequest(STREAM token, STREAM pubkey) { STREAM s; int length; int tagval; s = tcp_recv(NULL, 4); if (s == NULL) return False; // verify ASN.1 header if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) { logger(Protocol, Error, "cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x", s->p[0]); return False; } // peek at first 4 bytes to get full message length if (s->p[1] < 0x80) length = s->p[1] - 2; else if (s->p[1] == 0x81) length = s->p[2] - 1; else if (s->p[1] == 0x82) length = (s->p[2] << 8) | s->p[3]; else return False; // receive the remainings of message s = tcp_recv(s, length); // parse the response and into nego token if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; // version [0] if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; in_uint8s(s, length); // negoToken [1] if (token) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; token->end = token->p = token->data; out_uint8p(token, s->p, length); s_mark_end(token); } // pubKey [3] if (pubkey) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; pubkey->data = pubkey->p = s->p; pubkey->end = pubkey->data + length; pubkey->size = length; } return True; } RD_BOOL cssp_connect(char *server, char *user, char *domain, char *password, STREAM s) { UNUSED(s); OM_uint32 actual_time; gss_cred_id_t cred; gss_buffer_desc input_tok, output_tok; gss_name_t target_name; OM_uint32 major_status, minor_status; int context_established = 0; gss_ctx_id_t gss_ctx; gss_OID desired_mech = &_gss_spnego_krb5_mechanism_oid_desc; STREAM ts_creds; struct stream token = { 0 }; struct stream pubkey = { 0 }; struct stream pubkey_cmp = { 0 }; // Verify that system gss support spnego if (!cssp_gss_mech_available(desired_mech)) { logger(Core, Debug, "cssp_connect(), system doesn't have support for desired authentication mechanism"); return False; } // Get service name if (!cssp_gss_get_service_name(server, &target_name)) { logger(Core, Debug, "cssp_connect(), failed to get target service name"); return False; } // Establish TLS connection to server if (!tcp_tls_connect()) { logger(Core, Debug, "cssp_connect(), failed to establish TLS connection"); return False; } tcp_tls_get_server_pubkey(&pubkey); // Enter the spnego loop OM_uint32 actual_services; gss_OID actual_mech; struct stream blob = { 0 }; gss_ctx = GSS_C_NO_CONTEXT; cred = GSS_C_NO_CREDENTIAL; input_tok.length = 0; output_tok.length = 0; minor_status = 0; int i = 0; do { major_status = gss_init_sec_context(&minor_status, cred, &gss_ctx, target_name, desired_mech, GSS_C_MUTUAL_FLAG | GSS_C_DELEG_FLAG, GSS_C_INDEFINITE, GSS_C_NO_CHANNEL_BINDINGS, &input_tok, &actual_mech, &output_tok, &actual_services, &actual_time); if (GSS_ERROR(major_status)) { if (i == 0) logger(Core, Notice, "Failed to initialize NLA, do you have correct Kerberos TGT initialized ?"); else logger(Core, Error, "cssp_connect(), negotiation failed"); cssp_gss_report_error(GSS_C_GSS_CODE, "cssp_connect(), negotiation failed.", major_status, minor_status); goto bail_out; } // validate required services if (!(actual_services & GSS_C_CONF_FLAG)) { logger(Core, Error, "cssp_connect(), confidentiality service required but is not available"); goto bail_out; } // Send token to server if (output_tok.length != 0) { if (output_tok.length > token.size) s_realloc(&token, output_tok.length); s_reset(&token); out_uint8p(&token, output_tok.value, output_tok.length); s_mark_end(&token); if (!cssp_send_tsrequest(&token, NULL, NULL)) goto bail_out; (void) gss_release_buffer(&minor_status, &output_tok); } // Read token from server if (major_status & GSS_S_CONTINUE_NEEDED) { (void) gss_release_buffer(&minor_status, &input_tok); if (!cssp_read_tsrequest(&token, NULL)) goto bail_out; input_tok.value = token.data; input_tok.length = s_length(&token); } else { // Send encrypted pubkey for verification to server context_established = 1; if (!cssp_gss_wrap(gss_ctx, &pubkey, &blob)) goto bail_out; if (!cssp_send_tsrequest(NULL, NULL, &blob)) goto bail_out; context_established = 1; } i++; } while (!context_established); // read tsrequest response and decrypt for public key validation if (!cssp_read_tsrequest(NULL, &blob)) goto bail_out; if (!cssp_gss_unwrap(gss_ctx, &blob, &pubkey_cmp)) goto bail_out; pubkey_cmp.data[0] -= 1; // validate public key if (memcmp(pubkey.data, pubkey_cmp.data, s_length(&pubkey)) != 0) { logger(Core, Error, "cssp_connect(), public key mismatch, cannot guarantee integrity of server connection"); goto bail_out; } // Send TSCredentials ts_creds = cssp_encode_tscredentials(user, password, domain); if (!cssp_gss_wrap(gss_ctx, ts_creds, &blob)) goto bail_out; s_free(ts_creds); if (!cssp_send_tsrequest(NULL, &blob, NULL)) goto bail_out; return True; bail_out: xfree(token.data); return False; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_486_4
crossvul-cpp_data_good_933_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE % % C O O MM MM P P O O SS I T E % % C O O M M M PPPP O O SSS I T EEE % % C O O M M P O O SS I T E % % CCCC OOO M M P OOO SSSSS IIIII T EEEEE % % % % % % MagickCore Image Composite Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/memory_.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resample.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeImage() returns the second image composited onto the first % at the specified offset, using the specified composite method. % % The format of the CompositeImage method is: % % MagickBooleanType CompositeImage(Image *image, % const Image *source_image,const CompositeOperator compose, % const MagickBooleanType clip_to_self,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the canvas image, modified by he composition % % o source_image: the source image. % % o compose: This operator affects how the composite is applied to % the image. The operators and how they are utilized are listed here % http://www.w3.org/TR/SVG12/#compositing. % % o clip_to_self: set to MagickTrue to limit composition to area composed. % % o x_offset: the column offset of the composited image. % % o y_offset: the row offset of the composited image. % % Extra Controls from Image meta-data in 'image' (artifacts) % % o "compose:args" % A string containing extra numerical arguments for specific compose % methods, generally expressed as a 'geometry' or a comma separated list % of numbers. % % Compose methods needing such arguments include "BlendCompositeOp" and % "DisplaceCompositeOp". % % o exception: return any errors or warnings in this structure. % */ /* Composition based on the SVG specification: A Composition is defined by... Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors Blending areas : X = 1 for area of overlap, ie: f(Sc,Dc) Y = 1 for source preserved Z = 1 for canvas preserved Conversion to transparency (then optimized) Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa) Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa) Where... Sca = Sc*Sa normalized Source color divided by Source alpha Dca = Dc*Da normalized Dest color divided by Dest alpha Dc' = Dca'/Da' the desired color value for this channel. Da' in in the follow formula as 'gamma' The resulting alpla value. Most functions use a blending mode of over (X=1,Y=1,Z=1) this results in the following optimizations... gamma = Sa+Da-Sa*Da; gamma = 1 - QuantumScale*alpha * QuantumScale*beta; opacity = QuantumScale*alpha*beta; // over blend, optimized 1-Gamma The above SVG definitions also define that Mathematical Composition methods should use a 'Over' blending mode for Alpha Channel. It however was not applied for composition modes of 'Plus', 'Minus', the modulus versions of 'Add' and 'Subtract'. Mathematical operator changes to be applied from IM v6.7... 1) Modulus modes 'Add' and 'Subtract' are obsoleted and renamed 'ModulusAdd' and 'ModulusSubtract' for clarity. 2) All mathematical compositions work as per the SVG specification with regard to blending. This now includes 'ModulusAdd' and 'ModulusSubtract'. 3) When the special channel flag 'sync' (syncronize channel updates) is turned off (enabled by default) then mathematical compositions are only performed on the channels specified, and are applied independantally of each other. In other words the mathematics is performed as 'pure' mathematical operations, rather than as image operations. */ static void HCLComposite(const MagickRealType hue,const MagickRealType chroma, const MagickRealType luma,MagickRealType *red,MagickRealType *green, MagickRealType *blue) { MagickRealType b, c, g, h, m, r, x; /* Convert HCL to RGB colorspace. */ assert(red != (MagickRealType *) NULL); assert(green != (MagickRealType *) NULL); assert(blue != (MagickRealType *) NULL); h=6.0*hue; c=chroma; x=c*(1.0-fabs(fmod(h,2.0)-1.0)); r=0.0; g=0.0; b=0.0; if ((0.0 <= h) && (h < 1.0)) { r=c; g=x; } else if ((1.0 <= h) && (h < 2.0)) { r=x; g=c; } else if ((2.0 <= h) && (h < 3.0)) { g=c; b=x; } else if ((3.0 <= h) && (h < 4.0)) { g=x; b=c; } else if ((4.0 <= h) && (h < 5.0)) { r=x; b=c; } else if ((5.0 <= h) && (h < 6.0)) { r=c; b=x; } m=luma-(0.298839*r+0.586811*g+0.114350*b); *red=QuantumRange*(r+m); *green=QuantumRange*(g+m); *blue=QuantumRange*(b+m); } static void CompositeHCL(const MagickRealType red,const MagickRealType green, const MagickRealType blue,MagickRealType *hue,MagickRealType *chroma, MagickRealType *luma) { MagickRealType b, c, g, h, max, r; /* Convert RGB to HCL colorspace. */ assert(hue != (MagickRealType *) NULL); assert(chroma != (MagickRealType *) NULL); assert(luma != (MagickRealType *) NULL); r=red; g=green; b=blue; max=MagickMax(r,MagickMax(g,b)); c=max-(MagickRealType) MagickMin(r,MagickMin(g,b)); h=0.0; if (c == 0) h=0.0; else if (red == max) h=fmod((g-b)/c+6.0,6.0); else if (green == max) h=((b-r)/c)+2.0; else if (blue == max) h=((r-g)/c)+4.0; *hue=(h/6.0); *chroma=QuantumScale*c; *luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b); } static MagickBooleanType CompositeOverImage(Image *image, const Image *source_image,const MagickBooleanType clip_to_self, const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *image_view, *source_view; const char *value; MagickBooleanType clamp, status; MagickOffsetType progress; ssize_t y; /* Composite image. */ status=MagickTrue; progress=0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; PixelInfo canvas_pixel, source_pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, Sa, Sc, Sca; register ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); alpha=Sa+Da-Sa*Da; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((source_traits == UndefinedPixelTrait) && (channel != AlphaPixelChannel)) continue; if (channel == AlphaPixelChannel) { /* Set alpha channel. */ pixel=QuantumRange*alpha; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Sc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; gamma=PerceptibleReciprocal(alpha); pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } MagickExport MagickBooleanType CompositeImage(Image *image, const Image *composite,const CompositeOperator compose, const MagickBooleanType clip_to_self,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *source_view, *image_view; const char *value; GeometryInfo geometry_info; Image *canvas_image, *source_image; MagickBooleanType clamp, status; MagickOffsetType progress; MagickRealType amount, canvas_dissolve, midpoint, percent_luma, percent_chroma, source_dissolve, threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(composite != (Image *) NULL); assert(composite->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); source_image=CloneImage(composite,0,0,MagickTrue,exception); if (source_image == (const Image *) NULL) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); (void) SetImageColorspace(source_image,image->colorspace,exception); if ((compose == OverCompositeOp) || (compose == SrcOverCompositeOp)) { status=CompositeOverImage(image,source_image,clip_to_self,x_offset, y_offset,exception); source_image=DestroyImage(source_image); return(status); } amount=0.5; canvas_image=(Image *) NULL; canvas_dissolve=1.0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); SetGeometryInfo(&geometry_info); percent_luma=100.0; percent_chroma=100.0; source_dissolve=1.0; threshold=0.05f; switch (compose) { case CopyCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { register ssize_t i; if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(source_image); i++) { PixelChannel channel = GetPixelChannelChannel(source_image,i); PixelTrait source_traits = GetPixelChannelTraits(source_image, channel); PixelTrait traits = GetPixelChannelTraits(image,channel); if (source_traits == UndefinedPixelTrait) continue; if (traits != UndefinedPixelTrait) SetPixelChannel(image,channel,p[i],q); else if (channel == AlphaPixelChannel) SetPixelChannel(image,channel,OpaqueAlpha,q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case IntensityCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *p; register Quantum *q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } SetPixelAlpha(image,clamp != MagickFalse ? ClampPixel(GetPixelIntensity(source_image,p)) : ClampToQuantum(GetPixelIntensity(source_image,p)),q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case CopyAlphaCompositeOp: case ChangeMaskCompositeOp: { /* Modify canvas outside the overlaid region and require an alpha channel to exist, to add transparency. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); break; } case BlurCompositeOp: { CacheView *canvas_view; MagickRealType angle_range, angle_start, height, width; PixelInfo pixel; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling. Blur Image dictated by an overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,angle]]. */ canvas_image=CloneImage(image,0,0,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } /* Gather the maximum blur sigma values from user. */ flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (const char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & WidthValue) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidSetting","'%s' '%s'","compose:args",value); source_image=DestroyImage(source_image); canvas_image=DestroyImage(canvas_image); return(MagickFalse); } /* Users input sigma now needs to be converted to the EWA ellipse size. The filter defaults to a sigma of 0.5 so to make this match the users input the ellipse size needs to be doubled. */ width=height=geometry_info.rho*2.0; if ((flags & HeightValue) != 0 ) height=geometry_info.sigma*2.0; /* Default the unrotated ellipse width and height axis vectors. */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; /* rotate vectors if a rotation angle is given */ if ((flags & XValue) != 0 ) { MagickRealType angle; angle=DegreesToRadians(geometry_info.xi); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } /* Otherwise lets set a angle range and calculate in the loop */ angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { angle_start=DegreesToRadians(geometry_info.xi); angle_range=DegreesToRadians(geometry_info.psi)-angle_start; } /* Set up a gaussian cylindrical filter for EWA Bluring. As the minimum ellipse radius of support*1.0 the EWA algorithm can only produce a minimum blur of 0.5 for Gaussian (support=2.0) This means that even 'No Blur' will be still a little blurry! The solution (as well as the problem of preventing any user expert filter settings, is to set our own user settings, then restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter); /* do the variable blurring of each pixel in image */ GetPixelInfo(image,&pixel); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } if (fabs((double) angle_range) > MagickEpsilon) { MagickRealType angle; angle=angle_start+angle_range*QuantumScale* GetPixelBlue(source_image,p); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } #if 0 if ( x == 10 && y == 60 ) { (void) fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n",blur.x1, blur.x2,blur.y1, blur.y2); (void) fprintf(stderr, "scaled by=%lf,%lf\n",QuantumScale* GetPixelRed(p),QuantumScale*GetPixelGreen(p)); #endif ScaleResampleFilter(resample_filter, blur.x1*QuantumScale*GetPixelRed(source_image,p), blur.y1*QuantumScale*GetPixelGreen(source_image,p), blur.x2*QuantumScale*GetPixelRed(source_image,p), blur.y2*QuantumScale*GetPixelGreen(source_image,p) ); (void) ResamplePixelColor(resample_filter,(double) x_offset+x, (double) y_offset+y,&pixel,exception); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } resample_filter=DestroyResampleFilter(resample_filter); source_view=DestroyCacheView(source_view); canvas_view=DestroyCacheView(canvas_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DisplaceCompositeOp: case DistortCompositeOp: { CacheView *canvas_view; MagickRealType horizontal_scale, vertical_scale; PixelInfo pixel; PointInfo center, offset; /* Displace/Distort based on overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,center.x,center.y]] */ canvas_image=CloneImage(image,0,0,MagickTrue, exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & (WidthValue | HeightValue)) == 0 ) { if ((flags & AspectValue) == 0) { horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0; vertical_scale=(MagickRealType) (source_image->rows-1)/2.0; } else { horizontal_scale=(MagickRealType) (image->columns-1)/2.0; vertical_scale=(MagickRealType) (image->rows-1)/2.0; } } else { horizontal_scale=geometry_info.rho; vertical_scale=geometry_info.sigma; if ((flags & PercentValue) != 0) { if ((flags & AspectValue) == 0) { horizontal_scale*=(source_image->columns-1)/200.0; vertical_scale*=(source_image->rows-1)/200.0; } else { horizontal_scale*=(image->columns-1)/200.0; vertical_scale*=(image->rows-1)/200.0; } } if ((flags & HeightValue) == 0) vertical_scale=horizontal_scale; } /* Determine fixed center point for absolute distortion map Absolute distort == Displace offset relative to a fixed absolute point Select that point according to +X+Y user inputs. default = center of overlay image arg flag '!' = locations/percentage relative to background image */ center.x=(MagickRealType) x_offset; center.y=(MagickRealType) y_offset; if (compose == DistortCompositeOp) { if ((flags & XValue) == 0) if ((flags & AspectValue) != 0) center.x=(MagickRealType) ((image->columns-1)/2.0); else center.x=(MagickRealType) (x_offset+(source_image->columns-1)/ 2.0); else if ((flags & AspectValue) != 0) center.x=geometry_info.xi; else center.x=(MagickRealType) (x_offset+geometry_info.xi); if ((flags & YValue) == 0) if ((flags & AspectValue) != 0) center.y=(MagickRealType) ((image->rows-1)/2.0); else center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0); else if ((flags & AspectValue) != 0) center.y=geometry_info.psi; else center.y=(MagickRealType) (y_offset+geometry_info.psi); } /* Shift the pixel offset point as defined by the provided, displacement/distortion map. -- Like a lens... */ GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } /* Displace the offset. */ offset.x=(double) (horizontal_scale*(GetPixelRed(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ? x : 0); offset.y=(double) (vertical_scale*(GetPixelGreen(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ? y : 0); status=InterpolatePixelInfo(image,image_view, UndefinedInterpolatePixel,(double) offset.x,(double) offset.y, &pixel,exception); if (status == MagickFalse) break; /* Mask with the 'invalid pixel mask' in alpha channel. */ pixel.alpha=(MagickRealType) QuantumRange*(QuantumScale*pixel.alpha)* (QuantumScale*GetPixelAlpha(source_image,p)); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } if (x < (ssize_t) source_image->columns) break; sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } canvas_view=DestroyCacheView(canvas_view); source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DissolveCompositeOp: { /* Geometry arguments to dissolve factors. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0; if ((source_dissolve-MagickEpsilon) < 0.0) source_dissolve=0.0; if ((source_dissolve+MagickEpsilon) > 1.0) { canvas_dissolve=2.0-source_dissolve; source_dissolve=1.0; } if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; if ((canvas_dissolve-MagickEpsilon) < 0.0) canvas_dissolve=0.0; } break; } case BlendCompositeOp: { value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0-source_dissolve; if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; } break; } case MathematicsCompositeOp: { /* Just collect the values from "compose:args", setting. Unused values are set to zero automagically. Arguments are normally a comma separated list, so this probably should be changed to some 'general comma list' parser, (with a minimum number of values) */ SetGeometryInfo(&geometry_info); value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) (void) ParseGeometry(value,&geometry_info); break; } case ModulateCompositeOp: { /* Determine the luma and chroma scale. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); percent_luma=geometry_info.rho; if ((flags & SigmaValue) != 0) percent_chroma=geometry_info.sigma; } break; } case ThresholdCompositeOp: { /* Determine the amount and threshold. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); amount=geometry_info.rho; threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold=0.05f; } threshold*=QuantumRange; break; } default: break; } /* Composite image. */ status=MagickTrue; progress=0; midpoint=((MagickRealType) QuantumRange+1.0)/2; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; MagickRealType blue, chroma, green, hue, luma, red; PixelInfo canvas_pixel, source_pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } hue=0.0; chroma=0.0; luma=0.0; GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, DcaDa, Sa, SaSca, Sc, Sca; register ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; switch (compose) { case AlphaCompositeOp: case ChangeMaskCompositeOp: case CopyAlphaCompositeOp: case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case OutCompositeOp: case SrcInCompositeOp: case SrcOutCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; break; } case ClearCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=0.0; break; } case BlendCompositeOp: case DissolveCompositeOp: { if (channel == AlphaPixelChannel) pixel=canvas_dissolve*GetPixelAlpha(source_image,source); else pixel=(MagickRealType) source[channel]; break; } default: { pixel=(MagickRealType) source[channel]; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); switch (compose) { case BumpmapCompositeOp: { alpha=GetPixelIntensity(source_image,p)*Sa; break; } case ColorBurnCompositeOp: case ColorDodgeCompositeOp: case DarkenCompositeOp: case DifferenceCompositeOp: case DivideDstCompositeOp: case DivideSrcCompositeOp: case ExclusionCompositeOp: case HardLightCompositeOp: case HardMixCompositeOp: case LinearBurnCompositeOp: case LinearDodgeCompositeOp: case LinearLightCompositeOp: case LightenCompositeOp: case MathematicsCompositeOp: case MinusDstCompositeOp: case MinusSrcCompositeOp: case ModulusAddCompositeOp: case ModulusSubtractCompositeOp: case MultiplyCompositeOp: case OverlayCompositeOp: case PegtopLightCompositeOp: case PinLightCompositeOp: case ScreenCompositeOp: case SoftLightCompositeOp: case VividLightCompositeOp: { alpha=RoundToUnity(Sa+Da-Sa*Da); break; } case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case SrcInCompositeOp: { alpha=Sa*Da; break; } case DissolveCompositeOp: { alpha=source_dissolve*Sa*(-canvas_dissolve*Da)+source_dissolve*Sa+ canvas_dissolve*Da; break; } case DstOverCompositeOp: case OverCompositeOp: case SrcOverCompositeOp: { alpha=Sa+Da-Sa*Da; break; } case DstOutCompositeOp: { alpha=Da*(1.0-Sa); break; } case OutCompositeOp: case SrcOutCompositeOp: { alpha=Sa*(1.0-Da); break; } case BlendCompositeOp: case PlusCompositeOp: { alpha=RoundToUnity(source_dissolve*Sa+canvas_dissolve*Da); break; } case XorCompositeOp: { alpha=Sa+Da-2.0*Sa*Da; break; } default: { alpha=1.0; break; } } switch (compose) { case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case ModulateCompositeOp: case SaturateCompositeOp: { GetPixelInfoPixel(source_image,p,&source_pixel); GetPixelInfoPixel(image,q,&canvas_pixel); break; } default: break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel, sans; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits = GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((channel == AlphaPixelChannel) && ((traits & UpdatePixelTrait) != 0)) { /* Set alpha channel. */ switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case CopyBlackCompositeOp: case CopyBlueCompositeOp: case CopyCyanCompositeOp: case CopyGreenCompositeOp: case CopyMagentaCompositeOp: case CopyRedCompositeOp: case CopyYellowCompositeOp: case SrcAtopCompositeOp: case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Da; break; } case ChangeMaskCompositeOp: { MagickBooleanType equivalent; if (Da < 0.5) { pixel=(MagickRealType) TransparentAlpha; break; } equivalent=IsFuzzyEquivalencePixel(source_image,p,image,q); if (equivalent != MagickFalse) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) OpaqueAlpha; break; } case ClearCompositeOp: { pixel=(MagickRealType) TransparentAlpha; break; } case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Da; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Sa; break; } if (Sa < Da) { pixel=QuantumRange*Da; break; } pixel=QuantumRange*Sa; break; } case CopyAlphaCompositeOp: { if (source_image->alpha_trait == UndefinedPixelTrait) pixel=GetPixelIntensity(source_image,p); else pixel=QuantumRange*Sa; break; } case CopyCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: case DstAtopCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sa; break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case DifferenceCompositeOp: { pixel=QuantumRange*fabs(Sa-Da); break; } case LightenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case ModulateCompositeOp: { pixel=QuantumRange*Da; break; } case MultiplyCompositeOp: { pixel=QuantumRange*Sa*Da; break; } case StereoCompositeOp: { pixel=QuantumRange*(Sa+Da)/2; break; } default: { pixel=QuantumRange*alpha; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } if (source_traits == UndefinedPixelTrait) continue; /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Dc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; SaSca=Sa*PerceptibleReciprocal(Sca); DcaDa=Dca*PerceptibleReciprocal(Da); switch (compose) { case DarkenCompositeOp: case LightenCompositeOp: case ModulusSubtractCompositeOp: { gamma=PerceptibleReciprocal(1.0-alpha); break; } default: { gamma=PerceptibleReciprocal(alpha); break; } } pixel=Dc; switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case SrcAtopCompositeOp: { pixel=QuantumRange*(Sca*Da+Dca*(1.0-Sa)); break; } case BlendCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc+canvas_dissolve*Da*Dc); break; } case BlurCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sca; break; } case DisplaceCompositeOp: case DistortCompositeOp: { pixel=Sc; break; } case BumpmapCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } pixel=QuantumScale*GetPixelIntensity(source_image,p)*Dc; break; } case ChangeMaskCompositeOp: { pixel=Dc; break; } case ClearCompositeOp: { pixel=0.0; break; } case ColorBurnCompositeOp: { if ((Sca == 0.0) && (Dca == Da)) { pixel=QuantumRange*gamma*(Sa*Da+Dca*(1.0-Sa)); break; } if (Sca == 0.0) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-Sa*Da*MagickMin(1.0,(1.0-DcaDa)* SaSca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorDodgeCompositeOp: { if ((Sca*Da+Dca*Sa) >= Sa*Da) pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); else pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(Sa-Sca)+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &sans,&sans,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case CopyAlphaCompositeOp: { pixel=Dc; break; } case CopyBlackCompositeOp: { if (channel == BlackPixelChannel) pixel=(MagickRealType) (QuantumRange- GetPixelBlack(source_image,p)); break; } case CopyBlueCompositeOp: case CopyYellowCompositeOp: { if (channel == BluePixelChannel) pixel=(MagickRealType) GetPixelBlue(source_image,p); break; } case CopyGreenCompositeOp: case CopyMagentaCompositeOp: { if (channel == GreenPixelChannel) pixel=(MagickRealType) GetPixelGreen(source_image,p); break; } case CopyRedCompositeOp: case CopyCyanCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case DarkenCompositeOp: { /* Darken is equivalent to a 'Minimum' method OR a greyscale version of a binary 'Or' OR the 'Intersection' of pixel sets. */ if ((Sca*Da) < (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case DarkenIntensityCompositeOp: { pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case DifferenceCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca-2.0*MagickMin(Sca*Da,Dca*Sa)); break; } case DissolveCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc-source_dissolve*Sa* canvas_dissolve*Da*Dc+canvas_dissolve*Da*Dc); break; } case DivideDstCompositeOp: { if ((fabs((double) Sca) < MagickEpsilon) && (fabs((double) Dca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (fabs((double) Dca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case DivideSrcCompositeOp: { if ((fabs((double) Dca) < MagickEpsilon) && (fabs((double) Sca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } if (fabs((double) Sca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Da*Sa+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } pixel=QuantumRange*gamma*(Dca*Sa*SaSca+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } case DstAtopCompositeOp: { pixel=QuantumRange*(Dca*Sa+Sca*(1.0-Da)); break; } case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Dca; break; } case DstInCompositeOp: { pixel=QuantumRange*(Dca*Sa); break; } case DstOutCompositeOp: { pixel=QuantumRange*(Dca*(1.0-Sa)); break; } case DstOverCompositeOp: { pixel=QuantumRange*gamma*(Dca+Sca*(1.0-Da)); break; } case ExclusionCompositeOp: { pixel=QuantumRange*gamma*(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0- Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardMixCompositeOp: { pixel=gamma*(((Sca+Dca) < 1.0) ? 0.0 : QuantumRange); break; } case HueCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&sans,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case InCompositeOp: case SrcInCompositeOp: { pixel=QuantumRange*(Sca*Da); break; } case LinearBurnCompositeOp: { /* LinearBurn: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Sc + Dc - 1 */ pixel=QuantumRange*gamma*(Sca+Dca-Sa*Da); break; } case LinearDodgeCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc); break; } case LinearLightCompositeOp: { /* LinearLight: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Dc + 2*Sc - 1 */ pixel=QuantumRange*gamma*((Sca-Sa)*Da+Sca+Dca); break; } case LightenCompositeOp: { if ((Sca*Da) > (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case LightenIntensityCompositeOp: { /* Lighten is equivalent to a 'Maximum' method OR a greyscale version of a binary 'And' OR the 'Union' of pixel sets. */ pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case LuminizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&sans,&luma); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case MathematicsCompositeOp: { /* 'Mathematics' a free form user control mathematical composition is defined as... f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D Where the arguments A,B,C,D are (currently) passed to composite as a command separated 'geometry' string in "compose:args" image artifact. A = a->rho, B = a->sigma, C = a->xi, D = a->psi Applying the SVG transparency formula (see above), we get... Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa) Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) */ pixel=QuantumRange*gamma*(geometry_info.rho*Sca*Dca+ geometry_info.sigma*Sca*Da+geometry_info.xi*Dca*Sa+ geometry_info.psi*Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case MinusDstCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc-2.0*Da*Dc*Sa); break; } case MinusSrcCompositeOp: { /* Minus source from canvas. f(Sc,Dc) = Sc - Dc */ pixel=gamma*(Da*Dc+Sa*Sc-2.0*Sa*Sc*Da); break; } case ModulateCompositeOp: { ssize_t offset; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } offset=(ssize_t) (GetPixelIntensity(source_image,p)-midpoint); if (offset == 0) { pixel=Dc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); luma+=(0.01*percent_luma*offset)/midpoint; chroma*=0.01*percent_chroma; HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ModulusAddCompositeOp: { pixel=Sc+Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case ModulusSubtractCompositeOp: { pixel=Sc-Dc; while (pixel > QuantumRange) pixel-=QuantumRange; while (pixel < 0.0) pixel+=QuantumRange; pixel=(Sa*Da*pixel+Sa*Sc*(1.0-Da)+Da*Dc*(1.0-Sa)); break; } case MultiplyCompositeOp: { pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case OutCompositeOp: case SrcOutCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)); break; } case OverCompositeOp: case SrcOverCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); break; } case OverlayCompositeOp: { if ((2.0*Dca) < Da) { pixel=QuantumRange*gamma*(2.0*Dca*Sca+Dca*(1.0-Sa)+Sca*(1.0- Da)); break; } pixel=QuantumRange*gamma*(Da*Sa-2.0*(Sa-Sca)*(Da-Dca)+Dca*(1.0-Sa)+ Sca*(1.0-Da)); break; } case PegtopLightCompositeOp: { /* PegTop: A Soft-Light alternative: A continuous version of the Softlight function, producing very similar results. f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm. */ if (fabs((double) Da) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sca); break; } pixel=QuantumRange*gamma*(Dca*Dca*(Sa-2.0*Sca)/Da+Sca*(2.0*Dca+1.0- Da)+Dca*(1.0-Sa)); break; } case PinLightCompositeOp: { /* PinLight: A Photoshop 7 composition method http://www.simplefilter.de/en/basics/mixmods.html f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc */ if ((Dca*Sa) < (Da*(2.0*Sca-Sa))) { pixel=QuantumRange*gamma*(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa)); break; } if ((Dca*Sa) > (2.0*Sca*Da)) { pixel=QuantumRange*gamma*(Sca*Da+Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca); break; } case PlusCompositeOp: { pixel=QuantumRange*(Sca+Dca); break; } case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ScreenCompositeOp: { /* Screen: a negated multiply: f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc) */ pixel=QuantumRange*gamma*(Sca+Dca-Sca*Dca); break; } case SoftLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(Dca*(Sa+(2.0*Sca-Sa)*(1.0-DcaDa))+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da)) { pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*DcaDa* (4.0*DcaDa+1.0)*(DcaDa-1.0)+7.0*DcaDa)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(pow(DcaDa,0.5)- DcaDa)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case StereoCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case ThresholdCompositeOp: { MagickRealType delta; delta=Sc-Dc; if ((MagickRealType) fabs((double) (2.0*delta)) < threshold) { pixel=gamma*Dc; break; } pixel=gamma*(Dc+delta*amount); break; } case VividLightCompositeOp: { /* VividLight: A Photoshop 7 composition method. See http://www.simplefilter.de/en/basics/mixmods.html. f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc)) */ if ((fabs((double) Sa) < MagickEpsilon) || (fabs((double) (Sca-Sa)) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if ((2.0*Sca) <= Sa) { pixel=QuantumRange*gamma*(Sa*(Da+Sa*(Dca-Da)* PerceptibleReciprocal(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(2.0* (Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case XorCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } default: { pixel=Sc; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); if (canvas_image != (Image * ) NULL) canvas_image=DestroyImage(canvas_image); else source_image=DestroyImage(source_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e x t u r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TextureImage() repeatedly tiles the texture image across and down the image % canvas. % % The format of the TextureImage method is: % % MagickBooleanType TextureImage(Image *image,const Image *texture, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o texture_image: This image is the texture to layer on the background. % */ MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture, ExceptionInfo *exception) { #define TextureImageTag "Texture/Image" CacheView *image_view, *texture_view; Image *texture_image; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (texture == (const Image *) NULL) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); texture_image=CloneImage(texture,0,0,MagickTrue,exception); if (texture_image == (const Image *) NULL) return(MagickFalse); (void) TransformImageColorspace(texture_image,image->colorspace,exception); (void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod, exception); status=MagickTrue; if ((image->compose != CopyCompositeOp) && ((image->compose != OverCompositeOp) || (image->alpha_trait != UndefinedPixelTrait) || (texture_image->alpha_trait != UndefinedPixelTrait))) { /* Tile texture onto the image background. */ for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { MagickBooleanType thread_status; thread_status=CompositeImage(image,texture_image,image->compose, MagickTrue,x+texture_image->tile_offset.x,y+ texture_image->tile_offset.y,exception); if (thread_status == MagickFalse) { status=thread_status; break; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,TextureImageTag,(MagickOffsetType) image->rows,image->rows); texture_image=DestroyImage(texture_image); return(status); } /* Tile texture onto the image background (optimized). */ status=MagickTrue; texture_view=AcquireVirtualCacheView(texture_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(texture_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const Quantum *p, *pixels; register ssize_t x; register Quantum *q; size_t width; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x, (y+texture_image->tile_offset.y) % texture_image->rows, texture_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((pixels == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { register ssize_t j; p=pixels; width=texture_image->columns; if ((x+(ssize_t) width) > (ssize_t) image->columns) width=image->columns-x; for (j=0; j < (ssize_t) width; j++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(texture_image); i++) { PixelChannel channel = GetPixelChannelChannel(texture_image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait texture_traits=GetPixelChannelTraits(texture_image, channel); if ((traits == UndefinedPixelTrait) || (texture_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(texture_image); q+=GetPixelChannels(image); } } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } texture_view=DestroyCacheView(texture_view); image_view=DestroyCacheView(image_view); texture_image=DestroyImage(texture_image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_933_0
crossvul-cpp_data_good_5307_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V V IIIII FFFFF FFFFF % % V V I F F % % V V I FFF FFF % % V V I F F % % V IIIII F F % % % % % % Read/Write Khoros Visualization Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* Forward declarations. */ static MagickBooleanType WriteVIFFImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s V I F F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsVIFF() returns MagickTrue if the image format type, identified by the % magick string, is VIFF. % % The format of the IsVIFF method is: % % MagickBooleanType IsVIFF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsVIFF(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if (memcmp(magick,"\253\001",2) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadVIFFImage() reads a Khoros Visualization image file and returns % it. It allocates the memory necessary for the new Image structure and % returns a pointer to the new image. % % The format of the ReadVIFFImage method is: % % Image *ReadVIFFImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadVIFFImage returns a pointer to the image after % reading. A null image is returned if there is a memory shortage or if % the image cannot be read. % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,"NotAVIFFImage"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); (void) ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,"comment",viff_info.comment); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (number_pixels == 0) ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,"LocationTypeIsNotSupported"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read VIFF raster colormap. */ (void) ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green=ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green=ScaleCharToQuantum( (unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue=ScaleCharToQuantum( (unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } /* Initialize image structure. */ image->matte=viff_info.number_data_bands == 4 ? MagickTrue : MagickFalse; image->storage_class= (viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels, max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(MagickRealType) QuantumRange/min_value; min_value=0; } else scale_factor=(MagickRealType) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ if (image->storage_class != PseudoClass) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(q,quantum == 0 ? 0 : QuantumRange); SetPixelGreen(q,quantum == 0 ? 0 : QuantumRange); SetPixelBlue(q,quantum == 0 ? 0 : QuantumRange); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+bit,quantum); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p)); SetPixelGreen(q,ScaleCharToQuantum(*(p+number_pixels))); SetPixelBlue(q,ScaleCharToQuantum(*(p+2*number_pixels))); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(q); SetPixelRed(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].red); index=(ssize_t) GetPixelGreen(q); SetPixelGreen(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].green); index=(ssize_t) GetPixelRed(q); SetPixelBlue(q,image->colormap[(ssize_t) ConstrainColormapIndex(image,index)].blue); } SetPixelOpacity(q,image->matte != MagickFalse ? QuantumRange- ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterVIFFImage() adds properties for the VIFF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterVIFFImage method is: % % size_t RegisterVIFFImage(void) % */ ModuleExport size_t RegisterVIFFImage(void) { MagickInfo *entry; entry=SetMagickInfo("VIFF"); entry->decoder=(DecodeImageHandler *) ReadVIFFImage; entry->encoder=(EncodeImageHandler *) WriteVIFFImage; entry->magick=(IsImageFormatHandler *) IsVIFF; entry->description=ConstantString("Khoros Visualization image"); entry->module=ConstantString("VIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("XV"); entry->decoder=(DecodeImageHandler *) ReadVIFFImage; entry->encoder=(EncodeImageHandler *) WriteVIFFImage; entry->description=ConstantString("Khoros Visualization image"); entry->module=ConstantString("VIFF"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterVIFFImage() removes format registrations made by the % VIFF module from the list of supported formats. % % The format of the UnregisterVIFFImage method is: % % UnregisterVIFFImage(void) % */ ModuleExport void UnregisterVIFFImage(void) { (void) UnregisterMagickInfo("VIFF"); (void) UnregisterMagickInfo("XV"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e V I F F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteVIFFImage() writes an image to a file in the VIFF image format. % % The format of the WriteVIFFImage method is: % % MagickBooleanType WriteVIFFImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteVIFFImage(const ImageInfo *image_info, Image *image) { #define VFF_CM_genericRGB 15 #define VFF_CM_NONE 0 #define VFF_DEP_IEEEORDER 0x2 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 typedef struct _ViffInfo { char identifier, file_type, release, version, machine_dependency, reserve[3], comment[512]; size_t rows, columns, subrows; int x_offset, y_offset; unsigned int x_bits_per_pixel, y_bits_per_pixel, location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; const char *value; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels, packets; MemoryInfo *pixel_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; register ssize_t i; register unsigned char *q; ssize_t y; unsigned char *pixels; ViffInfo viff_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) ResetMagickMemory(&viff_info,0,sizeof(ViffInfo)); scene=0; do { /* Initialize VIFF image structure. */ (void) TransformImageColorspace(image,sRGBColorspace); DisableMSCWarning(4310) viff_info.identifier=(char) 0xab; RestoreMSCWarning viff_info.file_type=1; viff_info.release=1; viff_info.version=3; viff_info.machine_dependency=VFF_DEP_IEEEORDER; /* IEEE byte ordering */ *viff_info.comment='\0'; value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) (void) CopyMagickString(viff_info.comment,value,MagickMin(strlen(value), 511)+1); viff_info.rows=image->columns; viff_info.columns=image->rows; viff_info.subrows=0; viff_info.x_offset=(~0); viff_info.y_offset=(~0); viff_info.x_bits_per_pixel=0; viff_info.y_bits_per_pixel=0; viff_info.location_type=VFF_LOC_IMPLICIT; viff_info.location_dimension=0; viff_info.number_of_images=1; viff_info.data_encode_scheme=VFF_DES_RAW; viff_info.map_scheme=VFF_MS_NONE; viff_info.map_storage_type=VFF_MAPTYP_NONE; viff_info.map_rows=0; viff_info.map_columns=0; viff_info.map_subrows=0; viff_info.map_enable=1; /* no colormap */ viff_info.maps_per_cycle=0; number_pixels=(MagickSizeType) image->columns*image->rows; if (image->storage_class == DirectClass) { /* Full color VIFF raster. */ viff_info.number_data_bands=image->matte ? 4U : 3U; viff_info.color_space_model=VFF_CM_genericRGB; viff_info.data_storage_type=VFF_TYP_1_BYTE; packets=viff_info.number_data_bands*number_pixels; } else { viff_info.number_data_bands=1; viff_info.color_space_model=VFF_CM_NONE; viff_info.data_storage_type=VFF_TYP_1_BYTE; packets=number_pixels; if (SetImageGray(image,&image->exception) == MagickFalse) { /* Colormapped VIFF raster. */ viff_info.map_scheme=VFF_MS_ONEPERBAND; viff_info.map_storage_type=VFF_MAPTYP_1_BYTE; viff_info.map_rows=3; viff_info.map_columns=(unsigned int) image->colors; } else if (image->colors <= 2) { /* Monochrome VIFF raster. */ viff_info.data_storage_type=VFF_TYP_BIT; packets=((image->columns+7) >> 3)*image->rows; } } /* Write VIFF image header (pad to 1024 bytes). */ (void) WriteBlob(image,sizeof(viff_info.identifier),(unsigned char *) &viff_info.identifier); (void) WriteBlob(image,sizeof(viff_info.file_type),(unsigned char *) &viff_info.file_type); (void) WriteBlob(image,sizeof(viff_info.release),(unsigned char *) &viff_info.release); (void) WriteBlob(image,sizeof(viff_info.version),(unsigned char *) &viff_info.version); (void) WriteBlob(image,sizeof(viff_info.machine_dependency), (unsigned char *) &viff_info.machine_dependency); (void) WriteBlob(image,sizeof(viff_info.reserve),(unsigned char *) viff_info.reserve); (void) WriteBlob(image,512,(unsigned char *) viff_info.comment); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.rows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.columns); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.subrows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_offset); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_offset); viff_info.x_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16)); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.x_bits_per_pixel); viff_info.y_bits_per_pixel=(unsigned int) ((63 << 24) | (128 << 16)); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.y_bits_per_pixel); (void) WriteBlobMSBLong(image,viff_info.location_type); (void) WriteBlobMSBLong(image,viff_info.location_dimension); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_of_images); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.number_data_bands); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_storage_type); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.data_encode_scheme); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_scheme); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_storage_type); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_rows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_columns); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_subrows); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.map_enable); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.maps_per_cycle); (void) WriteBlobMSBLong(image,(unsigned int) viff_info.color_space_model); for (i=0; i < 420; i++) (void) WriteBlobByte(image,'\0'); /* Convert MIFF to VIFF raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) packets,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); q=pixels; if (image->storage_class == DirectClass) { /* Convert DirectClass packet to VIFF RGB pixel. */ number_pixels=(MagickSizeType) image->columns*image->rows; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q=ScaleQuantumToChar(GetPixelRed(p)); *(q+number_pixels)=ScaleQuantumToChar(GetPixelGreen(p)); *(q+number_pixels*2)=ScaleQuantumToChar(GetPixelBlue(p)); if (image->matte != MagickFalse) *(q+number_pixels*3)=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; q++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (SetImageGray(image,&image->exception) == MagickFalse) { unsigned char *viff_colormap; /* Dump colormap to file. */ viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 3*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=viff_colormap; for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].red); for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].green); for (i=0; i < (ssize_t) image->colors; i++) *q++=ScaleQuantumToChar(image->colormap[i].blue); (void) WriteBlob(image,3*image->colors,viff_colormap); viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); /* Convert PseudoClass packet to VIFF colormapped pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->colors <= 2) { ssize_t x, y; register unsigned char bit, byte; /* Convert PseudoClass image to a VIFF monochrome image. */ (void) SetImageType(image,BilevelType); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x80; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } } if (bit != 0) *q++=byte >> (8-bit); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else { /* Convert PseudoClass packet to VIFF grayscale pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) ClampToQuantum(GetPixelLuma(image,p)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } (void) WriteBlob(image,(size_t) packets,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5307_0
crossvul-cpp_data_good_2754_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IPv6 routing header printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "ip6.h" #include "netdissect.h" #include "addrtoname.h" #include "extract.h" int rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2 _U_) { register const struct ip6_rthdr *dp; register const struct ip6_rthdr0 *dp0; register const u_char *ep; int i, len; register const struct in6_addr *addr; dp = (const struct ip6_rthdr *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; ND_TCHECK(dp->ip6r_segleft); len = dp->ip6r_len; ND_PRINT((ndo, "srcrt (len=%d", dp->ip6r_len)); /*)*/ ND_PRINT((ndo, ", type=%d", dp->ip6r_type)); ND_PRINT((ndo, ", segleft=%d", dp->ip6r_segleft)); switch (dp->ip6r_type) { case IPV6_RTHDR_TYPE_0: case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */ dp0 = (const struct ip6_rthdr0 *)dp; ND_TCHECK(dp0->ip6r0_reserved); if (dp0->ip6r0_reserved || ndo->ndo_vflag) { ND_PRINT((ndo, ", rsv=0x%0x", EXTRACT_32BITS(&dp0->ip6r0_reserved))); } if (len % 2 == 1) goto trunc; len >>= 1; addr = &dp0->ip6r0_addr[0]; for (i = 0; i < len; i++) { if ((const u_char *)(addr + 1) > ep) goto trunc; ND_PRINT((ndo, ", [%d]%s", i, ip6addr_string(ndo, addr))); addr++; } /*(*/ ND_PRINT((ndo, ") ")); return((dp0->ip6r0_len + 1) << 3); break; default: goto trunc; break; } trunc: ND_PRINT((ndo, "[|srcrt]")); return -1; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2754_0
crossvul-cpp_data_good_2681_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: Network File System (NFS) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "nfs.h" #include "nfsfh.h" #include "ip.h" #include "ip6.h" #include "rpc_auth.h" #include "rpc_msg.h" static const char tstr[] = " [|nfs]"; static void nfs_printfh(netdissect_options *, const uint32_t *, const u_int); static int xid_map_enter(netdissect_options *, const struct sunrpc_msg *, const u_char *); static int xid_map_find(const struct sunrpc_msg *, const u_char *, uint32_t *, uint32_t *); static void interp_reply(netdissect_options *, const struct sunrpc_msg *, uint32_t, uint32_t, int); static const uint32_t *parse_post_op_attr(netdissect_options *, const uint32_t *, int); /* * Mapping of old NFS Version 2 RPC numbers to generic numbers. */ static uint32_t nfsv3_procid[NFS_NPROCS] = { NFSPROC_NULL, NFSPROC_GETATTR, NFSPROC_SETATTR, NFSPROC_NOOP, NFSPROC_LOOKUP, NFSPROC_READLINK, NFSPROC_READ, NFSPROC_NOOP, NFSPROC_WRITE, NFSPROC_CREATE, NFSPROC_REMOVE, NFSPROC_RENAME, NFSPROC_LINK, NFSPROC_SYMLINK, NFSPROC_MKDIR, NFSPROC_RMDIR, NFSPROC_READDIR, NFSPROC_FSSTAT, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP }; static const struct tok nfsproc_str[] = { { NFSPROC_NOOP, "nop" }, { NFSPROC_NULL, "null" }, { NFSPROC_GETATTR, "getattr" }, { NFSPROC_SETATTR, "setattr" }, { NFSPROC_LOOKUP, "lookup" }, { NFSPROC_ACCESS, "access" }, { NFSPROC_READLINK, "readlink" }, { NFSPROC_READ, "read" }, { NFSPROC_WRITE, "write" }, { NFSPROC_CREATE, "create" }, { NFSPROC_MKDIR, "mkdir" }, { NFSPROC_SYMLINK, "symlink" }, { NFSPROC_MKNOD, "mknod" }, { NFSPROC_REMOVE, "remove" }, { NFSPROC_RMDIR, "rmdir" }, { NFSPROC_RENAME, "rename" }, { NFSPROC_LINK, "link" }, { NFSPROC_READDIR, "readdir" }, { NFSPROC_READDIRPLUS, "readdirplus" }, { NFSPROC_FSSTAT, "fsstat" }, { NFSPROC_FSINFO, "fsinfo" }, { NFSPROC_PATHCONF, "pathconf" }, { NFSPROC_COMMIT, "commit" }, { 0, NULL } }; /* * NFS V2 and V3 status values. * * Some of these come from the RFCs for NFS V2 and V3, with the message * strings taken from the FreeBSD C library "errlst.c". * * Others are errors that are not in the RFC but that I suspect some * NFS servers could return; the values are FreeBSD errno values, as * the first NFS server was the SunOS 2.0 one, and until 5.0 SunOS * was primarily BSD-derived. */ static const struct tok status2str[] = { { 1, "Operation not permitted" }, /* EPERM */ { 2, "No such file or directory" }, /* ENOENT */ { 5, "Input/output error" }, /* EIO */ { 6, "Device not configured" }, /* ENXIO */ { 11, "Resource deadlock avoided" }, /* EDEADLK */ { 12, "Cannot allocate memory" }, /* ENOMEM */ { 13, "Permission denied" }, /* EACCES */ { 17, "File exists" }, /* EEXIST */ { 18, "Cross-device link" }, /* EXDEV */ { 19, "Operation not supported by device" }, /* ENODEV */ { 20, "Not a directory" }, /* ENOTDIR */ { 21, "Is a directory" }, /* EISDIR */ { 22, "Invalid argument" }, /* EINVAL */ { 26, "Text file busy" }, /* ETXTBSY */ { 27, "File too large" }, /* EFBIG */ { 28, "No space left on device" }, /* ENOSPC */ { 30, "Read-only file system" }, /* EROFS */ { 31, "Too many links" }, /* EMLINK */ { 45, "Operation not supported" }, /* EOPNOTSUPP */ { 62, "Too many levels of symbolic links" }, /* ELOOP */ { 63, "File name too long" }, /* ENAMETOOLONG */ { 66, "Directory not empty" }, /* ENOTEMPTY */ { 69, "Disc quota exceeded" }, /* EDQUOT */ { 70, "Stale NFS file handle" }, /* ESTALE */ { 71, "Too many levels of remote in path" }, /* EREMOTE */ { 99, "Write cache flushed to disk" }, /* NFSERR_WFLUSH (not used) */ { 10001, "Illegal NFS file handle" }, /* NFS3ERR_BADHANDLE */ { 10002, "Update synchronization mismatch" }, /* NFS3ERR_NOT_SYNC */ { 10003, "READDIR/READDIRPLUS cookie is stale" }, /* NFS3ERR_BAD_COOKIE */ { 10004, "Operation not supported" }, /* NFS3ERR_NOTSUPP */ { 10005, "Buffer or request is too small" }, /* NFS3ERR_TOOSMALL */ { 10006, "Unspecified error on server" }, /* NFS3ERR_SERVERFAULT */ { 10007, "Object of that type not supported" }, /* NFS3ERR_BADTYPE */ { 10008, "Request couldn't be completed in time" }, /* NFS3ERR_JUKEBOX */ { 0, NULL } }; static const struct tok nfsv3_writemodes[] = { { 0, "unstable" }, { 1, "datasync" }, { 2, "filesync" }, { 0, NULL } }; static const struct tok type2str[] = { { NFNON, "NON" }, { NFREG, "REG" }, { NFDIR, "DIR" }, { NFBLK, "BLK" }, { NFCHR, "CHR" }, { NFLNK, "LNK" }, { NFFIFO, "FIFO" }, { 0, NULL } }; static const struct tok sunrpc_auth_str[] = { { SUNRPC_AUTH_OK, "OK" }, { SUNRPC_AUTH_BADCRED, "Bogus Credentials (seal broken)" }, { SUNRPC_AUTH_REJECTEDCRED, "Rejected Credentials (client should begin new session)" }, { SUNRPC_AUTH_BADVERF, "Bogus Verifier (seal broken)" }, { SUNRPC_AUTH_REJECTEDVERF, "Verifier expired or was replayed" }, { SUNRPC_AUTH_TOOWEAK, "Credentials are too weak" }, { SUNRPC_AUTH_INVALIDRESP, "Bogus response verifier" }, { SUNRPC_AUTH_FAILED, "Unknown failure" }, { 0, NULL } }; static const struct tok sunrpc_str[] = { { SUNRPC_PROG_UNAVAIL, "PROG_UNAVAIL" }, { SUNRPC_PROG_MISMATCH, "PROG_MISMATCH" }, { SUNRPC_PROC_UNAVAIL, "PROC_UNAVAIL" }, { SUNRPC_GARBAGE_ARGS, "GARBAGE_ARGS" }, { SUNRPC_SYSTEM_ERR, "SYSTEM_ERR" }, { 0, NULL } }; static void print_nfsaddr(netdissect_options *ndo, const u_char *bp, const char *s, const char *d) { const struct ip *ip; const struct ip6_hdr *ip6; char srcaddr[INET6_ADDRSTRLEN], dstaddr[INET6_ADDRSTRLEN]; srcaddr[0] = dstaddr[0] = '\0'; switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; strlcpy(srcaddr, ipaddr_string(ndo, &ip->ip_src), sizeof(srcaddr)); strlcpy(dstaddr, ipaddr_string(ndo, &ip->ip_dst), sizeof(dstaddr)); break; case 6: ip6 = (const struct ip6_hdr *)bp; strlcpy(srcaddr, ip6addr_string(ndo, &ip6->ip6_src), sizeof(srcaddr)); strlcpy(dstaddr, ip6addr_string(ndo, &ip6->ip6_dst), sizeof(dstaddr)); break; default: strlcpy(srcaddr, "?", sizeof(srcaddr)); strlcpy(dstaddr, "?", sizeof(dstaddr)); break; } ND_PRINT((ndo, "%s.%s > %s.%s: ", srcaddr, s, dstaddr, d)); } static const uint32_t * parse_sattr3(netdissect_options *ndo, const uint32_t *dp, struct nfsv3_sattr *sa3) { ND_TCHECK(dp[0]); sa3->sa_modeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_modeset) { ND_TCHECK(dp[0]); sa3->sa_mode = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_uidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_uidset) { ND_TCHECK(dp[0]); sa3->sa_uid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_gidset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_gidset) { ND_TCHECK(dp[0]); sa3->sa_gid = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_sizeset = EXTRACT_32BITS(dp); dp++; if (sa3->sa_sizeset) { ND_TCHECK(dp[0]); sa3->sa_size = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_atimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_atime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_atime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } ND_TCHECK(dp[0]); sa3->sa_mtimetype = EXTRACT_32BITS(dp); dp++; if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) { ND_TCHECK(dp[1]); sa3->sa_mtime.nfsv3_sec = EXTRACT_32BITS(dp); dp++; sa3->sa_mtime.nfsv3_nsec = EXTRACT_32BITS(dp); dp++; } return dp; trunc: return NULL; } static int nfserr; /* true if we error rather than trunc */ static void print_sattr3(netdissect_options *ndo, const struct nfsv3_sattr *sa3, int verbose) { if (sa3->sa_modeset) ND_PRINT((ndo, " mode %o", sa3->sa_mode)); if (sa3->sa_uidset) ND_PRINT((ndo, " uid %u", sa3->sa_uid)); if (sa3->sa_gidset) ND_PRINT((ndo, " gid %u", sa3->sa_gid)); if (verbose > 1) { if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " atime %u.%06u", sa3->sa_atime.nfsv3_sec, sa3->sa_atime.nfsv3_nsec)); if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) ND_PRINT((ndo, " mtime %u.%06u", sa3->sa_mtime.nfsv3_sec, sa3->sa_mtime.nfsv3_nsec)); } } void nfsreply_print(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; char srcid[20], dstid[20]; /*fits 32bit*/ nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_xid); if (!ndo->ndo_nflag) { strlcpy(srcid, "nfs", sizeof(srcid)); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } else { snprintf(srcid, sizeof(srcid), "%u", NFS_PORT); snprintf(dstid, sizeof(dstid), "%u", EXTRACT_32BITS(&rp->rm_xid)); } print_nfsaddr(ndo, bp2, srcid, dstid); nfsreply_print_noaddr(ndo, bp, length, bp2); return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } void nfsreply_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; uint32_t proc, vers, reply_stat; enum sunrpc_reject_stat rstat; uint32_t rlow; uint32_t rhigh; enum sunrpc_auth_stat rwhy; nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; ND_TCHECK(rp->rm_reply.rp_stat); reply_stat = EXTRACT_32BITS(&rp->rm_reply.rp_stat); switch (reply_stat) { case SUNRPC_MSG_ACCEPTED: ND_PRINT((ndo, "reply ok %u", length)); if (xid_map_find(rp, bp2, &proc, &vers) >= 0) interp_reply(ndo, rp, proc, vers, length); break; case SUNRPC_MSG_DENIED: ND_PRINT((ndo, "reply ERR %u: ", length)); ND_TCHECK(rp->rm_reply.rp_reject.rj_stat); rstat = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_stat); switch (rstat) { case SUNRPC_RPC_MISMATCH: ND_TCHECK(rp->rm_reply.rp_reject.rj_vers.high); rlow = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.low); rhigh = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.high); ND_PRINT((ndo, "RPC Version mismatch (%u-%u)", rlow, rhigh)); break; case SUNRPC_AUTH_ERROR: ND_TCHECK(rp->rm_reply.rp_reject.rj_why); rwhy = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_why); ND_PRINT((ndo, "Auth %s", tok2str(sunrpc_auth_str, "Invalid failure code %u", rwhy))); break; default: ND_PRINT((ndo, "Unknown reason for rejecting rpc message %u", (unsigned int)rstat)); break; } break; default: ND_PRINT((ndo, "reply Unknown rpc response code=%u %u", reply_stat, length)); break; } return; trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Return a pointer to the first file handle in the packet. * If the packet was truncated, return 0. */ static const uint32_t * parsereq(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; register u_int len; /* * find the start of the req data (if we captured it) */ dp = (const uint32_t *)&rp->rm_call.cb_cred; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len < length) { dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp); ND_TCHECK2(dp[0], 0); return (dp); } } trunc: return (NULL); } /* * Print out an NFS file handle and return a pointer to following word. * If packet was truncated, return 0. */ static const uint32_t * parsefh(netdissect_options *ndo, register const uint32_t *dp, int v3) { u_int len; if (v3) { ND_TCHECK(dp[0]); len = EXTRACT_32BITS(dp) / 4; dp++; } else len = NFSX_V2FH / 4; if (ND_TTEST2(*dp, len * sizeof(*dp))) { nfs_printfh(ndo, dp, len); return (dp + len); } trunc: return (NULL); } /* * Print out a file name and return pointer to 32-bit word past it. * If packet was truncated, return 0. */ static const uint32_t * parsefn(netdissect_options *ndo, register const uint32_t *dp) { register uint32_t len; register const u_char *cp; /* Bail if we don't have the string length */ ND_TCHECK(*dp); /* Fetch string length; convert to host order */ len = *dp++; NTOHL(len); ND_TCHECK2(*dp, ((len + 3) & ~3)); cp = (const u_char *)dp; /* Update 32-bit pointer (NFS filenames padded to 32-bit boundaries) */ dp += ((len + 3) & ~3) / sizeof(*dp); ND_PRINT((ndo, "\"")); if (fn_printn(ndo, cp, len, ndo->ndo_snapend)) { ND_PRINT((ndo, "\"")); goto trunc; } ND_PRINT((ndo, "\"")); return (dp); trunc: return NULL; } /* * Print out file handle and file name. * Return pointer to 32-bit word past file name. * If packet was truncated (or there was some other error), return 0. */ static const uint32_t * parsefhn(netdissect_options *ndo, register const uint32_t *dp, int v3) { dp = parsefh(ndo, dp, v3); if (dp == NULL) return (NULL); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp)); } void nfsreq_print_noaddr(netdissect_options *ndo, register const u_char *bp, u_int length, register const u_char *bp2) { register const struct sunrpc_msg *rp; register const uint32_t *dp; nfs_type type; int v3; uint32_t proc; uint32_t access_flags; struct nfsv3_sattr sa3; ND_PRINT((ndo, "%d", length)); nfserr = 0; /* assume no error */ rp = (const struct sunrpc_msg *)bp; if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */ goto trunc; v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3); proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: case NFSPROC_SETATTR: case NFSPROC_READLINK: case NFSPROC_FSSTAT: case NFSPROC_FSINFO: case NFSPROC_PATHCONF: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefh(ndo, dp, v3) != NULL) return; break; case NFSPROC_LOOKUP: case NFSPROC_CREATE: case NFSPROC_MKDIR: case NFSPROC_REMOVE: case NFSPROC_RMDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && parsefhn(ndo, dp, v3) != NULL) return; break; case NFSPROC_ACCESS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[0]); access_flags = EXTRACT_32BITS(&dp[0]); if (access_flags & ~NFSV3ACCESS_FULL) { /* NFSV3ACCESS definitions aren't up to date */ ND_PRINT((ndo, " %04x", access_flags)); } else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) { ND_PRINT((ndo, " NFS_ACCESS_FULL")); } else { char separator = ' '; if (access_flags & NFSV3ACCESS_READ) { ND_PRINT((ndo, " NFS_ACCESS_READ")); separator = '|'; } if (access_flags & NFSV3ACCESS_LOOKUP) { ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_MODIFY) { ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXTEND) { ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_DELETE) { ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator)); separator = '|'; } if (access_flags & NFSV3ACCESS_EXECUTE) ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator)); } return; } break; case NFSPROC_READ: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); } else { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes @ %u", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_WRITE: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64, EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[3])))); } } else { ND_TCHECK(dp[3]); ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)", EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_SYMLINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; if (parsefn(ndo, dp) == NULL) break; if (v3 && ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_MKNOD: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_TCHECK(*dp); type = (nfs_type)EXTRACT_32BITS(dp); dp++; if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL) break; ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type))); if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u/%u", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); dp += 2; } if (ndo->ndo_vflag) print_sattr3(ndo, &sa3, ndo->ndo_vflag); return; } break; case NFSPROC_RENAME: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefhn(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_LINK: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_PRINT((ndo, " ->")); if (parsefhn(ndo, dp, v3) != NULL) return; } break; case NFSPROC_READDIR: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { if (v3) { ND_TCHECK(dp[4]); /* * We shouldn't really try to interpret the * offset cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3])); } else { ND_TCHECK(dp[1]); /* * Print the offset as signed, since -1 is * common, but offsets > 2^31 aren't. */ ND_PRINT((ndo, " %u bytes @ %d", EXTRACT_32BITS(&dp[1]), EXTRACT_32BITS(&dp[0]))); } return; } break; case NFSPROC_READDIRPLUS: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[4]); /* * We don't try to interpret the offset * cookie here. */ ND_PRINT((ndo, " %u bytes @ %" PRId64, EXTRACT_32BITS(&dp[4]), EXTRACT_64BITS(&dp[0]))); if (ndo->ndo_vflag) { ND_TCHECK(dp[5]); ND_PRINT((ndo, " max %u verf %08x%08x", EXTRACT_32BITS(&dp[5]), dp[2], dp[3])); } return; } break; case NFSPROC_COMMIT: if ((dp = parsereq(ndo, rp, length)) != NULL && (dp = parsefh(ndo, dp, v3)) != NULL) { ND_TCHECK(dp[2]); ND_PRINT((ndo, " %u bytes @ %" PRIu64, EXTRACT_32BITS(&dp[2]), EXTRACT_64BITS(&dp[0]))); return; } break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } /* * Print out an NFS file handle. * We assume packet was not truncated before the end of the * file handle pointed to by dp. * * Note: new version (using portable file-handle parser) doesn't produce * generation number. It probably could be made to do that, with some * additional hacking on the parser code. */ static void nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ char temp[NFSX_V3FHMAX+1]; u_int stringlen; /* Make sure string is null-terminated */ stringlen = len; if (stringlen > NFSX_V3FHMAX) stringlen = NFSX_V3FHMAX; strncpy(temp, sfsname, stringlen); temp[stringlen] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); } /* * Maintain a small cache of recent client.XID.server/proc pairs, to allow * us to match up replies with requests and thus to know how to parse * the reply. */ struct xid_map_entry { uint32_t xid; /* transaction ID (net order) */ int ipver; /* IP version (4 or 6) */ struct in6_addr client; /* client IP address (net order) */ struct in6_addr server; /* server IP address (net order) */ uint32_t proc; /* call proc number (host order) */ uint32_t vers; /* program version (host order) */ }; /* * Map entries are kept in an array that we manage as a ring; * new entries are always added at the tail of the ring. Initially, * all the entries are zero and hence don't match anything. */ #define XIDMAPSIZE 64 static struct xid_map_entry xid_map[XIDMAPSIZE]; static int xid_map_next = 0; static int xid_map_hint = 0; static int xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } if (!ND_TTEST(rp->rm_call.cb_proc)) return (0); xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } /* * Returns 0 and puts NFSPROC_xxx in proc return and * version in vers return, or returns -1 on failure */ static int xid_map_find(const struct sunrpc_msg *rp, const u_char *bp, uint32_t *proc, uint32_t *vers) { int i; struct xid_map_entry *xmep; uint32_t xid; const struct ip *ip = (const struct ip *)bp; const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp; int cmp; UNALIGNED_MEMCPY(&xid, &rp->rm_xid, sizeof(xmep->xid)); /* Start searching from where we last left off */ i = xid_map_hint; do { xmep = &xid_map[i]; cmp = 1; if (xmep->ipver != IP_V(ip) || xmep->xid != xid) goto nextitem; switch (xmep->ipver) { case 4: if (UNALIGNED_MEMCMP(&ip->ip_src, &xmep->server, sizeof(ip->ip_src)) != 0 || UNALIGNED_MEMCMP(&ip->ip_dst, &xmep->client, sizeof(ip->ip_dst)) != 0) { cmp = 0; } break; case 6: if (UNALIGNED_MEMCMP(&ip6->ip6_src, &xmep->server, sizeof(ip6->ip6_src)) != 0 || UNALIGNED_MEMCMP(&ip6->ip6_dst, &xmep->client, sizeof(ip6->ip6_dst)) != 0) { cmp = 0; } break; default: cmp = 0; break; } if (cmp) { /* match */ xid_map_hint = i; *proc = xmep->proc; *vers = xmep->vers; return 0; } nextitem: if (++i >= XIDMAPSIZE) i = 0; } while (i != xid_map_hint); /* search failed */ return (-1); } /* * Routines for parsing reply packets */ /* * Return a pointer to the beginning of the actual results. * If the packet was truncated, return 0. */ static const uint32_t * parserep(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; u_int len; enum sunrpc_accept_stat astat; /* * Portability note: * Here we find the address of the ar_verf credentials. * Originally, this calculation was * dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf * On the wire, the rp_acpt field starts immediately after * the (32 bit) rp_stat field. However, rp_acpt (which is a * "struct accepted_reply") contains a "struct opaque_auth", * whose internal representation contains a pointer, so on a * 64-bit machine the compiler inserts 32 bits of padding * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use * the internal representation to parse the on-the-wire * representation. Instead, we skip past the rp_stat field, * which is an "enum" and so occupies one 32-bit word. */ dp = ((const uint32_t *)&rp->rm_reply) + 1; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len >= length) return (NULL); /* * skip past the ar_verf credentials. */ dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t); /* * now we can check the ar_stat field */ ND_TCHECK(dp[0]); astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp); if (astat != SUNRPC_SUCCESS) { ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat))); nfserr = 1; /* suppress trunc string */ return (NULL); } /* successful return */ ND_TCHECK2(*dp, sizeof(astat)); return ((const uint32_t *) (sizeof(astat) + ((const char *)dp))); trunc: return (0); } static const uint32_t * parsestatus(netdissect_options *ndo, const uint32_t *dp, int *er) { int errnum; ND_TCHECK(dp[0]); errnum = EXTRACT_32BITS(&dp[0]); if (er) *er = errnum; if (errnum != 0) { if (!ndo->ndo_qflag) ND_PRINT((ndo, " ERROR: %s", tok2str(status2str, "unk %d", errnum))); nfserr = 1; } return (dp + 1); trunc: return NULL; } static const uint32_t * parsefattr(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { const struct nfs_fattr *fap; fap = (const struct nfs_fattr *)dp; ND_TCHECK(fap->fa_gid); if (verbose) { ND_PRINT((ndo, " %s %o ids %d/%d", tok2str(type2str, "unk-ft %d ", EXTRACT_32BITS(&fap->fa_type)), EXTRACT_32BITS(&fap->fa_mode), EXTRACT_32BITS(&fap->fa_uid), EXTRACT_32BITS(&fap->fa_gid))); if (v3) { ND_TCHECK(fap->fa3_size); ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_size))); } else { ND_TCHECK(fap->fa2_size); ND_PRINT((ndo, " sz %d", EXTRACT_32BITS(&fap->fa2_size))); } } /* print lots more stuff */ if (verbose > 1) { if (v3) { ND_TCHECK(fap->fa3_ctime); ND_PRINT((ndo, " nlink %d rdev %d/%d", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa3_rdev.specdata1), EXTRACT_32BITS(&fap->fa3_rdev.specdata2))); ND_PRINT((ndo, " fsid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fsid))); ND_PRINT((ndo, " fileid %" PRIx64, EXTRACT_64BITS((const uint32_t *)&fap->fa3_fileid))); ND_PRINT((ndo, " a/m/ctime %u.%06u", EXTRACT_32BITS(&fap->fa3_atime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_atime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_nsec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_sec), EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_nsec))); } else { ND_TCHECK(fap->fa2_ctime); ND_PRINT((ndo, " nlink %d rdev 0x%x fsid 0x%x nodeid 0x%x a/m/ctime", EXTRACT_32BITS(&fap->fa_nlink), EXTRACT_32BITS(&fap->fa2_rdev), EXTRACT_32BITS(&fap->fa2_fsid), EXTRACT_32BITS(&fap->fa2_fileid))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_atime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_atime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_usec))); ND_PRINT((ndo, " %u.%06u", EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_sec), EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_usec))); } } return ((const uint32_t *)((const unsigned char *)dp + (v3 ? NFSX_V3FATTR : NFSX_V2FATTR))); trunc: return (NULL); } static int parseattrstat(netdissect_options *ndo, const uint32_t *dp, int verbose, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); return (parsefattr(ndo, dp, verbose, v3) != NULL); } static int parsediropres(netdissect_options *ndo, const uint32_t *dp) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) return (1); dp = parsefh(ndo, dp, 0); if (dp == NULL) return (0); return (parsefattr(ndo, dp, ndo->ndo_vflag, 0) != NULL); } static int parselinkres(netdissect_options *ndo, const uint32_t *dp, int v3) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return(0); if (er) return(1); if (v3 && !(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); ND_PRINT((ndo, " ")); return (parsefn(ndo, dp) != NULL); } static int parsestatfs(netdissect_options *ndo, const uint32_t *dp, int v3) { const struct nfs_statfs *sfsp; int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (!v3 && er) return (1); if (ndo->ndo_qflag) return(1); if (v3) { if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); } ND_TCHECK2(*dp, (v3 ? NFSX_V3STATFS : NFSX_V2STATFS)); sfsp = (const struct nfs_statfs *)dp; if (v3) { ND_PRINT((ndo, " tbytes %" PRIu64 " fbytes %" PRIu64 " abytes %" PRIu64, EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_fbytes), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_abytes))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " tfiles %" PRIu64 " ffiles %" PRIu64 " afiles %" PRIu64 " invar %u", EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tfiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_ffiles), EXTRACT_64BITS((const uint32_t *)&sfsp->sf_afiles), EXTRACT_32BITS(&sfsp->sf_invarsec))); } } else { ND_PRINT((ndo, " tsize %d bsize %d blocks %d bfree %d bavail %d", EXTRACT_32BITS(&sfsp->sf_tsize), EXTRACT_32BITS(&sfsp->sf_bsize), EXTRACT_32BITS(&sfsp->sf_blocks), EXTRACT_32BITS(&sfsp->sf_bfree), EXTRACT_32BITS(&sfsp->sf_bavail))); } return (1); trunc: return (0); } static int parserddires(netdissect_options *ndo, const uint32_t *dp) { int er; dp = parsestatus(ndo, dp, &er); if (dp == NULL) return (0); if (er) return (1); if (ndo->ndo_qflag) return (1); ND_TCHECK(dp[2]); ND_PRINT((ndo, " offset 0x%x size %d ", EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1]))); if (dp[2] != 0) ND_PRINT((ndo, " eof")); return (1); trunc: return (0); } static const uint32_t * parse_wcc_attr(netdissect_options *ndo, const uint32_t *dp) { /* Our caller has already checked this */ ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0]))); ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u", EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5]))); return (dp + 6); } /* * Pre operation attributes. Print only if vflag > 1. */ static const uint32_t * parse_pre_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; ND_TCHECK2(*dp, 24); if (verbose > 1) { return parse_wcc_attr(ndo, dp); } else { /* If not verbose enough, just skip over wcc_attr */ return (dp + 6); } trunc: return (NULL); } /* * Post operation attributes are printed if vflag >= 1 */ static const uint32_t * parse_post_op_attr(netdissect_options *ndo, const uint32_t *dp, int verbose) { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (verbose) { return parsefattr(ndo, dp, verbose, 1); } else return (dp + (NFSX_V3FATTR / sizeof (uint32_t))); trunc: return (NULL); } static const uint32_t * parse_wcc_data(netdissect_options *ndo, const uint32_t *dp, int verbose) { if (verbose > 1) ND_PRINT((ndo, " PRE:")); if (!(dp = parse_pre_op_attr(ndo, dp, verbose))) return (0); if (verbose) ND_PRINT((ndo, " POST:")); return parse_post_op_attr(ndo, dp, verbose); } static const uint32_t * parsecreateopres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (er) dp = parse_wcc_data(ndo, dp, verbose); else { ND_TCHECK(dp[0]); if (!EXTRACT_32BITS(&dp[0])) return (dp + 1); dp++; if (!(dp = parsefh(ndo, dp, 1))) return (0); if (verbose) { if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " dir attr:")); dp = parse_wcc_data(ndo, dp, verbose); } } } return (dp); trunc: return (NULL); } static int parsewccres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); return parse_wcc_data(ndo, dp, verbose) != NULL; } static const uint32_t * parsev3rddirres(netdissect_options *ndo, const uint32_t *dp, int verbose) { int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, verbose))) return (0); if (er) return dp; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " verf %08x%08x", dp[0], dp[1])); dp += 2; } return dp; trunc: return (NULL); } static int parsefsinfo(netdissect_options *ndo, const uint32_t *dp) { const struct nfsv3_fsinfo *sfp; int er; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); sfp = (const struct nfsv3_fsinfo *)dp; ND_TCHECK(*sfp); ND_PRINT((ndo, " rtmax %u rtpref %u wtmax %u wtpref %u dtpref %u", EXTRACT_32BITS(&sfp->fs_rtmax), EXTRACT_32BITS(&sfp->fs_rtpref), EXTRACT_32BITS(&sfp->fs_wtmax), EXTRACT_32BITS(&sfp->fs_wtpref), EXTRACT_32BITS(&sfp->fs_dtpref))); if (ndo->ndo_vflag) { ND_PRINT((ndo, " rtmult %u wtmult %u maxfsz %" PRIu64, EXTRACT_32BITS(&sfp->fs_rtmult), EXTRACT_32BITS(&sfp->fs_wtmult), EXTRACT_64BITS((const uint32_t *)&sfp->fs_maxfilesize))); ND_PRINT((ndo, " delta %u.%06u ", EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_sec), EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_nsec))); } return (1); trunc: return (0); } static int parsepathconf(netdissect_options *ndo, const uint32_t *dp) { int er; const struct nfsv3_pathconf *spp; if (!(dp = parsestatus(ndo, dp, &er))) return (0); if (ndo->ndo_vflag) ND_PRINT((ndo, " POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) return (0); if (er) return (1); spp = (const struct nfsv3_pathconf *)dp; ND_TCHECK(*spp); ND_PRINT((ndo, " linkmax %u namemax %u %s %s %s %s", EXTRACT_32BITS(&spp->pc_linkmax), EXTRACT_32BITS(&spp->pc_namemax), EXTRACT_32BITS(&spp->pc_notrunc) ? "notrunc" : "", EXTRACT_32BITS(&spp->pc_chownrestricted) ? "chownres" : "", EXTRACT_32BITS(&spp->pc_caseinsensitive) ? "igncase" : "", EXTRACT_32BITS(&spp->pc_casepreserving) ? "keepcase" : "")); return (1); trunc: return (0); } static void interp_reply(netdissect_options *ndo, const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length) { register const uint32_t *dp; register int v3; int er; v3 = (vers == NFS_VER3); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: dp = parserep(ndo, rp, length); if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0) return; break; case NFSPROC_SETATTR: if (!(dp = parserep(ndo, rp, length))) return; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0) return; } break; case NFSPROC_LOOKUP: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (er) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } else { if (!(dp = parsefh(ndo, dp, v3))) break; if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) && ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } if (dp) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_ACCESS: if (!(dp = parserep(ndo, rp, length))) break; if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) ND_PRINT((ndo, " attr:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (!er) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0]))); } return; case NFSPROC_READLINK: dp = parserep(ndo, rp, length); if (dp != NULL && parselinkres(ndo, dp, v3) != 0) return; break; case NFSPROC_READ: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (EXTRACT_32BITS(&dp[1])) ND_PRINT((ndo, " EOF")); } return; } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0) return; } break; case NFSPROC_WRITE: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (ndo->ndo_vflag > 1) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[1])))); } return; } } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0) return; } break; case NFSPROC_CREATE: case NFSPROC_MKDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_SYMLINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_MKNOD: if (!(dp = parserep(ndo, rp, length))) break; if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; break; case NFSPROC_REMOVE: case NFSPROC_RMDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_RENAME: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " from:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " to:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; } return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_LINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " file POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " dir:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; return; } } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_READDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parserddires(ndo, dp) != 0) return; } break; case NFSPROC_READDIRPLUS: if (!(dp = parserep(ndo, rp, length))) break; if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; break; case NFSPROC_FSSTAT: dp = parserep(ndo, rp, length); if (dp != NULL && parsestatfs(ndo, dp, v3) != 0) return; break; case NFSPROC_FSINFO: dp = parserep(ndo, rp, length); if (dp != NULL && parsefsinfo(ndo, dp) != 0) return; break; case NFSPROC_PATHCONF: dp = parserep(ndo, rp, length); if (dp != NULL && parsepathconf(ndo, dp) != 0) return; break; case NFSPROC_COMMIT: dp = parserep(ndo, rp, length); if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0) return; break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_2681_0
crossvul-cpp_data_good_2648_0
/* * Copyright (C) 1999 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 /* draft-ietf-idr-shutdown-07 */ #define BGP_NOTIFY_MINOR_CEASE_SHUT 2 #define BGP_NOTIFY_MINOR_CEASE_RESET 4 #define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"}, { 3, "Peer Unconfigured"}, { BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 0, "Unspecified Error"}, { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (0 == plen) { snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; plen-=32; /* adjust prefix length */ if (64 < plen) return -1; memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[1], (plen + 7) / 8); memcpy(&route_target, &pptr[1], (plen + 7) / 8); if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, { 0, NULL} }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_TCHECK2(tptr[0], 5); ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; ND_TCHECK2(tptr[0], 3); tlen = len; while (tlen >= 3) { type = *tptr; length = EXTRACT_16BITS(tptr+1); ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length - 3); switch (type) { case BGP_AIGP_TLV: ND_TCHECK2(tptr[3], 8); ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr+3))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr+3,"\n\t ", length-3); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; uint8_t shutdown_comm_length; uint8_t remainder_offset; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } /* * draft-ietf-idr-shutdown describes a method to send a communication * intended for human consumption regarding the Administrative Shutdown */ if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT || bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) && length >= BGP_NOTIFICATION_SIZE + 1) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 1); shutdown_comm_length = *(tptr); remainder_offset = 0; /* garbage, hexdump it all */ if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN || shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) { ND_PRINT((ndo, ", invalid Shutdown Communication length")); } else if (shutdown_comm_length == 0) { ND_PRINT((ndo, ", empty Shutdown Communication")); remainder_offset += 1; } /* a proper shutdown communication */ else { ND_TCHECK2(*(tptr+1), shutdown_comm_length); ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length)); (void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL); ND_PRINT((ndo, "\"")); remainder_offset += shutdown_comm_length + 1; } /* if there is trailing data, hexdump it */ if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) { ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE))); hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE)); } } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2648_0
crossvul-cpp_data_good_5314_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT U U M M % % Q Q U U A A NN N T U U MM MM % % Q Q U U AAAAA N N N T U U M M M % % Q QQ U U A A N NN T U U M M % % QQQQ UUU A A N N T UUU M M % % % % MagicCore Methods to Acquire / Destroy Quantum Pixels % % % % Software Design % % Cristy % % October 1998 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/color-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/stream.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define QuantumSignature 0xab /* Forward declarations. */ static void DestroyQuantumPixels(QuantumInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumInfo() allocates the QuantumInfo structure. % % The format of the AcquireQuantumInfo method is: % % QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ MagickExport QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info, Image *image) { MagickBooleanType status; QuantumInfo *quantum_info; quantum_info=(QuantumInfo *) AcquireMagickMemory(sizeof(*quantum_info)); if (quantum_info == (QuantumInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); quantum_info->signature=MagickCoreSignature; GetQuantumInfo(image_info,quantum_info); if (image == (const Image *) NULL) return(quantum_info); status=SetQuantumDepth(image,quantum_info,image->depth); quantum_info->endian=image->endian; if (status == MagickFalse) quantum_info=DestroyQuantumInfo(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumPixels() allocates the pixel staging areas. % % The format of the AcquireQuantumPixels method is: % % MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, % const size_t extent) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o extent: the quantum info. % */ static MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, const size_t extent) { register ssize_t i; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); quantum_info->pixels=(unsigned char **) AcquireQuantumMemory( quantum_info->number_threads,sizeof(*quantum_info->pixels)); if (quantum_info->pixels == (unsigned char **) NULL) return(MagickFalse); quantum_info->extent=extent; (void) ResetMagickMemory(quantum_info->pixels,0,quantum_info->number_threads* sizeof(*quantum_info->pixels)); for (i=0; i < (ssize_t) quantum_info->number_threads; i++) { quantum_info->pixels[i]=(unsigned char *) AcquireQuantumMemory(extent+1, sizeof(**quantum_info->pixels)); if (quantum_info->pixels[i] == (unsigned char *) NULL) { while (--i >= 0) quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); return(MagickFalse); } (void) ResetMagickMemory(quantum_info->pixels[i],0,(extent+1)* sizeof(**quantum_info->pixels)); quantum_info->pixels[i][extent]=QuantumSignature; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumInfo() deallocates memory associated with the QuantumInfo % structure. % % The format of the DestroyQuantumInfo method is: % % QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); if (quantum_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&quantum_info->semaphore); quantum_info->signature=(~MagickCoreSignature); quantum_info=(QuantumInfo *) RelinquishMagickMemory(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumPixels() destroys the quantum pixels. % % The format of the DestroyQuantumPixels() method is: % % void DestroyQuantumPixels(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ static void DestroyQuantumPixels(QuantumInfo *quantum_info) { register ssize_t i; ssize_t extent; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); assert(quantum_info->pixels != (unsigned char **) NULL); extent=(ssize_t) quantum_info->extent; for (i=0; i < (ssize_t) quantum_info->number_threads; i++) if (quantum_info->pixels[i] != (unsigned char *) NULL) { /* Did we overrun our quantum buffer? */ assert(quantum_info->pixels[i][extent] == QuantumSignature); quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); } quantum_info->pixels=(unsigned char **) RelinquishMagickMemory( quantum_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumExtent() returns the quantum pixel buffer extent. % % The format of the GetQuantumExtent method is: % % size_t GetQuantumExtent(Image *image,const QuantumInfo *quantum_info, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t extent, packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; case CbYCrAQuantum: packet_size=4; break; case CbYCrQuantum: packet_size=3; break; case CbYCrYQuantum: packet_size=4; break; default: break; } extent=MagickMax(image->columns,image->rows); if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*extent*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*extent*quantum_info->depth+7)/8)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumEndian() returns the quantum endian of the image. % % The endian of the GetQuantumEndian method is: % % EndianType GetQuantumEndian(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport EndianType GetQuantumEndian(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->endian); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumFormat() returns the quantum format of the image. % % The format of the GetQuantumFormat method is: % % QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->format); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumInfo() initializes the QuantumInfo structure to default values. % % The format of the GetQuantumInfo method is: % % GetQuantumInfo(const ImageInfo *image_info,QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image_info: the image info. % % o quantum_info: the quantum info. % */ MagickExport void GetQuantumInfo(const ImageInfo *image_info, QuantumInfo *quantum_info) { const char *option; assert(quantum_info != (QuantumInfo *) NULL); (void) ResetMagickMemory(quantum_info,0,sizeof(*quantum_info)); quantum_info->quantum=8; quantum_info->maximum=1.0; quantum_info->scale=QuantumRange; quantum_info->pack=MagickTrue; quantum_info->semaphore=AcquireSemaphoreInfo(); quantum_info->signature=MagickCoreSignature; if (image_info == (const ImageInfo *) NULL) return; option=GetImageOption(image_info,"quantum:format"); if (option != (char *) NULL) quantum_info->format=(QuantumFormatType) ParseCommandOption( MagickQuantumFormatOptions,MagickFalse,option); option=GetImageOption(image_info,"quantum:minimum"); if (option != (char *) NULL) quantum_info->minimum=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:maximum"); if (option != (char *) NULL) quantum_info->maximum=StringToDouble(option,(char **) NULL); if ((quantum_info->minimum == 0.0) && (quantum_info->maximum == 0.0)) quantum_info->scale=0.0; else if (quantum_info->minimum == quantum_info->maximum) { quantum_info->scale=(double) QuantumRange/quantum_info->minimum; quantum_info->minimum=0.0; } else quantum_info->scale=(double) QuantumRange/(quantum_info->maximum- quantum_info->minimum); option=GetImageOption(image_info,"quantum:scale"); if (option != (char *) NULL) quantum_info->scale=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:polarity"); if (option != (char *) NULL) quantum_info->min_is_white=LocaleCompare(option,"min-is-white") == 0 ? MagickTrue : MagickFalse; quantum_info->endian=image_info->endian; ResetQuantumState(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumPixels() returns the quantum pixels. % % The format of the GetQuantumPixels method is: % % unsigned char *QuantumPixels GetQuantumPixels( % const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image: the image. % */ MagickExport unsigned char *GetQuantumPixels(const QuantumInfo *quantum_info) { const int id = GetOpenMPThreadId(); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->pixels[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumType() returns the quantum type of the image. % % The format of the GetQuantumType method is: % % QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) { QuantumType quantum_type; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); (void) exception; quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=IndexAlphaQuantum; } return(quantum_type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t Q u a n t u m S t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetQuantumState() resets the quantum state. % % The format of the ResetQuantumState method is: % % void ResetQuantumState(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickPrivate void ResetQuantumState(QuantumInfo *quantum_info) { static const unsigned int mask[32] = { 0x00000000U, 0x00000001U, 0x00000003U, 0x00000007U, 0x0000000fU, 0x0000001fU, 0x0000003fU, 0x0000007fU, 0x000000ffU, 0x000001ffU, 0x000003ffU, 0x000007ffU, 0x00000fffU, 0x00001fffU, 0x00003fffU, 0x00007fffU, 0x0000ffffU, 0x0001ffffU, 0x0003ffffU, 0x0007ffffU, 0x000fffffU, 0x001fffffU, 0x003fffffU, 0x007fffffU, 0x00ffffffU, 0x01ffffffU, 0x03ffffffU, 0x07ffffffU, 0x0fffffffU, 0x1fffffffU, 0x3fffffffU, 0x7fffffffU }; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->state.inverse_scale=1.0; if (fabs(quantum_info->scale) >= MagickEpsilon) quantum_info->state.inverse_scale/=quantum_info->scale; quantum_info->state.pixel=0U; quantum_info->state.bits=0U; quantum_info->state.mask=mask; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumAlphaType() sets the quantum format. % % The format of the SetQuantumAlphaType method is: % % void SetQuantumAlphaType(QuantumInfo *quantum_info, % const QuantumAlphaType type) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o type: the alpha type (e.g. associate). % */ MagickExport void SetQuantumAlphaType(QuantumInfo *quantum_info, const QuantumAlphaType type) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->alpha_type=type; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumDepth() sets the quantum depth. % % The format of the SetQuantumDepth method is: % % MagickBooleanType SetQuantumDepth(const Image *image, % QuantumInfo *quantum_info,const size_t depth) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o depth: the quantum depth. % */ MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=MagickMax(image->columns,image->rows)*quantum; if ((MagickMax(image->columns,image->rows) != 0) && (quantum != (extent/MagickMax(image->columns,image->rows)))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumEndian() sets the quantum endian. % % The endian of the SetQuantumEndian method is: % % MagickBooleanType SetQuantumEndian(const Image *image, % QuantumInfo *quantum_info,const EndianType endian) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o endian: the quantum endian. % */ MagickExport MagickBooleanType SetQuantumEndian(const Image *image, QuantumInfo *quantum_info,const EndianType endian) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->endian=endian; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumFormat() sets the quantum format. % % The format of the SetQuantumFormat method is: % % MagickBooleanType SetQuantumFormat(const Image *image, % QuantumInfo *quantum_info,const QuantumFormatType format) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o format: the quantum format. % */ MagickExport MagickBooleanType SetQuantumFormat(const Image *image, QuantumInfo *quantum_info,const QuantumFormatType format) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->format=format; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumImageType() sets the image type based on the quantum type. % % The format of the SetQuantumImageType method is: % % void ImageType SetQuantumImageType(Image *image, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport void SetQuantumImageType(Image *image, const QuantumType quantum_type) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (quantum_type) { case IndexQuantum: case IndexAlphaQuantum: { image->type=PaletteType; break; } case GrayQuantum: case GrayAlphaQuantum: { image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; break; } case CyanQuantum: case MagentaQuantum: case YellowQuantum: case BlackQuantum: case CMYKQuantum: case CMYKAQuantum: { image->type=ColorSeparationType; break; } default: { image->type=TrueColorType; break; } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPack() sets the quantum pack flag. % % The format of the SetQuantumPack method is: % % void SetQuantumPack(QuantumInfo *quantum_info, % const MagickBooleanType pack) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o pack: the pack flag. % */ MagickExport void SetQuantumPack(QuantumInfo *quantum_info, const MagickBooleanType pack) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->pack=pack; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPad() sets the quantum pad. % % The format of the SetQuantumPad method is: % % MagickBooleanType SetQuantumPad(const Image *image, % QuantumInfo *quantum_info,const size_t pad) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o pad: the quantum pad. % */ MagickExport MagickBooleanType SetQuantumPad(const Image *image, QuantumInfo *quantum_info,const size_t pad) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->pad=pad; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m M i n I s W h i t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumMinIsWhite() sets the quantum min-is-white flag. % % The format of the SetQuantumMinIsWhite method is: % % void SetQuantumMinIsWhite(QuantumInfo *quantum_info, % const MagickBooleanType min_is_white) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o min_is_white: the min-is-white flag. % */ MagickExport void SetQuantumMinIsWhite(QuantumInfo *quantum_info, const MagickBooleanType min_is_white) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->min_is_white=min_is_white; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m Q u a n t u m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumQuantum() sets the quantum quantum. % % The format of the SetQuantumQuantum method is: % % void SetQuantumQuantum(QuantumInfo *quantum_info, % const size_t quantum) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o quantum: the quantum quantum. % */ MagickExport void SetQuantumQuantum(QuantumInfo *quantum_info, const size_t quantum) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->quantum=quantum; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m S c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumScale() sets the quantum scale. % % The format of the SetQuantumScale method is: % % void SetQuantumScale(QuantumInfo *quantum_info,const double scale) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o scale: the quantum scale. % */ MagickExport void SetQuantumScale(QuantumInfo *quantum_info,const double scale) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->scale=scale; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5314_1
crossvul-cpp_data_good_5303_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); return; } switch (type) { case -1: { SetPixelAlpha(image, pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5303_0
crossvul-cpp_data_bad_2957_0
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "libavutil/attributes.h" #include "libavutil/cpu.h" #include "libavutil/x86/cpu.h" #include "libavcodec/mpegvideodsp.h" #include "libavcodec/videodsp.h" #if HAVE_INLINE_ASM static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height) { const int w = 8; const int ix = ox >> (16 + shift); const int iy = oy >> (16 + shift); const int oxs = ox >> 4; const int oys = oy >> 4; const int dxxs = dxx >> 4; const int dxys = dxy >> 4; const int dyxs = dyx >> 4; const int dyys = dyy >> 4; const uint16_t r4[4] = { r, r, r, r }; const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; const uint64_t shift2 = 2 * shift; #define MAX_STRIDE 4096U #define MAX_H 8U uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; int x, y; const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); const int dxh = dxy * (h - 1); const int dyw = dyx * (w - 1); int need_emu = (unsigned) ix >= width - w || (unsigned) iy >= height - h; if ( // non-constant fullpel offset (3% of blocks) ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || // uses more than 16 bits of subpel mv (only at huge resolution) (dxx | dxy | dyx | dyy) & 15 || (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { // FIXME could still use mmx for some of the rows ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy * stride; if (need_emu) { ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); src = edge_buf; } __asm__ volatile ( "movd %0, %%mm6 \n\t" "pxor %%mm7, %%mm7 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" :: "r" (1 << shift)); for (x = 0; x < w; x += 4) { uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), oxs - dxys + dxxs * (x + 1), oxs - dxys + dxxs * (x + 2), oxs - dxys + dxxs * (x + 3) }; uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), oys - dyys + dyxs * (x + 1), oys - dyys + dyxs * (x + 2), oys - dyys + dyxs * (x + 3) }; for (y = 0; y < h; y++) { __asm__ volatile ( "movq %0, %%mm4 \n\t" "movq %1, %%mm5 \n\t" "paddw %2, %%mm4 \n\t" "paddw %3, %%mm5 \n\t" "movq %%mm4, %0 \n\t" "movq %%mm5, %1 \n\t" "psrlw $12, %%mm4 \n\t" "psrlw $12, %%mm5 \n\t" : "+m" (*dx4), "+m" (*dy4) : "m" (*dxy4), "m" (*dyy4)); __asm__ volatile ( "movq %%mm6, %%mm2 \n\t" "movq %%mm6, %%mm1 \n\t" "psubw %%mm4, %%mm2 \n\t" "psubw %%mm5, %%mm1 \n\t" "movq %%mm2, %%mm0 \n\t" "movq %%mm4, %%mm3 \n\t" "pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy) "pmullw %%mm5, %%mm3 \n\t" // dx * dy "pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy "pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy) "movd %4, %%mm5 \n\t" "movd %3, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy "pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy "movd %2, %%mm5 \n\t" "movd %1, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy) "pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy) "paddw %5, %%mm1 \n\t" "paddw %%mm3, %%mm2 \n\t" "paddw %%mm1, %%mm0 \n\t" "paddw %%mm2, %%mm0 \n\t" "psrlw %6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "=m" (dst[x + y * stride]) : "m" (src[0]), "m" (src[1]), "m" (src[stride]), "m" (src[stride + 1]), "m" (*r4), "m" (shift2)); src += stride; } src += 4 - h * stride; } } #endif /* HAVE_INLINE_ASM */ av_cold void ff_mpegvideodsp_init_x86(MpegVideoDSPContext *c) { #if HAVE_INLINE_ASM int cpu_flags = av_get_cpu_flags(); if (INLINE_MMX(cpu_flags)) c->gmc = gmc_mmx; #endif /* HAVE_INLINE_ASM */ }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2957_0
crossvul-cpp_data_good_5483_0
/* SCTP kernel implementation * (C) Copyright IBM Corp. 2001, 2004 * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2001-2002 Intel Corp. * Copyright (c) 2002 Nokia Corp. * * This is part of the SCTP Linux Kernel Implementation. * * These are the state functions for the state machine. * * This SCTP implementation is free software; * you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This SCTP implementation is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied * ************************ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU CC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <linux-sctp@vger.kernel.org> * * Written or modified by: * La Monte H.P. Yarroll <piggy@acm.org> * Karl Knutson <karl@athena.chicago.il.us> * Mathew Kotowsky <kotowsky@sctp.org> * Sridhar Samudrala <samudrala@us.ibm.com> * Jon Grimm <jgrimm@us.ibm.com> * Hui Huang <hui.huang@nokia.com> * Dajiang Zhang <dajiang.zhang@nokia.com> * Daisy Chang <daisyc@us.ibm.com> * Ardelle Fan <ardelle.fan@intel.com> * Ryan Layer <rmlayer@us.ibm.com> * Kevin Gao <kevin.gao@intel.com> */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/types.h> #include <linux/kernel.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/net.h> #include <linux/inet.h> #include <linux/slab.h> #include <net/sock.h> #include <net/inet_ecn.h> #include <linux/skbuff.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> #include <net/sctp/structs.h> static struct sctp_packet *sctp_abort_pkt_new(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, struct sctp_chunk *chunk, const void *payload, size_t paylen); static int sctp_eat_data(const struct sctp_association *asoc, struct sctp_chunk *chunk, sctp_cmd_seq_t *commands); static struct sctp_packet *sctp_ootb_pkt_new(struct net *net, const struct sctp_association *asoc, const struct sctp_chunk *chunk); static void sctp_send_stale_cookie_err(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const struct sctp_chunk *chunk, sctp_cmd_seq_t *commands, struct sctp_chunk *err_chunk); static sctp_disposition_t sctp_sf_do_5_2_6_stale(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands); static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands); static sctp_disposition_t sctp_sf_tabort_8_4_8(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands); static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk); static sctp_disposition_t sctp_stop_t1_and_abort(struct net *net, sctp_cmd_seq_t *commands, __be16 error, int sk_err, const struct sctp_association *asoc, struct sctp_transport *transport); static sctp_disposition_t sctp_sf_abort_violation( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, void *arg, sctp_cmd_seq_t *commands, const __u8 *payload, const size_t paylen); static sctp_disposition_t sctp_sf_violation_chunklen( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands); static sctp_disposition_t sctp_sf_violation_paramlen( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, void *ext, sctp_cmd_seq_t *commands); static sctp_disposition_t sctp_sf_violation_ctsn( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands); static sctp_disposition_t sctp_sf_violation_chunk( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands); static sctp_ierror_t sctp_sf_authenticate(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, struct sctp_chunk *chunk); static sctp_disposition_t __sctp_sf_do_9_1_abort(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands); /* Small helper function that checks if the chunk length * is of the appropriate length. The 'required_length' argument * is set to be the size of a specific chunk we are testing. * Return Values: 1 = Valid length * 0 = Invalid length * */ static inline int sctp_chunk_length_valid(struct sctp_chunk *chunk, __u16 required_length) { __u16 chunk_length = ntohs(chunk->chunk_hdr->length); /* Previously already marked? */ if (unlikely(chunk->pdiscard)) return 0; if (unlikely(chunk_length < required_length)) return 0; return 1; } /********************************************************** * These are the state functions for handling chunk events. **********************************************************/ /* * Process the final SHUTDOWN COMPLETE. * * Section: 4 (C) (diagram), 9.2 * Upon reception of the SHUTDOWN COMPLETE chunk the endpoint will verify * that it is in SHUTDOWN-ACK-SENT state, if it is not the chunk should be * discarded. If the endpoint is in the SHUTDOWN-ACK-SENT state the endpoint * should stop the T2-shutdown timer and remove all knowledge of the * association (and thus the association enters the CLOSED state). * * Verification Tag: 8.5.1(C), sctpimpguide 2.41. * C) Rules for packet carrying SHUTDOWN COMPLETE: * ... * - The receiver of a SHUTDOWN COMPLETE shall accept the packet * if the Verification Tag field of the packet matches its own tag and * the T bit is not set * OR * it is set to its peer's tag and the T bit is set in the Chunk * Flags. * Otherwise, the receiver MUST silently discard the packet * and take no further action. An endpoint MUST ignore the * SHUTDOWN COMPLETE if it is not in the SHUTDOWN-ACK-SENT state. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_4_C(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_ulpevent *ev; if (!sctp_vtag_verify_either(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 2960 6.10 Bundling * * An endpoint MUST NOT bundle INIT, INIT ACK or * SHUTDOWN COMPLETE with any other chunks. */ if (!chunk->singleton) return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the SHUTDOWN_COMPLETE chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* RFC 2960 10.2 SCTP-to-ULP * * H) SHUTDOWN COMPLETE notification * * When SCTP completes the shutdown procedures (section 9.2) this * notification is passed to the upper layer. */ ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP, 0, 0, 0, NULL, GFP_ATOMIC); if (ev) sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); /* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint * will verify that it is in SHUTDOWN-ACK-SENT state, if it is * not the chunk should be discarded. If the endpoint is in * the SHUTDOWN-ACK-SENT state the endpoint should stop the * T2-shutdown timer and remove all knowledge of the * association (and thus the association enters the CLOSED * state). */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_CLOSED)); SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); return SCTP_DISPOSITION_DELETE_TCB; } /* * Respond to a normal INIT chunk. * We are the side that is being asked for an association. * * Section: 5.1 Normal Establishment of an Association, B * B) "Z" shall respond immediately with an INIT ACK chunk. The * destination IP address of the INIT ACK MUST be set to the source * IP address of the INIT to which this INIT ACK is responding. In * the response, besides filling in other parameters, "Z" must set the * Verification Tag field to Tag_A, and also provide its own * Verification Tag (Tag_Z) in the Initiate Tag field. * * Verification Tag: Must be 0. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_5_1B_init(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_chunk *repl; struct sctp_association *new_asoc; struct sctp_chunk *err_chunk; struct sctp_packet *packet; sctp_unrecognized_param_t *unk_param; int len; /* 6.10 Bundling * An endpoint MUST NOT bundle INIT, INIT ACK or * SHUTDOWN COMPLETE with any other chunks. * * IG Section 2.11.2 * Furthermore, we require that the receiver of an INIT chunk MUST * enforce these rules by silently discarding an arriving packet * with an INIT chunk that is bundled with other chunks. */ if (!chunk->singleton) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* If the packet is an OOTB packet which is temporarily on the * control endpoint, respond with an ABORT. */ if (ep == sctp_sk(net->sctp.ctl_sock)->ep) { SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } /* 3.1 A packet containing an INIT chunk MUST have a zero Verification * Tag. */ if (chunk->sctp_hdr->vtag != 0) return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); /* Make sure that the INIT chunk has a valid length. * Normally, this would cause an ABORT with a Protocol Violation * error, but since we don't have an association, we'll * just discard the packet. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t))) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* If the INIT is coming toward a closing socket, we'll send back * and ABORT. Essentially, this catches the race of INIT being * backloged to the socket at the same time as the user isses close(). * Since the socket and all its associations are going away, we * can treat this OOTB */ if (sctp_sstate(ep->base.sk, CLOSING)) return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); /* Verify the INIT chunk before processing it. */ err_chunk = NULL; if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type, (sctp_init_chunk_t *)chunk->chunk_hdr, chunk, &err_chunk)) { /* This chunk contains fatal error. It is to be discarded. * Send an ABORT, with causes if there is any. */ if (err_chunk) { packet = sctp_abort_pkt_new(net, ep, asoc, arg, (__u8 *)(err_chunk->chunk_hdr) + sizeof(sctp_chunkhdr_t), ntohs(err_chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t)); sctp_chunk_free(err_chunk); if (packet) { sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); return SCTP_DISPOSITION_CONSUME; } else { return SCTP_DISPOSITION_NOMEM; } } else { return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } } /* Grab the INIT header. */ chunk->subh.init_hdr = (sctp_inithdr_t *)chunk->skb->data; /* Tag the variable length parameters. */ chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t)); new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC); if (!new_asoc) goto nomem; if (sctp_assoc_set_bind_addr_from_ep(new_asoc, sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0) goto nomem_init; /* The call, sctp_process_init(), can fail on memory allocation. */ if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), (sctp_init_chunk_t *)chunk->chunk_hdr, GFP_ATOMIC)) goto nomem_init; /* B) "Z" shall respond immediately with an INIT ACK chunk. */ /* If there are errors need to be reported for unknown parameters, * make sure to reserve enough room in the INIT ACK for them. */ len = 0; if (err_chunk) len = ntohs(err_chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t); repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len); if (!repl) goto nomem_init; /* If there are errors need to be reported for unknown parameters, * include them in the outgoing INIT ACK as "Unrecognized parameter" * parameter. */ if (err_chunk) { /* Get the "Unrecognized parameter" parameter(s) out of the * ERROR chunk generated by sctp_verify_init(). Since the * error cause code for "unknown parameter" and the * "Unrecognized parameter" type is the same, we can * construct the parameters in INIT ACK by copying the * ERROR causes over. */ unk_param = (sctp_unrecognized_param_t *) ((__u8 *)(err_chunk->chunk_hdr) + sizeof(sctp_chunkhdr_t)); /* Replace the cause code with the "Unrecognized parameter" * parameter type. */ sctp_addto_chunk(repl, len, unk_param); sctp_chunk_free(err_chunk); } sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); /* * Note: After sending out INIT ACK with the State Cookie parameter, * "Z" MUST NOT allocate any resources, nor keep any states for the * new association. Otherwise, "Z" will be vulnerable to resource * attacks. */ sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); return SCTP_DISPOSITION_DELETE_TCB; nomem_init: sctp_association_free(new_asoc); nomem: if (err_chunk) sctp_chunk_free(err_chunk); return SCTP_DISPOSITION_NOMEM; } /* * Respond to a normal INIT ACK chunk. * We are the side that is initiating the association. * * Section: 5.1 Normal Establishment of an Association, C * C) Upon reception of the INIT ACK from "Z", "A" shall stop the T1-init * timer and leave COOKIE-WAIT state. "A" shall then send the State * Cookie received in the INIT ACK chunk in a COOKIE ECHO chunk, start * the T1-cookie timer, and enter the COOKIE-ECHOED state. * * Note: The COOKIE ECHO chunk can be bundled with any pending outbound * DATA chunks, but it MUST be the first chunk in the packet and * until the COOKIE ACK is returned the sender MUST NOT send any * other packets to the peer. * * Verification Tag: 3.3.3 * If the value of the Initiate Tag in a received INIT ACK chunk is * found to be 0, the receiver MUST treat it as an error and close the * association by transmitting an ABORT. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_5_1C_ack(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_init_chunk_t *initchunk; struct sctp_chunk *err_chunk; struct sctp_packet *packet; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* 6.10 Bundling * An endpoint MUST NOT bundle INIT, INIT ACK or * SHUTDOWN COMPLETE with any other chunks. */ if (!chunk->singleton) return sctp_sf_violation_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the INIT-ACK chunk has a valid length */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_initack_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Grab the INIT header. */ chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data; /* Verify the INIT chunk before processing it. */ err_chunk = NULL; if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type, (sctp_init_chunk_t *)chunk->chunk_hdr, chunk, &err_chunk)) { sctp_error_t error = SCTP_ERROR_NO_RESOURCE; /* This chunk contains fatal error. It is to be discarded. * Send an ABORT, with causes. If there are no causes, * then there wasn't enough memory. Just terminate * the association. */ if (err_chunk) { packet = sctp_abort_pkt_new(net, ep, asoc, arg, (__u8 *)(err_chunk->chunk_hdr) + sizeof(sctp_chunkhdr_t), ntohs(err_chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t)); sctp_chunk_free(err_chunk); if (packet) { sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); error = SCTP_ERROR_INV_PARAM; } } /* SCTP-AUTH, Section 6.3: * It should be noted that if the receiver wants to tear * down an association in an authenticated way only, the * handling of malformed packets should not result in * tearing down the association. * * This means that if we only want to abort associations * in an authenticated way (i.e AUTH+ABORT), then we * can't destroy this association just because the packet * was malformed. */ if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED, asoc, chunk->transport); } /* Tag the variable length parameters. Note that we never * convert the parameters in an INIT chunk. */ chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t)); initchunk = (sctp_init_chunk_t *) chunk->chunk_hdr; sctp_add_cmd_sf(commands, SCTP_CMD_PEER_INIT, SCTP_PEER_INIT(initchunk)); /* Reset init error count upon receipt of INIT-ACK. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL()); /* 5.1 C) "A" shall stop the T1-init timer and leave * COOKIE-WAIT state. "A" shall then ... start the T1-cookie * timer, and enter the COOKIE-ECHOED state. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_COOKIE_ECHOED)); /* SCTP-AUTH: genereate the assocition shared keys so that * we can potentially signe the COOKIE-ECHO. */ sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_SHKEY, SCTP_NULL()); /* 5.1 C) "A" shall then send the State Cookie received in the * INIT ACK chunk in a COOKIE ECHO chunk, ... */ /* If there is any errors to report, send the ERROR chunk generated * for unknown parameters as well. */ sctp_add_cmd_sf(commands, SCTP_CMD_GEN_COOKIE_ECHO, SCTP_CHUNK(err_chunk)); return SCTP_DISPOSITION_CONSUME; } /* * Respond to a normal COOKIE ECHO chunk. * We are the side that is being asked for an association. * * Section: 5.1 Normal Establishment of an Association, D * D) Upon reception of the COOKIE ECHO chunk, Endpoint "Z" will reply * with a COOKIE ACK chunk after building a TCB and moving to * the ESTABLISHED state. A COOKIE ACK chunk may be bundled with * any pending DATA chunks (and/or SACK chunks), but the COOKIE ACK * chunk MUST be the first chunk in the packet. * * IMPLEMENTATION NOTE: An implementation may choose to send the * Communication Up notification to the SCTP user upon reception * of a valid COOKIE ECHO chunk. * * Verification Tag: 8.5.1 Exceptions in Verification Tag Rules * D) Rules for packet carrying a COOKIE ECHO * * - When sending a COOKIE ECHO, the endpoint MUST use the value of the * Initial Tag received in the INIT ACK. * * - The receiver of a COOKIE ECHO follows the procedures in Section 5. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_5_1D_ce(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_association *new_asoc; sctp_init_chunk_t *peer_init; struct sctp_chunk *repl; struct sctp_ulpevent *ev, *ai_ev = NULL; int error = 0; struct sctp_chunk *err_chk_p; struct sock *sk; /* If the packet is an OOTB packet which is temporarily on the * control endpoint, respond with an ABORT. */ if (ep == sctp_sk(net->sctp.ctl_sock)->ep) { SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } /* Make sure that the COOKIE_ECHO chunk has a valid length. * In this case, we check that we have enough for at least a * chunk header. More detailed verification is done * in sctp_unpack_cookie(). */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* If the endpoint is not listening or if the number of associations * on the TCP-style socket exceed the max backlog, respond with an * ABORT. */ sk = ep->base.sk; if (!sctp_sstate(sk, LISTENING) || (sctp_style(sk, TCP) && sk_acceptq_is_full(sk))) return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); /* "Decode" the chunk. We have no optional parameters so we * are in good shape. */ chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data; if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t))) goto nomem; /* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint * "Z" will reply with a COOKIE ACK chunk after building a TCB * and moving to the ESTABLISHED state. */ new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error, &err_chk_p); /* FIXME: * If the re-build failed, what is the proper error path * from here? * * [We should abort the association. --piggy] */ if (!new_asoc) { /* FIXME: Several errors are possible. A bad cookie should * be silently discarded, but think about logging it too. */ switch (error) { case -SCTP_IERROR_NOMEM: goto nomem; case -SCTP_IERROR_STALE_COOKIE: sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands, err_chk_p); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); case -SCTP_IERROR_BAD_SIG: default: return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } } /* Delay state machine commands until later. * * Re-build the bind address for the association is done in * the sctp_unpack_cookie() already. */ /* This is a brand-new association, so these are not yet side * effects--it is safe to run them here. */ peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; if (!sctp_process_init(new_asoc, chunk, &chunk->subh.cookie_hdr->c.peer_addr, peer_init, GFP_ATOMIC)) goto nomem_init; /* SCTP-AUTH: Now that we've populate required fields in * sctp_process_init, set up the assocaition shared keys as * necessary so that we can potentially authenticate the ACK */ error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC); if (error) goto nomem_init; /* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo * is supposed to be authenticated and we have to do delayed * authentication. We've just recreated the association using * the information in the cookie and now it's much easier to * do the authentication. */ if (chunk->auth_chunk) { struct sctp_chunk auth; sctp_ierror_t ret; /* Make sure that we and the peer are AUTH capable */ if (!net->sctp.auth_enable || !new_asoc->peer.auth_capable) { sctp_association_free(new_asoc); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* set-up our fake chunk so that we can process it */ auth.skb = chunk->auth_chunk; auth.asoc = chunk->asoc; auth.sctp_hdr = chunk->sctp_hdr; auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk, sizeof(sctp_chunkhdr_t)); skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t)); auth.transport = chunk->transport; ret = sctp_sf_authenticate(net, ep, new_asoc, type, &auth); if (ret != SCTP_IERROR_NO_ERROR) { sctp_association_free(new_asoc); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } } repl = sctp_make_cookie_ack(new_asoc, chunk); if (!repl) goto nomem_init; /* RFC 2960 5.1 Normal Establishment of an Association * * D) IMPLEMENTATION NOTE: An implementation may choose to * send the Communication Up notification to the SCTP user * upon reception of a valid COOKIE ECHO chunk. */ ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0, new_asoc->c.sinit_num_ostreams, new_asoc->c.sinit_max_instreams, NULL, GFP_ATOMIC); if (!ev) goto nomem_ev; /* Sockets API Draft Section 5.3.1.6 * When a peer sends a Adaptation Layer Indication parameter , SCTP * delivers this notification to inform the application that of the * peers requested adaptation layer. */ if (new_asoc->peer.adaptation_ind) { ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc, GFP_ATOMIC); if (!ai_ev) goto nomem_aiev; } /* Add all the state machine commands now since we've created * everything. This way we don't introduce memory corruptions * during side-effect processing and correclty count established * associations. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_ESTABLISHED)); SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB); SCTP_INC_STATS(net, SCTP_MIB_PASSIVEESTABS); sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL()); if (new_asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); /* This will send the COOKIE ACK */ sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); /* Queue the ASSOC_CHANGE event */ sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); /* Send up the Adaptation Layer Indication event */ if (ai_ev) sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ai_ev)); return SCTP_DISPOSITION_CONSUME; nomem_aiev: sctp_ulpevent_free(ev); nomem_ev: sctp_chunk_free(repl); nomem_init: sctp_association_free(new_asoc); nomem: return SCTP_DISPOSITION_NOMEM; } /* * Respond to a normal COOKIE ACK chunk. * We are the side that is asking for an association. * * RFC 2960 5.1 Normal Establishment of an Association * * E) Upon reception of the COOKIE ACK, endpoint "A" will move from the * COOKIE-ECHOED state to the ESTABLISHED state, stopping the T1-cookie * timer. It may also notify its ULP about the successful * establishment of the association with a Communication Up * notification (see Section 10). * * Verification Tag: * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_5_1E_ca(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_ulpevent *ev; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Verify that the chunk length for the COOKIE-ACK is OK. * If we don't do this, any bundled chunks may be junked. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Reset init error count upon receipt of COOKIE-ACK, * to avoid problems with the managemement of this * counter in stale cookie situations when a transition back * from the COOKIE-ECHOED state to the COOKIE-WAIT * state is performed. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL()); /* RFC 2960 5.1 Normal Establishment of an Association * * E) Upon reception of the COOKIE ACK, endpoint "A" will move * from the COOKIE-ECHOED state to the ESTABLISHED state, * stopping the T1-cookie timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_ESTABLISHED)); SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB); SCTP_INC_STATS(net, SCTP_MIB_ACTIVEESTABS); sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL()); if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); /* It may also notify its ULP about the successful * establishment of the association with a Communication Up * notification (see Section 10). */ ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_UP, 0, asoc->c.sinit_num_ostreams, asoc->c.sinit_max_instreams, NULL, GFP_ATOMIC); if (!ev) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); /* Sockets API Draft Section 5.3.1.6 * When a peer sends a Adaptation Layer Indication parameter , SCTP * delivers this notification to inform the application that of the * peers requested adaptation layer. */ if (asoc->peer.adaptation_ind) { ev = sctp_ulpevent_make_adaptation_indication(asoc, GFP_ATOMIC); if (!ev) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); } return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* Generate and sendout a heartbeat packet. */ static sctp_disposition_t sctp_sf_heartbeat(const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_transport *transport = (struct sctp_transport *) arg; struct sctp_chunk *reply; /* Send a heartbeat to our peer. */ reply = sctp_make_heartbeat(asoc, transport); if (!reply) return SCTP_DISPOSITION_NOMEM; /* Set rto_pending indicating that an RTT measurement * is started with this heartbeat chunk. */ sctp_add_cmd_sf(commands, SCTP_CMD_RTO_PENDING, SCTP_TRANSPORT(transport)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; } /* Generate a HEARTBEAT packet on the given transport. */ sctp_disposition_t sctp_sf_sendbeat_8_3(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_transport *transport = (struct sctp_transport *) arg; if (asoc->overall_error_count >= asoc->max_retrans) { sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); /* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */ sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_NO_ERROR)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_DELETE_TCB; } /* Section 3.3.5. * The Sender-specific Heartbeat Info field should normally include * information about the sender's current time when this HEARTBEAT * chunk is sent and the destination transport address to which this * HEARTBEAT is sent (see Section 8.3). */ if (transport->param_flags & SPP_HB_ENABLE) { if (SCTP_DISPOSITION_NOMEM == sctp_sf_heartbeat(ep, asoc, type, arg, commands)) return SCTP_DISPOSITION_NOMEM; /* Set transport error counter and association error counter * when sending heartbeat. */ sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT, SCTP_TRANSPORT(transport)); } sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_IDLE, SCTP_TRANSPORT(transport)); sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMER_UPDATE, SCTP_TRANSPORT(transport)); return SCTP_DISPOSITION_CONSUME; } /* * Process an heartbeat request. * * Section: 8.3 Path Heartbeat * The receiver of the HEARTBEAT should immediately respond with a * HEARTBEAT ACK that contains the Heartbeat Information field copied * from the received HEARTBEAT chunk. * * Verification Tag: 8.5 Verification Tag [Normal verification] * When receiving an SCTP packet, the endpoint MUST ensure that the * value in the Verification Tag field of the received SCTP packet * matches its own Tag. If the received Verification Tag value does not * match the receiver's own tag value, the receiver shall silently * discard the packet and shall not process it any further except for * those cases listed in Section 8.5.1 below. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_beat_8_3(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_paramhdr_t *param_hdr; struct sctp_chunk *chunk = arg; struct sctp_chunk *reply; size_t paylen = 0; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the HEARTBEAT chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_heartbeat_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* 8.3 The receiver of the HEARTBEAT should immediately * respond with a HEARTBEAT ACK that contains the Heartbeat * Information field copied from the received HEARTBEAT chunk. */ chunk->subh.hb_hdr = (sctp_heartbeathdr_t *) chunk->skb->data; param_hdr = (sctp_paramhdr_t *) chunk->subh.hb_hdr; paylen = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t); if (ntohs(param_hdr->length) > paylen) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, param_hdr, commands); if (!pskb_pull(chunk->skb, paylen)) goto nomem; reply = sctp_make_heartbeat_ack(asoc, chunk, param_hdr, paylen); if (!reply) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* * Process the returning HEARTBEAT ACK. * * Section: 8.3 Path Heartbeat * Upon the receipt of the HEARTBEAT ACK, the sender of the HEARTBEAT * should clear the error counter of the destination transport * address to which the HEARTBEAT was sent, and mark the destination * transport address as active if it is not so marked. The endpoint may * optionally report to the upper layer when an inactive destination * address is marked as active due to the reception of the latest * HEARTBEAT ACK. The receiver of the HEARTBEAT ACK must also * clear the association overall error count as well (as defined * in section 8.1). * * The receiver of the HEARTBEAT ACK should also perform an RTT * measurement for that destination transport address using the time * value carried in the HEARTBEAT ACK chunk. * * Verification Tag: 8.5 Verification Tag [Normal verification] * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_backbeat_8_3(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; union sctp_addr from_addr; struct sctp_transport *link; sctp_sender_hb_info_t *hbinfo; unsigned long max_interval; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the HEARTBEAT-ACK chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t) + sizeof(sctp_sender_hb_info_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); hbinfo = (sctp_sender_hb_info_t *) chunk->skb->data; /* Make sure that the length of the parameter is what we expect */ if (ntohs(hbinfo->param_hdr.length) != sizeof(sctp_sender_hb_info_t)) { return SCTP_DISPOSITION_DISCARD; } from_addr = hbinfo->daddr; link = sctp_assoc_lookup_paddr(asoc, &from_addr); /* This should never happen, but lets log it if so. */ if (unlikely(!link)) { if (from_addr.sa.sa_family == AF_INET6) { net_warn_ratelimited("%s association %p could not find address %pI6\n", __func__, asoc, &from_addr.v6.sin6_addr); } else { net_warn_ratelimited("%s association %p could not find address %pI4\n", __func__, asoc, &from_addr.v4.sin_addr.s_addr); } return SCTP_DISPOSITION_DISCARD; } /* Validate the 64-bit random nonce. */ if (hbinfo->hb_nonce != link->hb_nonce) return SCTP_DISPOSITION_DISCARD; max_interval = link->hbinterval + link->rto; /* Check if the timestamp looks valid. */ if (time_after(hbinfo->sent_at, jiffies) || time_after(jiffies, hbinfo->sent_at + max_interval)) { pr_debug("%s: HEARTBEAT ACK with invalid timestamp received " "for transport:%p\n", __func__, link); return SCTP_DISPOSITION_DISCARD; } /* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of * the HEARTBEAT should clear the error counter of the * destination transport address to which the HEARTBEAT was * sent and mark the destination transport address as active if * it is not so marked. */ sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_ON, SCTP_TRANSPORT(link)); return SCTP_DISPOSITION_CONSUME; } /* Helper function to send out an abort for the restart * condition. */ static int sctp_sf_send_restart_abort(struct net *net, union sctp_addr *ssa, struct sctp_chunk *init, sctp_cmd_seq_t *commands) { int len; struct sctp_packet *pkt; union sctp_addr_param *addrparm; struct sctp_errhdr *errhdr; struct sctp_endpoint *ep; char buffer[sizeof(struct sctp_errhdr)+sizeof(union sctp_addr_param)]; struct sctp_af *af = sctp_get_af_specific(ssa->v4.sin_family); /* Build the error on the stack. We are way to malloc crazy * throughout the code today. */ errhdr = (struct sctp_errhdr *)buffer; addrparm = (union sctp_addr_param *)errhdr->variable; /* Copy into a parm format. */ len = af->to_addr_param(ssa, addrparm); len += sizeof(sctp_errhdr_t); errhdr->cause = SCTP_ERROR_RESTART; errhdr->length = htons(len); /* Assign to the control socket. */ ep = sctp_sk(net->sctp.ctl_sock)->ep; /* Association is NULL since this may be a restart attack and we * want to send back the attacker's vtag. */ pkt = sctp_abort_pkt_new(net, ep, NULL, init, errhdr, len); if (!pkt) goto out; sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(pkt)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); /* Discard the rest of the inbound packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); out: /* Even if there is no memory, treat as a failure so * the packet will get dropped. */ return 0; } static bool list_has_sctp_addr(const struct list_head *list, union sctp_addr *ipaddr) { struct sctp_transport *addr; list_for_each_entry(addr, list, transports) { if (sctp_cmp_addr_exact(ipaddr, &addr->ipaddr)) return true; } return false; } /* A restart is occurring, check to make sure no new addresses * are being added as we may be under a takeover attack. */ static int sctp_sf_check_restart_addrs(const struct sctp_association *new_asoc, const struct sctp_association *asoc, struct sctp_chunk *init, sctp_cmd_seq_t *commands) { struct net *net = sock_net(new_asoc->base.sk); struct sctp_transport *new_addr; int ret = 1; /* Implementor's Guide - Section 5.2.2 * ... * Before responding the endpoint MUST check to see if the * unexpected INIT adds new addresses to the association. If new * addresses are added to the association, the endpoint MUST respond * with an ABORT.. */ /* Search through all current addresses and make sure * we aren't adding any new ones. */ list_for_each_entry(new_addr, &new_asoc->peer.transport_addr_list, transports) { if (!list_has_sctp_addr(&asoc->peer.transport_addr_list, &new_addr->ipaddr)) { sctp_sf_send_restart_abort(net, &new_addr->ipaddr, init, commands); ret = 0; break; } } /* Return success if all addresses were found. */ return ret; } /* Populate the verification/tie tags based on overlapping INIT * scenario. * * Note: Do not use in CLOSED or SHUTDOWN-ACK-SENT state. */ static void sctp_tietags_populate(struct sctp_association *new_asoc, const struct sctp_association *asoc) { switch (asoc->state) { /* 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State */ case SCTP_STATE_COOKIE_WAIT: new_asoc->c.my_vtag = asoc->c.my_vtag; new_asoc->c.my_ttag = asoc->c.my_vtag; new_asoc->c.peer_ttag = 0; break; case SCTP_STATE_COOKIE_ECHOED: new_asoc->c.my_vtag = asoc->c.my_vtag; new_asoc->c.my_ttag = asoc->c.my_vtag; new_asoc->c.peer_ttag = asoc->c.peer_vtag; break; /* 5.2.2 Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED, * COOKIE-WAIT and SHUTDOWN-ACK-SENT */ default: new_asoc->c.my_ttag = asoc->c.my_vtag; new_asoc->c.peer_ttag = asoc->c.peer_vtag; break; } /* Other parameters for the endpoint SHOULD be copied from the * existing parameters of the association (e.g. number of * outbound streams) into the INIT ACK and cookie. */ new_asoc->rwnd = asoc->rwnd; new_asoc->c.sinit_num_ostreams = asoc->c.sinit_num_ostreams; new_asoc->c.sinit_max_instreams = asoc->c.sinit_max_instreams; new_asoc->c.initial_tsn = asoc->c.initial_tsn; } /* * Compare vtag/tietag values to determine unexpected COOKIE-ECHO * handling action. * * RFC 2960 5.2.4 Handle a COOKIE ECHO when a TCB exists. * * Returns value representing action to be taken. These action values * correspond to Action/Description values in RFC 2960, Table 2. */ static char sctp_tietags_compare(struct sctp_association *new_asoc, const struct sctp_association *asoc) { /* In this case, the peer may have restarted. */ if ((asoc->c.my_vtag != new_asoc->c.my_vtag) && (asoc->c.peer_vtag != new_asoc->c.peer_vtag) && (asoc->c.my_vtag == new_asoc->c.my_ttag) && (asoc->c.peer_vtag == new_asoc->c.peer_ttag)) return 'A'; /* Collision case B. */ if ((asoc->c.my_vtag == new_asoc->c.my_vtag) && ((asoc->c.peer_vtag != new_asoc->c.peer_vtag) || (0 == asoc->c.peer_vtag))) { return 'B'; } /* Collision case D. */ if ((asoc->c.my_vtag == new_asoc->c.my_vtag) && (asoc->c.peer_vtag == new_asoc->c.peer_vtag)) return 'D'; /* Collision case C. */ if ((asoc->c.my_vtag != new_asoc->c.my_vtag) && (asoc->c.peer_vtag == new_asoc->c.peer_vtag) && (0 == new_asoc->c.my_ttag) && (0 == new_asoc->c.peer_ttag)) return 'C'; /* No match to any of the special cases; discard this packet. */ return 'E'; } /* Common helper routine for both duplicate and simulataneous INIT * chunk handling. */ static sctp_disposition_t sctp_sf_do_unexpected_init( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_disposition_t retval; struct sctp_chunk *chunk = arg; struct sctp_chunk *repl; struct sctp_association *new_asoc; struct sctp_chunk *err_chunk; struct sctp_packet *packet; sctp_unrecognized_param_t *unk_param; int len; /* 6.10 Bundling * An endpoint MUST NOT bundle INIT, INIT ACK or * SHUTDOWN COMPLETE with any other chunks. * * IG Section 2.11.2 * Furthermore, we require that the receiver of an INIT chunk MUST * enforce these rules by silently discarding an arriving packet * with an INIT chunk that is bundled with other chunks. */ if (!chunk->singleton) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* 3.1 A packet containing an INIT chunk MUST have a zero Verification * Tag. */ if (chunk->sctp_hdr->vtag != 0) return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); /* Make sure that the INIT chunk has a valid length. * In this case, we generate a protocol violation since we have * an association established. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Grab the INIT header. */ chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data; /* Tag the variable length parameters. */ chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t)); /* Verify the INIT chunk before processing it. */ err_chunk = NULL; if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type, (sctp_init_chunk_t *)chunk->chunk_hdr, chunk, &err_chunk)) { /* This chunk contains fatal error. It is to be discarded. * Send an ABORT, with causes if there is any. */ if (err_chunk) { packet = sctp_abort_pkt_new(net, ep, asoc, arg, (__u8 *)(err_chunk->chunk_hdr) + sizeof(sctp_chunkhdr_t), ntohs(err_chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t)); if (packet) { sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); retval = SCTP_DISPOSITION_CONSUME; } else { retval = SCTP_DISPOSITION_NOMEM; } goto cleanup; } else { return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } } /* * Other parameters for the endpoint SHOULD be copied from the * existing parameters of the association (e.g. number of * outbound streams) into the INIT ACK and cookie. * FIXME: We are copying parameters from the endpoint not the * association. */ new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC); if (!new_asoc) goto nomem; if (sctp_assoc_set_bind_addr_from_ep(new_asoc, sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0) goto nomem; /* In the outbound INIT ACK the endpoint MUST copy its current * Verification Tag and Peers Verification tag into a reserved * place (local tie-tag and per tie-tag) within the state cookie. */ if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), (sctp_init_chunk_t *)chunk->chunk_hdr, GFP_ATOMIC)) goto nomem; /* Make sure no new addresses are being added during the * restart. Do not do this check for COOKIE-WAIT state, * since there are no peer addresses to check against. * Upon return an ABORT will have been sent if needed. */ if (!sctp_state(asoc, COOKIE_WAIT)) { if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) { retval = SCTP_DISPOSITION_CONSUME; goto nomem_retval; } } sctp_tietags_populate(new_asoc, asoc); /* B) "Z" shall respond immediately with an INIT ACK chunk. */ /* If there are errors need to be reported for unknown parameters, * make sure to reserve enough room in the INIT ACK for them. */ len = 0; if (err_chunk) { len = ntohs(err_chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t); } repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len); if (!repl) goto nomem; /* If there are errors need to be reported for unknown parameters, * include them in the outgoing INIT ACK as "Unrecognized parameter" * parameter. */ if (err_chunk) { /* Get the "Unrecognized parameter" parameter(s) out of the * ERROR chunk generated by sctp_verify_init(). Since the * error cause code for "unknown parameter" and the * "Unrecognized parameter" type is the same, we can * construct the parameters in INIT ACK by copying the * ERROR causes over. */ unk_param = (sctp_unrecognized_param_t *) ((__u8 *)(err_chunk->chunk_hdr) + sizeof(sctp_chunkhdr_t)); /* Replace the cause code with the "Unrecognized parameter" * parameter type. */ sctp_addto_chunk(repl, len, unk_param); } sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); /* * Note: After sending out INIT ACK with the State Cookie parameter, * "Z" MUST NOT allocate any resources for this new association. * Otherwise, "Z" will be vulnerable to resource attacks. */ sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); retval = SCTP_DISPOSITION_CONSUME; return retval; nomem: retval = SCTP_DISPOSITION_NOMEM; nomem_retval: if (new_asoc) sctp_association_free(new_asoc); cleanup: if (err_chunk) sctp_chunk_free(err_chunk); return retval; } /* * Handle simultaneous INIT. * This means we started an INIT and then we got an INIT request from * our peer. * * Section: 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State (Item B) * This usually indicates an initialization collision, i.e., each * endpoint is attempting, at about the same time, to establish an * association with the other endpoint. * * Upon receipt of an INIT in the COOKIE-WAIT or COOKIE-ECHOED state, an * endpoint MUST respond with an INIT ACK using the same parameters it * sent in its original INIT chunk (including its Verification Tag, * unchanged). These original parameters are combined with those from the * newly received INIT chunk. The endpoint shall also generate a State * Cookie with the INIT ACK. The endpoint uses the parameters sent in its * INIT to calculate the State Cookie. * * After that, the endpoint MUST NOT change its state, the T1-init * timer shall be left running and the corresponding TCB MUST NOT be * destroyed. The normal procedures for handling State Cookies when * a TCB exists will resolve the duplicate INITs to a single association. * * For an endpoint that is in the COOKIE-ECHOED state it MUST populate * its Tie-Tags with the Tag information of itself and its peer (see * section 5.2.2 for a description of the Tie-Tags). * * Verification Tag: Not explicit, but an INIT can not have a valid * verification tag, so we skip the check. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_5_2_1_siminit(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* Call helper to do the real work for both simulataneous and * duplicate INIT chunk handling. */ return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands); } /* * Handle duplicated INIT messages. These are usually delayed * restransmissions. * * Section: 5.2.2 Unexpected INIT in States Other than CLOSED, * COOKIE-ECHOED and COOKIE-WAIT * * Unless otherwise stated, upon reception of an unexpected INIT for * this association, the endpoint shall generate an INIT ACK with a * State Cookie. In the outbound INIT ACK the endpoint MUST copy its * current Verification Tag and peer's Verification Tag into a reserved * place within the state cookie. We shall refer to these locations as * the Peer's-Tie-Tag and the Local-Tie-Tag. The outbound SCTP packet * containing this INIT ACK MUST carry a Verification Tag value equal to * the Initiation Tag found in the unexpected INIT. And the INIT ACK * MUST contain a new Initiation Tag (randomly generated see Section * 5.3.1). Other parameters for the endpoint SHOULD be copied from the * existing parameters of the association (e.g. number of outbound * streams) into the INIT ACK and cookie. * * After sending out the INIT ACK, the endpoint shall take no further * actions, i.e., the existing association, including its current state, * and the corresponding TCB MUST NOT be changed. * * Note: Only when a TCB exists and the association is not in a COOKIE- * WAIT state are the Tie-Tags populated. For a normal association INIT * (i.e. the endpoint is in a COOKIE-WAIT state), the Tie-Tags MUST be * set to 0 (indicating that no previous TCB existed). The INIT ACK and * State Cookie are populated as specified in section 5.2.1. * * Verification Tag: Not specified, but an INIT has no way of knowing * what the verification tag could be, so we ignore it. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_5_2_2_dupinit(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* Call helper to do the real work for both simulataneous and * duplicate INIT chunk handling. */ return sctp_sf_do_unexpected_init(net, ep, asoc, type, arg, commands); } /* * Unexpected INIT-ACK handler. * * Section 5.2.3 * If an INIT ACK received by an endpoint in any state other than the * COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk. * An unexpected INIT ACK usually indicates the processing of an old or * duplicated INIT chunk. */ sctp_disposition_t sctp_sf_do_5_2_3_initack(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* Per the above section, we'll discard the chunk if we have an * endpoint. If this is an OOTB INIT-ACK, treat it as such. */ if (ep == sctp_sk(net->sctp.ctl_sock)->ep) return sctp_sf_ootb(net, ep, asoc, type, arg, commands); else return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); } /* Unexpected COOKIE-ECHO handler for peer restart (Table 2, action 'A') * * Section 5.2.4 * A) In this case, the peer may have restarted. */ static sctp_disposition_t sctp_sf_do_dupcook_a(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, struct sctp_chunk *chunk, sctp_cmd_seq_t *commands, struct sctp_association *new_asoc) { sctp_init_chunk_t *peer_init; struct sctp_ulpevent *ev; struct sctp_chunk *repl; struct sctp_chunk *err; sctp_disposition_t disposition; /* new_asoc is a brand-new association, so these are not yet * side effects--it is safe to run them here. */ peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init, GFP_ATOMIC)) goto nomem; /* Make sure no new addresses are being added during the * restart. Though this is a pretty complicated attack * since you'd have to get inside the cookie. */ if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) { return SCTP_DISPOSITION_CONSUME; } /* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes * the peer has restarted (Action A), it MUST NOT setup a new * association but instead resend the SHUTDOWN ACK and send an ERROR * chunk with a "Cookie Received while Shutting Down" error cause to * its peer. */ if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) { disposition = sctp_sf_do_9_2_reshutack(net, ep, asoc, SCTP_ST_CHUNK(chunk->chunk_hdr->type), chunk, commands); if (SCTP_DISPOSITION_NOMEM == disposition) goto nomem; err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_COOKIE_IN_SHUTDOWN, NULL, 0, 0); if (err) sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(err)); return SCTP_DISPOSITION_CONSUME; } /* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked * data. Consider the optional choice of resending of this data. */ sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_SACK)); sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL()); /* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue * and ASCONF-ACK cache. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL()); repl = sctp_make_cookie_ack(new_asoc, chunk); if (!repl) goto nomem; /* Report association restart to upper layer. */ ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0, new_asoc->c.sinit_num_ostreams, new_asoc->c.sinit_max_instreams, NULL, GFP_ATOMIC); if (!ev) goto nomem_ev; /* Update the content of current association. */ sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); if (sctp_state(asoc, SHUTDOWN_PENDING) && (sctp_sstate(asoc->base.sk, CLOSING) || sock_flag(asoc->base.sk, SOCK_DEAD))) { /* if were currently in SHUTDOWN_PENDING, but the socket * has been closed by user, don't transition to ESTABLISHED. * Instead trigger SHUTDOWN bundled with COOKIE_ACK. */ sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); return sctp_sf_do_9_2_start_shutdown(net, ep, asoc, SCTP_ST_CHUNK(0), NULL, commands); } else { sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_ESTABLISHED)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); } return SCTP_DISPOSITION_CONSUME; nomem_ev: sctp_chunk_free(repl); nomem: return SCTP_DISPOSITION_NOMEM; } /* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'B') * * Section 5.2.4 * B) In this case, both sides may be attempting to start an association * at about the same time but the peer endpoint started its INIT * after responding to the local endpoint's INIT */ /* This case represents an initialization collision. */ static sctp_disposition_t sctp_sf_do_dupcook_b(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, struct sctp_chunk *chunk, sctp_cmd_seq_t *commands, struct sctp_association *new_asoc) { sctp_init_chunk_t *peer_init; struct sctp_chunk *repl; /* new_asoc is a brand-new association, so these are not yet * side effects--it is safe to run them here. */ peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init, GFP_ATOMIC)) goto nomem; /* Update the content of current association. */ sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_ESTABLISHED)); SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB); sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL()); repl = sctp_make_cookie_ack(new_asoc, chunk); if (!repl) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); /* RFC 2960 5.1 Normal Establishment of an Association * * D) IMPLEMENTATION NOTE: An implementation may choose to * send the Communication Up notification to the SCTP user * upon reception of a valid COOKIE ECHO chunk. * * Sadly, this needs to be implemented as a side-effect, because * we are not guaranteed to have set the association id of the real * association and so these notifications need to be delayed until * the association id is allocated. */ sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_CHANGE, SCTP_U8(SCTP_COMM_UP)); /* Sockets API Draft Section 5.3.1.6 * When a peer sends a Adaptation Layer Indication parameter , SCTP * delivers this notification to inform the application that of the * peers requested adaptation layer. * * This also needs to be done as a side effect for the same reason as * above. */ if (asoc->peer.adaptation_ind) sctp_add_cmd_sf(commands, SCTP_CMD_ADAPTATION_IND, SCTP_NULL()); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'C') * * Section 5.2.4 * C) In this case, the local endpoint's cookie has arrived late. * Before it arrived, the local endpoint sent an INIT and received an * INIT-ACK and finally sent a COOKIE ECHO with the peer's same tag * but a new tag of its own. */ /* This case represents an initialization collision. */ static sctp_disposition_t sctp_sf_do_dupcook_c(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, struct sctp_chunk *chunk, sctp_cmd_seq_t *commands, struct sctp_association *new_asoc) { /* The cookie should be silently discarded. * The endpoint SHOULD NOT change states and should leave * any timers running. */ return SCTP_DISPOSITION_DISCARD; } /* Unexpected COOKIE-ECHO handler lost chunk (Table 2, action 'D') * * Section 5.2.4 * * D) When both local and remote tags match the endpoint should always * enter the ESTABLISHED state, if it has not already done so. */ /* This case represents an initialization collision. */ static sctp_disposition_t sctp_sf_do_dupcook_d(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, struct sctp_chunk *chunk, sctp_cmd_seq_t *commands, struct sctp_association *new_asoc) { struct sctp_ulpevent *ev = NULL, *ai_ev = NULL; struct sctp_chunk *repl; /* Clarification from Implementor's Guide: * D) When both local and remote tags match the endpoint should * enter the ESTABLISHED state, if it is in the COOKIE-ECHOED state. * It should stop any cookie timer that may be running and send * a COOKIE ACK. */ /* Don't accidentally move back into established state. */ if (asoc->state < SCTP_STATE_ESTABLISHED) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_ESTABLISHED)); SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB); sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL()); /* RFC 2960 5.1 Normal Establishment of an Association * * D) IMPLEMENTATION NOTE: An implementation may choose * to send the Communication Up notification to the * SCTP user upon reception of a valid COOKIE * ECHO chunk. */ ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_UP, 0, asoc->c.sinit_num_ostreams, asoc->c.sinit_max_instreams, NULL, GFP_ATOMIC); if (!ev) goto nomem; /* Sockets API Draft Section 5.3.1.6 * When a peer sends a Adaptation Layer Indication parameter, * SCTP delivers this notification to inform the application * that of the peers requested adaptation layer. */ if (asoc->peer.adaptation_ind) { ai_ev = sctp_ulpevent_make_adaptation_indication(asoc, GFP_ATOMIC); if (!ai_ev) goto nomem; } } repl = sctp_make_cookie_ack(new_asoc, chunk); if (!repl) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); if (ev) sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); if (ai_ev) sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ai_ev)); return SCTP_DISPOSITION_CONSUME; nomem: if (ai_ev) sctp_ulpevent_free(ai_ev); if (ev) sctp_ulpevent_free(ev); return SCTP_DISPOSITION_NOMEM; } /* * Handle a duplicate COOKIE-ECHO. This usually means a cookie-carrying * chunk was retransmitted and then delayed in the network. * * Section: 5.2.4 Handle a COOKIE ECHO when a TCB exists * * Verification Tag: None. Do cookie validation. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_disposition_t retval; struct sctp_chunk *chunk = arg; struct sctp_association *new_asoc; int error = 0; char action; struct sctp_chunk *err_chk_p; /* Make sure that the chunk has a valid length from the protocol * perspective. In this case check to make sure we have at least * enough for the chunk header. Cookie length verification is * done later. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* "Decode" the chunk. We have no optional parameters so we * are in good shape. */ chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data; if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t))) goto nomem; /* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie * of a duplicate COOKIE ECHO match the Verification Tags of the * current association, consider the State Cookie valid even if * the lifespan is exceeded. */ new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error, &err_chk_p); /* FIXME: * If the re-build failed, what is the proper error path * from here? * * [We should abort the association. --piggy] */ if (!new_asoc) { /* FIXME: Several errors are possible. A bad cookie should * be silently discarded, but think about logging it too. */ switch (error) { case -SCTP_IERROR_NOMEM: goto nomem; case -SCTP_IERROR_STALE_COOKIE: sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands, err_chk_p); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); case -SCTP_IERROR_BAD_SIG: default: return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } } /* Compare the tie_tag in cookie with the verification tag of * current association. */ action = sctp_tietags_compare(new_asoc, asoc); switch (action) { case 'A': /* Association restart. */ retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands, new_asoc); break; case 'B': /* Collision case B. */ retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands, new_asoc); break; case 'C': /* Collision case C. */ retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands, new_asoc); break; case 'D': /* Collision case D. */ retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands, new_asoc); break; default: /* Discard packet for all others. */ retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); break; } /* Delete the tempory new association. */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); /* Restore association pointer to provide SCTP command interpeter * with a valid context in case it needs to manipulate * the queues */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC((struct sctp_association *)asoc)); return retval; nomem: return SCTP_DISPOSITION_NOMEM; } /* * Process an ABORT. (SHUTDOWN-PENDING state) * * See sctp_sf_do_9_1_abort(). */ sctp_disposition_t sctp_sf_shutdown_pending_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; if (!sctp_vtag_verify_either(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the ABORT chunk has a valid length. * Since this is an ABORT chunk, we have to discard it * because of the following text: * RFC 2960, Section 3.3.7 * If an endpoint receives an ABORT with a format error or for an * association that doesn't exist, it MUST silently discard it. * Because the length is "invalid", we can't really discard just * as we do not know its true length. So, to be safe, discard the * packet. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t))) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* ADD-IP: Special case for ABORT chunks * F4) One special consideration is that ABORT Chunks arriving * destined to the IP address being deleted MUST be * ignored (see Section 5.3.1 for further details). */ if (SCTP_ADDR_DEL == sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest)) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands); } /* * Process an ABORT. (SHUTDOWN-SENT state) * * See sctp_sf_do_9_1_abort(). */ sctp_disposition_t sctp_sf_shutdown_sent_abort(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; if (!sctp_vtag_verify_either(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the ABORT chunk has a valid length. * Since this is an ABORT chunk, we have to discard it * because of the following text: * RFC 2960, Section 3.3.7 * If an endpoint receives an ABORT with a format error or for an * association that doesn't exist, it MUST silently discard it. * Because the length is "invalid", we can't really discard just * as we do not know its true length. So, to be safe, discard the * packet. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t))) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* ADD-IP: Special case for ABORT chunks * F4) One special consideration is that ABORT Chunks arriving * destined to the IP address being deleted MUST be * ignored (see Section 5.3.1 for further details). */ if (SCTP_ADDR_DEL == sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest)) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); /* Stop the T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); /* Stop the T5-shutdown guard timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD)); return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands); } /* * Process an ABORT. (SHUTDOWN-ACK-SENT state) * * See sctp_sf_do_9_1_abort(). */ sctp_disposition_t sctp_sf_shutdown_ack_sent_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* The same T2 timer, so we should be able to use * common function with the SHUTDOWN-SENT state. */ return sctp_sf_shutdown_sent_abort(net, ep, asoc, type, arg, commands); } /* * Handle an Error received in COOKIE_ECHOED state. * * Only handle the error type of stale COOKIE Error, the other errors will * be ignored. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_cookie_echoed_err(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_errhdr_t *err; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the ERROR chunk has a valid length. * The parameter walking depends on this as well. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Process the error here */ /* FUTURE FIXME: When PR-SCTP related and other optional * parms are emitted, this will have to change to handle multiple * errors. */ sctp_walk_errors(err, chunk->chunk_hdr) { if (SCTP_ERROR_STALE_COOKIE == err->cause) return sctp_sf_do_5_2_6_stale(net, ep, asoc, type, arg, commands); } /* It is possible to have malformed error causes, and that * will cause us to end the walk early. However, since * we are discarding the packet, there should be no adverse * affects. */ return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* * Handle a Stale COOKIE Error * * Section: 5.2.6 Handle Stale COOKIE Error * If the association is in the COOKIE-ECHOED state, the endpoint may elect * one of the following three alternatives. * ... * 3) Send a new INIT chunk to the endpoint, adding a Cookie * Preservative parameter requesting an extension to the lifetime of * the State Cookie. When calculating the time extension, an * implementation SHOULD use the RTT information measured based on the * previous COOKIE ECHO / ERROR exchange, and should add no more * than 1 second beyond the measured RTT, due to long State Cookie * lifetimes making the endpoint more subject to a replay attack. * * Verification Tag: Not explicit, but safe to ignore. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ static sctp_disposition_t sctp_sf_do_5_2_6_stale(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; u32 stale; sctp_cookie_preserve_param_t bht; sctp_errhdr_t *err; struct sctp_chunk *reply; struct sctp_bind_addr *bp; int attempts = asoc->init_err_counter + 1; if (attempts > asoc->max_init_attempts) { sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED, SCTP_PERR(SCTP_ERROR_STALE_COOKIE)); return SCTP_DISPOSITION_DELETE_TCB; } err = (sctp_errhdr_t *)(chunk->skb->data); /* When calculating the time extension, an implementation * SHOULD use the RTT information measured based on the * previous COOKIE ECHO / ERROR exchange, and should add no * more than 1 second beyond the measured RTT, due to long * State Cookie lifetimes making the endpoint more subject to * a replay attack. * Measure of Staleness's unit is usec. (1/1000000 sec) * Suggested Cookie Life-span Increment's unit is msec. * (1/1000 sec) * In general, if you use the suggested cookie life, the value * found in the field of measure of staleness should be doubled * to give ample time to retransmit the new cookie and thus * yield a higher probability of success on the reattempt. */ stale = ntohl(*(__be32 *)((u8 *)err + sizeof(sctp_errhdr_t))); stale = (stale * 2) / 1000; bht.param_hdr.type = SCTP_PARAM_COOKIE_PRESERVATIVE; bht.param_hdr.length = htons(sizeof(bht)); bht.lifespan_increment = htonl(stale); /* Build that new INIT chunk. */ bp = (struct sctp_bind_addr *) &asoc->base.bind_addr; reply = sctp_make_init(asoc, bp, GFP_ATOMIC, sizeof(bht)); if (!reply) goto nomem; sctp_addto_chunk(reply, sizeof(bht), &bht); /* Clear peer's init_tag cached in assoc as we are sending a new INIT */ sctp_add_cmd_sf(commands, SCTP_CMD_CLEAR_INIT_TAG, SCTP_NULL()); /* Stop pending T3-rtx and heartbeat timers */ sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL()); /* Delete non-primary peer ip addresses since we are transitioning * back to the COOKIE-WAIT state */ sctp_add_cmd_sf(commands, SCTP_CMD_DEL_NON_PRIMARY, SCTP_NULL()); /* If we've sent any data bundled with COOKIE-ECHO we will need to * resend */ sctp_add_cmd_sf(commands, SCTP_CMD_T1_RETRAN, SCTP_TRANSPORT(asoc->peer.primary_path)); /* Cast away the const modifier, as we want to just * rerun it through as a sideffect. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_INC, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_COOKIE_WAIT)); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* * Process an ABORT. * * Section: 9.1 * After checking the Verification Tag, the receiving endpoint shall * remove the association from its record, and shall report the * termination to its upper layer. * * Verification Tag: 8.5.1 Exceptions in Verification Tag Rules * B) Rules for packet carrying ABORT: * * - The endpoint shall always fill in the Verification Tag field of the * outbound packet with the destination endpoint's tag value if it * is known. * * - If the ABORT is sent in response to an OOTB packet, the endpoint * MUST follow the procedure described in Section 8.4. * * - The receiver MUST accept the packet if the Verification Tag * matches either its own tag, OR the tag of its peer. Otherwise, the * receiver MUST silently discard the packet and take no further * action. * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_9_1_abort(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; if (!sctp_vtag_verify_either(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the ABORT chunk has a valid length. * Since this is an ABORT chunk, we have to discard it * because of the following text: * RFC 2960, Section 3.3.7 * If an endpoint receives an ABORT with a format error or for an * association that doesn't exist, it MUST silently discard it. * Because the length is "invalid", we can't really discard just * as we do not know its true length. So, to be safe, discard the * packet. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t))) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* ADD-IP: Special case for ABORT chunks * F4) One special consideration is that ABORT Chunks arriving * destined to the IP address being deleted MUST be * ignored (see Section 5.3.1 for further details). */ if (SCTP_ADDR_DEL == sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest)) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); return __sctp_sf_do_9_1_abort(net, ep, asoc, type, arg, commands); } static sctp_disposition_t __sctp_sf_do_9_1_abort(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; unsigned int len; __be16 error = SCTP_ERROR_NO_ERROR; /* See if we have an error cause code in the chunk. */ len = ntohs(chunk->chunk_hdr->length); if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr)) { sctp_errhdr_t *err; sctp_walk_errors(err, chunk->chunk_hdr); if ((void *)err != (void *)chunk->chunk_end) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); error = ((sctp_errhdr_t *)chunk->skb->data)->cause; } sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNRESET)); /* ASSOC_FAILED will DELETE_TCB. */ sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(error)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } /* * Process an ABORT. (COOKIE-WAIT state) * * See sctp_sf_do_9_1_abort() above. */ sctp_disposition_t sctp_sf_cookie_wait_abort(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; unsigned int len; __be16 error = SCTP_ERROR_NO_ERROR; if (!sctp_vtag_verify_either(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the ABORT chunk has a valid length. * Since this is an ABORT chunk, we have to discard it * because of the following text: * RFC 2960, Section 3.3.7 * If an endpoint receives an ABORT with a format error or for an * association that doesn't exist, it MUST silently discard it. * Because the length is "invalid", we can't really discard just * as we do not know its true length. So, to be safe, discard the * packet. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t))) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* See if we have an error cause code in the chunk. */ len = ntohs(chunk->chunk_hdr->length); if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr)) error = ((sctp_errhdr_t *)chunk->skb->data)->cause; return sctp_stop_t1_and_abort(net, commands, error, ECONNREFUSED, asoc, chunk->transport); } /* * Process an incoming ICMP as an ABORT. (COOKIE-WAIT state) */ sctp_disposition_t sctp_sf_cookie_wait_icmp_abort(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { return sctp_stop_t1_and_abort(net, commands, SCTP_ERROR_NO_ERROR, ENOPROTOOPT, asoc, (struct sctp_transport *)arg); } /* * Process an ABORT. (COOKIE-ECHOED state) */ sctp_disposition_t sctp_sf_cookie_echoed_abort(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* There is a single T1 timer, so we should be able to use * common function with the COOKIE-WAIT state. */ return sctp_sf_cookie_wait_abort(net, ep, asoc, type, arg, commands); } /* * Stop T1 timer and abort association with "INIT failed". * * This is common code called by several sctp_sf_*_abort() functions above. */ static sctp_disposition_t sctp_stop_t1_and_abort(struct net *net, sctp_cmd_seq_t *commands, __be16 error, int sk_err, const struct sctp_association *asoc, struct sctp_transport *transport) { pr_debug("%s: ABORT received (INIT)\n", __func__); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_CLOSED)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(sk_err)); /* CMD_INIT_FAILED will DELETE_TCB. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED, SCTP_PERR(error)); return SCTP_DISPOSITION_ABORT; } /* * sctp_sf_do_9_2_shut * * Section: 9.2 * Upon the reception of the SHUTDOWN, the peer endpoint shall * - enter the SHUTDOWN-RECEIVED state, * * - stop accepting new data from its SCTP user * * - verify, by checking the Cumulative TSN Ack field of the chunk, * that all its outstanding DATA chunks have been received by the * SHUTDOWN sender. * * Once an endpoint as reached the SHUTDOWN-RECEIVED state it MUST NOT * send a SHUTDOWN in response to a ULP request. And should discard * subsequent SHUTDOWN chunks. * * If there are still outstanding DATA chunks left, the SHUTDOWN * receiver shall continue to follow normal data transmission * procedures defined in Section 6 until all outstanding DATA chunks * are acknowledged; however, the SHUTDOWN receiver MUST NOT accept * new data from its SCTP user. * * Verification Tag: 8.5 Verification Tag [Normal verification] * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_9_2_shutdown(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_shutdownhdr_t *sdh; sctp_disposition_t disposition; struct sctp_ulpevent *ev; __u32 ctsn; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the SHUTDOWN chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Convert the elaborate header. */ sdh = (sctp_shutdownhdr_t *)chunk->skb->data; skb_pull(chunk->skb, sizeof(sctp_shutdownhdr_t)); chunk->subh.shutdown_hdr = sdh; ctsn = ntohl(sdh->cum_tsn_ack); if (TSN_lt(ctsn, asoc->ctsn_ack_point)) { pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn, asoc->ctsn_ack_point); return SCTP_DISPOSITION_DISCARD; } /* If Cumulative TSN Ack beyond the max tsn currently * send, terminating the association and respond to the * sender with an ABORT. */ if (!TSN_lt(ctsn, asoc->next_tsn)) return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands); /* API 5.3.1.5 SCTP_SHUTDOWN_EVENT * When a peer sends a SHUTDOWN, SCTP delivers this notification to * inform the application that it should cease sending data. */ ev = sctp_ulpevent_make_shutdown_event(asoc, 0, GFP_ATOMIC); if (!ev) { disposition = SCTP_DISPOSITION_NOMEM; goto out; } sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); /* Upon the reception of the SHUTDOWN, the peer endpoint shall * - enter the SHUTDOWN-RECEIVED state, * - stop accepting new data from its SCTP user * * [This is implicit in the new state.] */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_SHUTDOWN_RECEIVED)); disposition = SCTP_DISPOSITION_CONSUME; if (sctp_outq_is_empty(&asoc->outqueue)) { disposition = sctp_sf_do_9_2_shutdown_ack(net, ep, asoc, type, arg, commands); } if (SCTP_DISPOSITION_NOMEM == disposition) goto out; /* - verify, by checking the Cumulative TSN Ack field of the * chunk, that all its outstanding DATA chunks have been * received by the SHUTDOWN sender. */ sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN, SCTP_BE32(chunk->subh.shutdown_hdr->cum_tsn_ack)); out: return disposition; } /* * sctp_sf_do_9_2_shut_ctsn * * Once an endpoint has reached the SHUTDOWN-RECEIVED state, * it MUST NOT send a SHUTDOWN in response to a ULP request. * The Cumulative TSN Ack of the received SHUTDOWN chunk * MUST be processed. */ sctp_disposition_t sctp_sf_do_9_2_shut_ctsn(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_shutdownhdr_t *sdh; __u32 ctsn; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the SHUTDOWN chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); sdh = (sctp_shutdownhdr_t *)chunk->skb->data; ctsn = ntohl(sdh->cum_tsn_ack); if (TSN_lt(ctsn, asoc->ctsn_ack_point)) { pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn, asoc->ctsn_ack_point); return SCTP_DISPOSITION_DISCARD; } /* If Cumulative TSN Ack beyond the max tsn currently * send, terminating the association and respond to the * sender with an ABORT. */ if (!TSN_lt(ctsn, asoc->next_tsn)) return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands); /* verify, by checking the Cumulative TSN Ack field of the * chunk, that all its outstanding DATA chunks have been * received by the SHUTDOWN sender. */ sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN, SCTP_BE32(sdh->cum_tsn_ack)); return SCTP_DISPOSITION_CONSUME; } /* RFC 2960 9.2 * If an endpoint is in SHUTDOWN-ACK-SENT state and receives an INIT chunk * (e.g., if the SHUTDOWN COMPLETE was lost) with source and destination * transport addresses (either in the IP addresses or in the INIT chunk) * that belong to this association, it should discard the INIT chunk and * retransmit the SHUTDOWN ACK chunk. */ sctp_disposition_t sctp_sf_do_9_2_reshutack(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = (struct sctp_chunk *) arg; struct sctp_chunk *reply; /* Make sure that the chunk has a valid length */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Since we are not going to really process this INIT, there * is no point in verifying chunk boundries. Just generate * the SHUTDOWN ACK. */ reply = sctp_make_shutdown_ack(asoc, chunk); if (NULL == reply) goto nomem; /* Set the transport for the SHUTDOWN ACK chunk and the timeout for * the T2-SHUTDOWN timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply)); /* and restart the T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* * sctp_sf_do_ecn_cwr * * Section: Appendix A: Explicit Congestion Notification * * CWR: * * RFC 2481 details a specific bit for a sender to send in the header of * its next outbound TCP segment to indicate to its peer that it has * reduced its congestion window. This is termed the CWR bit. For * SCTP the same indication is made by including the CWR chunk. * This chunk contains one data element, i.e. the TSN number that * was sent in the ECNE chunk. This element represents the lowest * TSN number in the datagram that was originally marked with the * CE bit. * * Verification Tag: 8.5 Verification Tag [Normal verification] * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_ecn_cwr(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_cwrhdr_t *cwr; struct sctp_chunk *chunk = arg; u32 lowest_tsn; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); cwr = (sctp_cwrhdr_t *) chunk->skb->data; skb_pull(chunk->skb, sizeof(sctp_cwrhdr_t)); lowest_tsn = ntohl(cwr->lowest_tsn); /* Does this CWR ack the last sent congestion notification? */ if (TSN_lte(asoc->last_ecne_tsn, lowest_tsn)) { /* Stop sending ECNE. */ sctp_add_cmd_sf(commands, SCTP_CMD_ECN_CWR, SCTP_U32(lowest_tsn)); } return SCTP_DISPOSITION_CONSUME; } /* * sctp_sf_do_ecne * * Section: Appendix A: Explicit Congestion Notification * * ECN-Echo * * RFC 2481 details a specific bit for a receiver to send back in its * TCP acknowledgements to notify the sender of the Congestion * Experienced (CE) bit having arrived from the network. For SCTP this * same indication is made by including the ECNE chunk. This chunk * contains one data element, i.e. the lowest TSN associated with the IP * datagram marked with the CE bit..... * * Verification Tag: 8.5 Verification Tag [Normal verification] * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_ecne(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_ecnehdr_t *ecne; struct sctp_chunk *chunk = arg; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); ecne = (sctp_ecnehdr_t *) chunk->skb->data; skb_pull(chunk->skb, sizeof(sctp_ecnehdr_t)); /* If this is a newer ECNE than the last CWR packet we sent out */ sctp_add_cmd_sf(commands, SCTP_CMD_ECN_ECNE, SCTP_U32(ntohl(ecne->lowest_tsn))); return SCTP_DISPOSITION_CONSUME; } /* * Section: 6.2 Acknowledgement on Reception of DATA Chunks * * The SCTP endpoint MUST always acknowledge the reception of each valid * DATA chunk. * * The guidelines on delayed acknowledgement algorithm specified in * Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an * acknowledgement SHOULD be generated for at least every second packet * (not every second DATA chunk) received, and SHOULD be generated within * 200 ms of the arrival of any unacknowledged DATA chunk. In some * situations it may be beneficial for an SCTP transmitter to be more * conservative than the algorithms detailed in this document allow. * However, an SCTP transmitter MUST NOT be more aggressive than the * following algorithms allow. * * A SCTP receiver MUST NOT generate more than one SACK for every * incoming packet, other than to update the offered window as the * receiving application consumes new data. * * Verification Tag: 8.5 Verification Tag [Normal verification] * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_eat_data_6_2(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_arg_t force = SCTP_NOFORCE(); int error; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); error = sctp_eat_data(asoc, chunk, commands); switch (error) { case SCTP_IERROR_NO_ERROR: break; case SCTP_IERROR_HIGH_TSN: case SCTP_IERROR_BAD_STREAM: SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS); goto discard_noforce; case SCTP_IERROR_DUP_TSN: case SCTP_IERROR_IGNORE_TSN: SCTP_INC_STATS(net, SCTP_MIB_IN_DATA_CHUNK_DISCARDS); goto discard_force; case SCTP_IERROR_NO_DATA: return SCTP_DISPOSITION_ABORT; case SCTP_IERROR_PROTO_VIOLATION: return sctp_sf_abort_violation(net, ep, asoc, chunk, commands, (u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t)); default: BUG(); } if (chunk->chunk_hdr->flags & SCTP_DATA_SACK_IMM) force = SCTP_FORCE(); if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); } /* If this is the last chunk in a packet, we need to count it * toward sack generation. Note that we need to SACK every * OTHER packet containing data chunks, EVEN IF WE DISCARD * THEM. We elect to NOT generate SACK's if the chunk fails * the verification tag test. * * RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks * * The SCTP endpoint MUST always acknowledge the reception of * each valid DATA chunk. * * The guidelines on delayed acknowledgement algorithm * specified in Section 4.2 of [RFC2581] SHOULD be followed. * Specifically, an acknowledgement SHOULD be generated for at * least every second packet (not every second DATA chunk) * received, and SHOULD be generated within 200 ms of the * arrival of any unacknowledged DATA chunk. In some * situations it may be beneficial for an SCTP transmitter to * be more conservative than the algorithms detailed in this * document allow. However, an SCTP transmitter MUST NOT be * more aggressive than the following algorithms allow. */ if (chunk->end_of_packet) sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force); return SCTP_DISPOSITION_CONSUME; discard_force: /* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks * * When a packet arrives with duplicate DATA chunk(s) and with * no new DATA chunk(s), the endpoint MUST immediately send a * SACK with no delay. If a packet arrives with duplicate * DATA chunk(s) bundled with new DATA chunks, the endpoint * MAY immediately send a SACK. Normally receipt of duplicate * DATA chunks will occur when the original SACK chunk was lost * and the peer's RTO has expired. The duplicate TSN number(s) * SHOULD be reported in the SACK as duplicate. */ /* In our case, we split the MAY SACK advice up whether or not * the last chunk is a duplicate.' */ if (chunk->end_of_packet) sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE()); return SCTP_DISPOSITION_DISCARD; discard_noforce: if (chunk->end_of_packet) sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force); return SCTP_DISPOSITION_DISCARD; } /* * sctp_sf_eat_data_fast_4_4 * * Section: 4 (4) * (4) In SHUTDOWN-SENT state the endpoint MUST acknowledge any received * DATA chunks without delay. * * Verification Tag: 8.5 Verification Tag [Normal verification] * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_eat_data_fast_4_4(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; int error; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); error = sctp_eat_data(asoc, chunk, commands); switch (error) { case SCTP_IERROR_NO_ERROR: case SCTP_IERROR_HIGH_TSN: case SCTP_IERROR_DUP_TSN: case SCTP_IERROR_IGNORE_TSN: case SCTP_IERROR_BAD_STREAM: break; case SCTP_IERROR_NO_DATA: return SCTP_DISPOSITION_ABORT; case SCTP_IERROR_PROTO_VIOLATION: return sctp_sf_abort_violation(net, ep, asoc, chunk, commands, (u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t)); default: BUG(); } /* Go a head and force a SACK, since we are shutting down. */ /* Implementor's Guide. * * While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately * respond to each received packet containing one or more DATA chunk(s) * with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer */ if (chunk->end_of_packet) { /* We must delay the chunk creation since the cumulative * TSN has not been updated yet. */ sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE()); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); } return SCTP_DISPOSITION_CONSUME; } /* * Section: 6.2 Processing a Received SACK * D) Any time a SACK arrives, the endpoint performs the following: * * i) If Cumulative TSN Ack is less than the Cumulative TSN Ack Point, * then drop the SACK. Since Cumulative TSN Ack is monotonically * increasing, a SACK whose Cumulative TSN Ack is less than the * Cumulative TSN Ack Point indicates an out-of-order SACK. * * ii) Set rwnd equal to the newly received a_rwnd minus the number * of bytes still outstanding after processing the Cumulative TSN Ack * and the Gap Ack Blocks. * * iii) If the SACK is missing a TSN that was previously * acknowledged via a Gap Ack Block (e.g., the data receiver * reneged on the data), then mark the corresponding DATA chunk * as available for retransmit: Mark it as missing for fast * retransmit as described in Section 7.2.4 and if no retransmit * timer is running for the destination address to which the DATA * chunk was originally transmitted, then T3-rtx is started for * that destination address. * * Verification Tag: 8.5 Verification Tag [Normal verification] * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_eat_sack_6_2(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_sackhdr_t *sackh; __u32 ctsn; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the SACK chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_sack_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Pull the SACK chunk from the data buffer */ sackh = sctp_sm_pull_sack(chunk); /* Was this a bogus SACK? */ if (!sackh) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); chunk->subh.sack_hdr = sackh; ctsn = ntohl(sackh->cum_tsn_ack); /* i) If Cumulative TSN Ack is less than the Cumulative TSN * Ack Point, then drop the SACK. Since Cumulative TSN * Ack is monotonically increasing, a SACK whose * Cumulative TSN Ack is less than the Cumulative TSN Ack * Point indicates an out-of-order SACK. */ if (TSN_lt(ctsn, asoc->ctsn_ack_point)) { pr_debug("%s: ctsn:%x, ctsn_ack_point:%x\n", __func__, ctsn, asoc->ctsn_ack_point); return SCTP_DISPOSITION_DISCARD; } /* If Cumulative TSN Ack beyond the max tsn currently * send, terminating the association and respond to the * sender with an ABORT. */ if (!TSN_lt(ctsn, asoc->next_tsn)) return sctp_sf_violation_ctsn(net, ep, asoc, type, arg, commands); /* Return this SACK for further processing. */ sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_SACK, SCTP_CHUNK(chunk)); /* Note: We do the rest of the work on the PROCESS_SACK * sideeffect. */ return SCTP_DISPOSITION_CONSUME; } /* * Generate an ABORT in response to a packet. * * Section: 8.4 Handle "Out of the blue" Packets, sctpimpguide 2.41 * * 8) The receiver should respond to the sender of the OOTB packet with * an ABORT. When sending the ABORT, the receiver of the OOTB packet * MUST fill in the Verification Tag field of the outbound packet * with the value found in the Verification Tag field of the OOTB * packet and set the T-bit in the Chunk Flags to indicate that the * Verification Tag is reflected. After sending this ABORT, the * receiver of the OOTB packet shall discard the OOTB packet and take * no further action. * * Verification Tag: * * The return value is the disposition of the chunk. */ static sctp_disposition_t sctp_sf_tabort_8_4_8(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_packet *packet = NULL; struct sctp_chunk *chunk = arg; struct sctp_chunk *abort; packet = sctp_ootb_pkt_new(net, asoc, chunk); if (packet) { /* Make an ABORT. The T bit will be set if the asoc * is NULL. */ abort = sctp_make_abort(asoc, chunk, 0); if (!abort) { sctp_ootb_pkt_free(packet); return SCTP_DISPOSITION_NOMEM; } /* Reflect vtag if T-Bit is set */ if (sctp_test_T_bit(abort)) packet->vtag = ntohl(chunk->sctp_hdr->vtag); /* Set the skb to the belonging sock for accounting. */ abort->skb->sk = ep->base.sk; sctp_packet_append_chunk(packet, abort); sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); return SCTP_DISPOSITION_CONSUME; } return SCTP_DISPOSITION_NOMEM; } /* * Received an ERROR chunk from peer. Generate SCTP_REMOTE_ERROR * event as ULP notification for each cause included in the chunk. * * API 5.3.1.3 - SCTP_REMOTE_ERROR * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_operr_notify(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_errhdr_t *err; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the ERROR chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); sctp_walk_errors(err, chunk->chunk_hdr); if ((void *)err != (void *)chunk->chunk_end) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)err, commands); sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_OPERR, SCTP_CHUNK(chunk)); return SCTP_DISPOSITION_CONSUME; } /* * Process an inbound SHUTDOWN ACK. * * From Section 9.2: * Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall * stop the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its * peer, and remove all record of the association. * * The return value is the disposition. */ sctp_disposition_t sctp_sf_do_9_2_final(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_chunk *reply; struct sctp_ulpevent *ev; if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the SHUTDOWN_ACK chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* 10.2 H) SHUTDOWN COMPLETE notification * * When SCTP completes the shutdown procedures (section 9.2) this * notification is passed to the upper layer. */ ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP, 0, 0, 0, NULL, GFP_ATOMIC); if (!ev) goto nomem; /* ...send a SHUTDOWN COMPLETE chunk to its peer, */ reply = sctp_make_shutdown_complete(asoc, chunk); if (!reply) goto nomem_chunk; /* Do all the commands now (after allocation), so that we * have consistent state if memory allocation failes */ sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); /* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall * stop the T2-shutdown timer, */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_CLOSED)); SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); /* ...and remove all record of the association. */ sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); return SCTP_DISPOSITION_DELETE_TCB; nomem_chunk: sctp_ulpevent_free(ev); nomem: return SCTP_DISPOSITION_NOMEM; } /* * RFC 2960, 8.4 - Handle "Out of the blue" Packets, sctpimpguide 2.41. * * 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should * respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE. * When sending the SHUTDOWN COMPLETE, the receiver of the OOTB * packet must fill in the Verification Tag field of the outbound * packet with the Verification Tag received in the SHUTDOWN ACK and * set the T-bit in the Chunk Flags to indicate that the Verification * Tag is reflected. * * 8) The receiver should respond to the sender of the OOTB packet with * an ABORT. When sending the ABORT, the receiver of the OOTB packet * MUST fill in the Verification Tag field of the outbound packet * with the value found in the Verification Tag field of the OOTB * packet and set the T-bit in the Chunk Flags to indicate that the * Verification Tag is reflected. After sending this ABORT, the * receiver of the OOTB packet shall discard the OOTB packet and take * no further action. */ sctp_disposition_t sctp_sf_ootb(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sk_buff *skb = chunk->skb; sctp_chunkhdr_t *ch; sctp_errhdr_t *err; __u8 *ch_end; int ootb_shut_ack = 0; int ootb_cookie_ack = 0; SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); ch = (sctp_chunkhdr_t *) chunk->chunk_hdr; do { /* Report violation if the chunk is less then minimal */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Report violation if chunk len overflows */ ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Now that we know we at least have a chunk header, * do things that are type appropriate. */ if (SCTP_CID_SHUTDOWN_ACK == ch->type) ootb_shut_ack = 1; /* RFC 2960, Section 3.3.7 * Moreover, under any circumstances, an endpoint that * receives an ABORT MUST NOT respond to that ABORT by * sending an ABORT of its own. */ if (SCTP_CID_ABORT == ch->type) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR * or a COOKIE ACK the SCTP Packet should be silently * discarded. */ if (SCTP_CID_COOKIE_ACK == ch->type) ootb_cookie_ack = 1; if (SCTP_CID_ERROR == ch->type) { sctp_walk_errors(err, ch) { if (SCTP_ERROR_STALE_COOKIE == err->cause) { ootb_cookie_ack = 1; break; } } } ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); if (ootb_shut_ack) return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands); else if (ootb_cookie_ack) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); else return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } /* * Handle an "Out of the blue" SHUTDOWN ACK. * * Section: 8.4 5, sctpimpguide 2.41. * * 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should * respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE. * When sending the SHUTDOWN COMPLETE, the receiver of the OOTB * packet must fill in the Verification Tag field of the outbound * packet with the Verification Tag received in the SHUTDOWN ACK and * set the T-bit in the Chunk Flags to indicate that the Verification * Tag is reflected. * * Inputs * (endpoint, asoc, type, arg, commands) * * Outputs * (sctp_disposition_t) * * The return value is the disposition of the chunk. */ static sctp_disposition_t sctp_sf_shut_8_4_5(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_packet *packet = NULL; struct sctp_chunk *chunk = arg; struct sctp_chunk *shut; packet = sctp_ootb_pkt_new(net, asoc, chunk); if (packet) { /* Make an SHUTDOWN_COMPLETE. * The T bit will be set if the asoc is NULL. */ shut = sctp_make_shutdown_complete(asoc, chunk); if (!shut) { sctp_ootb_pkt_free(packet); return SCTP_DISPOSITION_NOMEM; } /* Reflect vtag if T-Bit is set */ if (sctp_test_T_bit(shut)) packet->vtag = ntohl(chunk->sctp_hdr->vtag); /* Set the skb to the belonging sock for accounting. */ shut->skb->sk = ep->base.sk; sctp_packet_append_chunk(packet, shut); sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); /* If the chunk length is invalid, we don't want to process * the reset of the packet. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* We need to discard the rest of the packet to prevent * potential bomming attacks from additional bundled chunks. * This is documented in SCTP Threats ID. */ return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } return SCTP_DISPOSITION_NOMEM; } /* * Handle SHUTDOWN ACK in COOKIE_ECHOED or COOKIE_WAIT state. * * Verification Tag: 8.5.1 E) Rules for packet carrying a SHUTDOWN ACK * If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state the * procedures in section 8.4 SHOULD be followed, in other words it * should be treated as an Out Of The Blue packet. * [This means that we do NOT check the Verification Tag on these * chunks. --piggy ] * */ sctp_disposition_t sctp_sf_do_8_5_1_E_sa(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; /* Make sure that the SHUTDOWN_ACK chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Although we do have an association in this case, it corresponds * to a restarted association. So the packet is treated as an OOTB * packet and the state function that handles OOTB SHUTDOWN_ACK is * called with a NULL association. */ SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); return sctp_sf_shut_8_4_5(net, ep, NULL, type, arg, commands); } /* ADDIP Section 4.2 Upon reception of an ASCONF Chunk. */ sctp_disposition_t sctp_sf_do_asconf(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_chunk *asconf_ack = NULL; struct sctp_paramhdr *err_param = NULL; sctp_addiphdr_t *hdr; __u32 serial; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* ADD-IP: Section 4.1.1 * This chunk MUST be sent in an authenticated way by using * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk * is received unauthenticated it MUST be silently discarded as * described in [I-D.ietf-tsvwg-sctp-auth]. */ if (!net->sctp.addip_noauth && !chunk->auth) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the ASCONF ADDIP chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_addip_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); hdr = (sctp_addiphdr_t *)chunk->skb->data; serial = ntohl(hdr->serial); /* Verify the ASCONF chunk before processing it. */ if (!sctp_verify_asconf(asoc, chunk, true, &err_param)) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)err_param, commands); /* ADDIP 5.2 E1) Compare the value of the serial number to the value * the endpoint stored in a new association variable * 'Peer-Serial-Number'. */ if (serial == asoc->peer.addip_serial + 1) { /* If this is the first instance of ASCONF in the packet, * we can clean our old ASCONF-ACKs. */ if (!chunk->has_asconf) sctp_assoc_clean_asconf_ack_cache(asoc); /* ADDIP 5.2 E4) When the Sequence Number matches the next one * expected, process the ASCONF as described below and after * processing the ASCONF Chunk, append an ASCONF-ACK Chunk to * the response packet and cache a copy of it (in the event it * later needs to be retransmitted). * * Essentially, do V1-V5. */ asconf_ack = sctp_process_asconf((struct sctp_association *) asoc, chunk); if (!asconf_ack) return SCTP_DISPOSITION_NOMEM; } else if (serial < asoc->peer.addip_serial + 1) { /* ADDIP 5.2 E2) * If the value found in the Sequence Number is less than the * ('Peer- Sequence-Number' + 1), simply skip to the next * ASCONF, and include in the outbound response packet * any previously cached ASCONF-ACK response that was * sent and saved that matches the Sequence Number of the * ASCONF. Note: It is possible that no cached ASCONF-ACK * Chunk exists. This will occur when an older ASCONF * arrives out of order. In such a case, the receiver * should skip the ASCONF Chunk and not include ASCONF-ACK * Chunk for that chunk. */ asconf_ack = sctp_assoc_lookup_asconf_ack(asoc, hdr->serial); if (!asconf_ack) return SCTP_DISPOSITION_DISCARD; /* Reset the transport so that we select the correct one * this time around. This is to make sure that we don't * accidentally use a stale transport that's been removed. */ asconf_ack->transport = NULL; } else { /* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since * it must be either a stale packet or from an attacker. */ return SCTP_DISPOSITION_DISCARD; } /* ADDIP 5.2 E6) The destination address of the SCTP packet * containing the ASCONF-ACK Chunks MUST be the source address of * the SCTP packet that held the ASCONF Chunks. * * To do this properly, we'll set the destination address of the chunk * and at the transmit time, will try look up the transport to use. * Since ASCONFs may be bundled, the correct transport may not be * created until we process the entire packet, thus this workaround. */ asconf_ack->dest = chunk->source; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack)); if (asoc->new_transport) { sctp_sf_heartbeat(ep, asoc, type, asoc->new_transport, commands); ((struct sctp_association *)asoc)->new_transport = NULL; } return SCTP_DISPOSITION_CONSUME; } /* * ADDIP Section 4.3 General rules for address manipulation * When building TLV parameters for the ASCONF Chunk that will add or * delete IP addresses the D0 to D13 rules should be applied: */ sctp_disposition_t sctp_sf_do_asconf_ack(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *asconf_ack = arg; struct sctp_chunk *last_asconf = asoc->addip_last_asconf; struct sctp_chunk *abort; struct sctp_paramhdr *err_param = NULL; sctp_addiphdr_t *addip_hdr; __u32 sent_serial, rcvd_serial; if (!sctp_vtag_verify(asconf_ack, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* ADD-IP, Section 4.1.2: * This chunk MUST be sent in an authenticated way by using * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk * is received unauthenticated it MUST be silently discarded as * described in [I-D.ietf-tsvwg-sctp-auth]. */ if (!net->sctp.addip_noauth && !asconf_ack->auth) return sctp_sf_discard_chunk(net, ep, asoc, type, arg, commands); /* Make sure that the ADDIP chunk has a valid length. */ if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data; rcvd_serial = ntohl(addip_hdr->serial); /* Verify the ASCONF-ACK chunk before processing it. */ if (!sctp_verify_asconf(asoc, asconf_ack, false, &err_param)) return sctp_sf_violation_paramlen(net, ep, asoc, type, arg, (void *)err_param, commands); if (last_asconf) { addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr; sent_serial = ntohl(addip_hdr->serial); } else { sent_serial = asoc->addip_serial - 1; } /* D0) If an endpoint receives an ASCONF-ACK that is greater than or * equal to the next serial number to be used but no ASCONF chunk is * outstanding the endpoint MUST ABORT the association. Note that a * sequence number is greater than if it is no more than 2^^31-1 * larger than the current sequence number (using serial arithmetic). */ if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) && !(asoc->addip_last_asconf)) { abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); if (!sctp_process_asconf_ack((struct sctp_association *)asoc, asconf_ack)) { /* Successfully processed ASCONF_ACK. We can * release the next asconf if we have one. */ sctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF, SCTP_NULL()); return SCTP_DISPOSITION_CONSUME; } abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } return SCTP_DISPOSITION_DISCARD; } /* * PR-SCTP Section 3.6 Receiver Side Implementation of PR-SCTP * * When a FORWARD TSN chunk arrives, the data receiver MUST first update * its cumulative TSN point to the value carried in the FORWARD TSN * chunk, and then MUST further advance its cumulative TSN point locally * if possible. * After the above processing, the data receiver MUST stop reporting any * missing TSNs earlier than or equal to the new cumulative TSN point. * * Verification Tag: 8.5 Verification Tag [Normal verification] * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_eat_fwd_tsn(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_fwdtsn_hdr *fwdtsn_hdr; struct sctp_fwdtsn_skip *skip; __u16 len; __u32 tsn; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* Make sure that the FORWARD_TSN chunk has valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data; chunk->subh.fwdtsn_hdr = fwdtsn_hdr; len = ntohs(chunk->chunk_hdr->length); len -= sizeof(struct sctp_chunkhdr); skb_pull(chunk->skb, len); tsn = ntohl(fwdtsn_hdr->new_cum_tsn); pr_debug("%s: TSN 0x%x\n", __func__, tsn); /* The TSN is too high--silently discard the chunk and count on it * getting retransmitted later. */ if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0) goto discard_noforce; /* Silently discard the chunk if stream-id is not valid */ sctp_walk_fwdtsn(skip, chunk) { if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams) goto discard_noforce; } sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn)); if (len > sizeof(struct sctp_fwdtsn_hdr)) sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN, SCTP_CHUNK(chunk)); /* Count this as receiving DATA. */ if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); } /* FIXME: For now send a SACK, but DATA processing may * send another. */ sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE()); return SCTP_DISPOSITION_CONSUME; discard_noforce: return SCTP_DISPOSITION_DISCARD; } sctp_disposition_t sctp_sf_eat_fwd_tsn_fast( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_fwdtsn_hdr *fwdtsn_hdr; struct sctp_fwdtsn_skip *skip; __u16 len; __u32 tsn; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* Make sure that the FORWARD_TSN chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data; chunk->subh.fwdtsn_hdr = fwdtsn_hdr; len = ntohs(chunk->chunk_hdr->length); len -= sizeof(struct sctp_chunkhdr); skb_pull(chunk->skb, len); tsn = ntohl(fwdtsn_hdr->new_cum_tsn); pr_debug("%s: TSN 0x%x\n", __func__, tsn); /* The TSN is too high--silently discard the chunk and count on it * getting retransmitted later. */ if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0) goto gen_shutdown; /* Silently discard the chunk if stream-id is not valid */ sctp_walk_fwdtsn(skip, chunk) { if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams) goto gen_shutdown; } sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn)); if (len > sizeof(struct sctp_fwdtsn_hdr)) sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN, SCTP_CHUNK(chunk)); /* Go a head and force a SACK, since we are shutting down. */ gen_shutdown: /* Implementor's Guide. * * While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately * respond to each received packet containing one or more DATA chunk(s) * with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer */ sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE()); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); return SCTP_DISPOSITION_CONSUME; } /* * SCTP-AUTH Section 6.3 Receiving authenticated chukns * * The receiver MUST use the HMAC algorithm indicated in the HMAC * Identifier field. If this algorithm was not specified by the * receiver in the HMAC-ALGO parameter in the INIT or INIT-ACK chunk * during association setup, the AUTH chunk and all chunks after it MUST * be discarded and an ERROR chunk SHOULD be sent with the error cause * defined in Section 4.1. * * If an endpoint with no shared key receives a Shared Key Identifier * other than 0, it MUST silently discard all authenticated chunks. If * the endpoint has at least one endpoint pair shared key for the peer, * it MUST use the key specified by the Shared Key Identifier if a * key has been configured for that Shared Key Identifier. If no * endpoint pair shared key has been configured for that Shared Key * Identifier, all authenticated chunks MUST be silently discarded. * * Verification Tag: 8.5 Verification Tag [Normal verification] * * The return value is the disposition of the chunk. */ static sctp_ierror_t sctp_sf_authenticate(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, struct sctp_chunk *chunk) { struct sctp_authhdr *auth_hdr; struct sctp_hmac *hmac; unsigned int sig_len; __u16 key_id; __u8 *save_digest; __u8 *digest; /* Pull in the auth header, so we can do some more verification */ auth_hdr = (struct sctp_authhdr *)chunk->skb->data; chunk->subh.auth_hdr = auth_hdr; skb_pull(chunk->skb, sizeof(struct sctp_authhdr)); /* Make sure that we support the HMAC algorithm from the auth * chunk. */ if (!sctp_auth_asoc_verify_hmac_id(asoc, auth_hdr->hmac_id)) return SCTP_IERROR_AUTH_BAD_HMAC; /* Make sure that the provided shared key identifier has been * configured */ key_id = ntohs(auth_hdr->shkey_id); if (key_id != asoc->active_key_id && !sctp_auth_get_shkey(asoc, key_id)) return SCTP_IERROR_AUTH_BAD_KEYID; /* Make sure that the length of the signature matches what * we expect. */ sig_len = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_auth_chunk_t); hmac = sctp_auth_get_hmac(ntohs(auth_hdr->hmac_id)); if (sig_len != hmac->hmac_len) return SCTP_IERROR_PROTO_VIOLATION; /* Now that we've done validation checks, we can compute and * verify the hmac. The steps involved are: * 1. Save the digest from the chunk. * 2. Zero out the digest in the chunk. * 3. Compute the new digest * 4. Compare saved and new digests. */ digest = auth_hdr->hmac; skb_pull(chunk->skb, sig_len); save_digest = kmemdup(digest, sig_len, GFP_ATOMIC); if (!save_digest) goto nomem; memset(digest, 0, sig_len); sctp_auth_calculate_hmac(asoc, chunk->skb, (struct sctp_auth_chunk *)chunk->chunk_hdr, GFP_ATOMIC); /* Discard the packet if the digests do not match */ if (memcmp(save_digest, digest, sig_len)) { kfree(save_digest); return SCTP_IERROR_BAD_SIG; } kfree(save_digest); chunk->auth = 1; return SCTP_IERROR_NO_ERROR; nomem: return SCTP_IERROR_NOMEM; } sctp_disposition_t sctp_sf_eat_auth(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_authhdr *auth_hdr; struct sctp_chunk *chunk = arg; struct sctp_chunk *err_chunk; sctp_ierror_t error; /* Make sure that the peer has AUTH capable */ if (!asoc->peer.auth_capable) return sctp_sf_unk_chunk(net, ep, asoc, type, arg, commands); if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* Make sure that the AUTH chunk has valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_auth_chunk))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); auth_hdr = (struct sctp_authhdr *)chunk->skb->data; error = sctp_sf_authenticate(net, ep, asoc, type, chunk); switch (error) { case SCTP_IERROR_AUTH_BAD_HMAC: /* Generate the ERROR chunk and discard the rest * of the packet */ err_chunk = sctp_make_op_error(asoc, chunk, SCTP_ERROR_UNSUP_HMAC, &auth_hdr->hmac_id, sizeof(__u16), 0); if (err_chunk) { sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(err_chunk)); } /* Fall Through */ case SCTP_IERROR_AUTH_BAD_KEYID: case SCTP_IERROR_BAD_SIG: return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); case SCTP_IERROR_PROTO_VIOLATION: return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); case SCTP_IERROR_NOMEM: return SCTP_DISPOSITION_NOMEM; default: /* Prevent gcc warnings */ break; } if (asoc->active_key_id != ntohs(auth_hdr->shkey_id)) { struct sctp_ulpevent *ev; ev = sctp_ulpevent_make_authkey(asoc, ntohs(auth_hdr->shkey_id), SCTP_AUTH_NEWKEY, GFP_ATOMIC); if (!ev) return -ENOMEM; sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); } return SCTP_DISPOSITION_CONSUME; } /* * Process an unknown chunk. * * Section: 3.2. Also, 2.1 in the implementor's guide. * * Chunk Types are encoded such that the highest-order two bits specify * the action that must be taken if the processing endpoint does not * recognize the Chunk Type. * * 00 - Stop processing this SCTP packet and discard it, do not process * any further chunks within it. * * 01 - Stop processing this SCTP packet and discard it, do not process * any further chunks within it, and report the unrecognized * chunk in an 'Unrecognized Chunk Type'. * * 10 - Skip this chunk and continue processing. * * 11 - Skip this chunk and continue processing, but report in an ERROR * Chunk using the 'Unrecognized Chunk Type' cause of error. * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_unk_chunk(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *unk_chunk = arg; struct sctp_chunk *err_chunk; sctp_chunkhdr_t *hdr; pr_debug("%s: processing unknown chunk id:%d\n", __func__, type.chunk); if (!sctp_vtag_verify(unk_chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the chunk has a valid length. * Since we don't know the chunk type, we use a general * chunkhdr structure to make a comparison. */ if (!sctp_chunk_length_valid(unk_chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); switch (type.chunk & SCTP_CID_ACTION_MASK) { case SCTP_CID_ACTION_DISCARD: /* Discard the packet. */ return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); case SCTP_CID_ACTION_DISCARD_ERR: /* Generate an ERROR chunk as response. */ hdr = unk_chunk->chunk_hdr; err_chunk = sctp_make_op_error(asoc, unk_chunk, SCTP_ERROR_UNKNOWN_CHUNK, hdr, SCTP_PAD4(ntohs(hdr->length)), 0); if (err_chunk) { sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(err_chunk)); } /* Discard the packet. */ sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); return SCTP_DISPOSITION_CONSUME; case SCTP_CID_ACTION_SKIP: /* Skip the chunk. */ return SCTP_DISPOSITION_DISCARD; case SCTP_CID_ACTION_SKIP_ERR: /* Generate an ERROR chunk as response. */ hdr = unk_chunk->chunk_hdr; err_chunk = sctp_make_op_error(asoc, unk_chunk, SCTP_ERROR_UNKNOWN_CHUNK, hdr, SCTP_PAD4(ntohs(hdr->length)), 0); if (err_chunk) { sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(err_chunk)); } /* Skip the chunk. */ return SCTP_DISPOSITION_CONSUME; default: break; } return SCTP_DISPOSITION_DISCARD; } /* * Discard the chunk. * * Section: 0.2, 5.2.3, 5.2.5, 5.2.6, 6.0, 8.4.6, 8.5.1c, 9.2 * [Too numerous to mention...] * Verification Tag: No verification needed. * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_discard_chunk(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; /* Make sure that the chunk has a valid length. * Since we don't know the chunk type, we use a general * chunkhdr structure to make a comparison. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); pr_debug("%s: chunk:%d is discarded\n", __func__, type.chunk); return SCTP_DISPOSITION_DISCARD; } /* * Discard the whole packet. * * Section: 8.4 2) * * 2) If the OOTB packet contains an ABORT chunk, the receiver MUST * silently discard the OOTB packet and take no further action. * * Verification Tag: No verification necessary * * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_pdiscard(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_DISCARDS); sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); return SCTP_DISPOSITION_CONSUME; } /* * The other end is violating protocol. * * Section: Not specified * Verification Tag: Not specified * Inputs * (endpoint, asoc, chunk) * * Outputs * (asoc, reply_msg, msg_up, timers, counters) * * We simply tag the chunk as a violation. The state machine will log * the violation and continue. */ sctp_disposition_t sctp_sf_violation(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; /* Make sure that the chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); return SCTP_DISPOSITION_VIOLATION; } /* * Common function to handle a protocol violation. */ static sctp_disposition_t sctp_sf_abort_violation( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, void *arg, sctp_cmd_seq_t *commands, const __u8 *payload, const size_t paylen) { struct sctp_packet *packet = NULL; struct sctp_chunk *chunk = arg; struct sctp_chunk *abort = NULL; /* SCTP-AUTH, Section 6.3: * It should be noted that if the receiver wants to tear * down an association in an authenticated way only, the * handling of malformed packets should not result in * tearing down the association. * * This means that if we only want to abort associations * in an authenticated way (i.e AUTH+ABORT), then we * can't destroy this association just because the packet * was malformed. */ if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc)) goto discard; /* Make the abort chunk. */ abort = sctp_make_abort_violation(asoc, chunk, payload, paylen); if (!abort) goto nomem; if (asoc) { /* Treat INIT-ACK as a special case during COOKIE-WAIT. */ if (chunk->chunk_hdr->type == SCTP_CID_INIT_ACK && !asoc->peer.i.init_tag) { sctp_initack_chunk_t *initack; initack = (sctp_initack_chunk_t *)chunk->chunk_hdr; if (!sctp_chunk_length_valid(chunk, sizeof(sctp_initack_chunk_t))) abort->chunk_hdr->flags |= SCTP_CHUNK_FLAG_T; else { unsigned int inittag; inittag = ntohl(initack->init_hdr.init_tag); sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_INITTAG, SCTP_U32(inittag)); } } sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); if (asoc->state <= SCTP_STATE_COOKIE_ECHOED) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNREFUSED)); sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED, SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION)); } else { sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION)); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); } } else { packet = sctp_ootb_pkt_new(net, asoc, chunk); if (!packet) goto nomem_pkt; if (sctp_test_T_bit(abort)) packet->vtag = ntohl(chunk->sctp_hdr->vtag); abort->skb->sk = ep->base.sk; sctp_packet_append_chunk(packet, abort); sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); } SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); discard: sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands); return SCTP_DISPOSITION_ABORT; nomem_pkt: sctp_chunk_free(abort); nomem: return SCTP_DISPOSITION_NOMEM; } /* * Handle a protocol violation when the chunk length is invalid. * "Invalid" length is identified as smaller than the minimal length a * given chunk can be. For example, a SACK chunk has invalid length * if its length is set to be smaller than the size of sctp_sack_chunk_t. * * We inform the other end by sending an ABORT with a Protocol Violation * error code. * * Section: Not specified * Verification Tag: Nothing to do * Inputs * (endpoint, asoc, chunk) * * Outputs * (reply_msg, msg_up, counters) * * Generate an ABORT chunk and terminate the association. */ static sctp_disposition_t sctp_sf_violation_chunklen( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { static const char err_str[] = "The following chunk had invalid length:"; return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str, sizeof(err_str)); } /* * Handle a protocol violation when the parameter length is invalid. * If the length is smaller than the minimum length of a given parameter, * or accumulated length in multi parameters exceeds the end of the chunk, * the length is considered as invalid. */ static sctp_disposition_t sctp_sf_violation_paramlen( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, void *ext, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_paramhdr *param = ext; struct sctp_chunk *abort = NULL; if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc)) goto discard; /* Make the abort chunk. */ abort = sctp_make_violation_paramlen(asoc, chunk, param); if (!abort) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION)); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); discard: sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands); return SCTP_DISPOSITION_ABORT; nomem: return SCTP_DISPOSITION_NOMEM; } /* Handle a protocol violation when the peer trying to advance the * cumulative tsn ack to a point beyond the max tsn currently sent. * * We inform the other end by sending an ABORT with a Protocol Violation * error code. */ static sctp_disposition_t sctp_sf_violation_ctsn( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { static const char err_str[] = "The cumulative tsn ack beyond the max tsn currently sent:"; return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str, sizeof(err_str)); } /* Handle protocol violation of an invalid chunk bundling. For example, * when we have an association and we receive bundled INIT-ACK, or * SHUDOWN-COMPLETE, our peer is clearly violationg the "MUST NOT bundle" * statement from the specs. Additionally, there might be an attacker * on the path and we may not want to continue this communication. */ static sctp_disposition_t sctp_sf_violation_chunk( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { static const char err_str[] = "The following chunk violates protocol:"; if (!asoc) return sctp_sf_violation(net, ep, asoc, type, arg, commands); return sctp_sf_abort_violation(net, ep, asoc, arg, commands, err_str, sizeof(err_str)); } /*************************************************************************** * These are the state functions for handling primitive (Section 10) events. ***************************************************************************/ /* * sctp_sf_do_prm_asoc * * Section: 10.1 ULP-to-SCTP * B) Associate * * Format: ASSOCIATE(local SCTP instance name, destination transport addr, * outbound stream count) * -> association id [,destination transport addr list] [,outbound stream * count] * * This primitive allows the upper layer to initiate an association to a * specific peer endpoint. * * The peer endpoint shall be specified by one of the transport addresses * which defines the endpoint (see Section 1.4). If the local SCTP * instance has not been initialized, the ASSOCIATE is considered an * error. * [This is not relevant for the kernel implementation since we do all * initialization at boot time. It we hadn't initialized we wouldn't * get anywhere near this code.] * * An association id, which is a local handle to the SCTP association, * will be returned on successful establishment of the association. If * SCTP is not able to open an SCTP association with the peer endpoint, * an error is returned. * [In the kernel implementation, the struct sctp_association needs to * be created BEFORE causing this primitive to run.] * * Other association parameters may be returned, including the * complete destination transport addresses of the peer as well as the * outbound stream count of the local endpoint. One of the transport * address from the returned destination addresses will be selected by * the local endpoint as default primary path for sending SCTP packets * to this peer. The returned "destination transport addr list" can * be used by the ULP to change the default primary path or to force * sending a packet to a specific transport address. [All of this * stuff happens when the INIT ACK arrives. This is a NON-BLOCKING * function.] * * Mandatory attributes: * * o local SCTP instance name - obtained from the INITIALIZE operation. * [This is the argument asoc.] * o destination transport addr - specified as one of the transport * addresses of the peer endpoint with which the association is to be * established. * [This is asoc->peer.active_path.] * o outbound stream count - the number of outbound streams the ULP * would like to open towards this peer endpoint. * [BUG: This is not currently implemented.] * Optional attributes: * * None. * * The return value is a disposition. */ sctp_disposition_t sctp_sf_do_prm_asoc(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *repl; struct sctp_association *my_asoc; /* The comment below says that we enter COOKIE-WAIT AFTER * sending the INIT, but that doesn't actually work in our * implementation... */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_COOKIE_WAIT)); /* RFC 2960 5.1 Normal Establishment of an Association * * A) "A" first sends an INIT chunk to "Z". In the INIT, "A" * must provide its Verification Tag (Tag_A) in the Initiate * Tag field. Tag_A SHOULD be a random number in the range of * 1 to 4294967295 (see 5.3.1 for Tag value selection). ... */ repl = sctp_make_init(asoc, &asoc->base.bind_addr, GFP_ATOMIC, 0); if (!repl) goto nomem; /* Choose transport for INIT. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT, SCTP_CHUNK(repl)); /* Cast away the const modifier, as we want to just * rerun it through as a sideffect. */ my_asoc = (struct sctp_association *)asoc; sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(my_asoc)); /* After sending the INIT, "A" starts the T1-init timer and * enters the COOKIE-WAIT state. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* * Process the SEND primitive. * * Section: 10.1 ULP-to-SCTP * E) Send * * Format: SEND(association id, buffer address, byte count [,context] * [,stream id] [,life time] [,destination transport address] * [,unorder flag] [,no-bundle flag] [,payload protocol-id] ) * -> result * * This is the main method to send user data via SCTP. * * Mandatory attributes: * * o association id - local handle to the SCTP association * * o buffer address - the location where the user message to be * transmitted is stored; * * o byte count - The size of the user data in number of bytes; * * Optional attributes: * * o context - an optional 32 bit integer that will be carried in the * sending failure notification to the ULP if the transportation of * this User Message fails. * * o stream id - to indicate which stream to send the data on. If not * specified, stream 0 will be used. * * o life time - specifies the life time of the user data. The user data * will not be sent by SCTP after the life time expires. This * parameter can be used to avoid efforts to transmit stale * user messages. SCTP notifies the ULP if the data cannot be * initiated to transport (i.e. sent to the destination via SCTP's * send primitive) within the life time variable. However, the * user data will be transmitted if SCTP has attempted to transmit a * chunk before the life time expired. * * o destination transport address - specified as one of the destination * transport addresses of the peer endpoint to which this packet * should be sent. Whenever possible, SCTP should use this destination * transport address for sending the packets, instead of the current * primary path. * * o unorder flag - this flag, if present, indicates that the user * would like the data delivered in an unordered fashion to the peer * (i.e., the U flag is set to 1 on all DATA chunks carrying this * message). * * o no-bundle flag - instructs SCTP not to bundle this user data with * other outbound DATA chunks. SCTP MAY still bundle even when * this flag is present, when faced with network congestion. * * o payload protocol-id - A 32 bit unsigned integer that is to be * passed to the peer indicating the type of payload protocol data * being transmitted. This value is passed as opaque data by SCTP. * * The return value is the disposition. */ sctp_disposition_t sctp_sf_do_prm_send(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_datamsg *msg = arg; sctp_add_cmd_sf(commands, SCTP_CMD_SEND_MSG, SCTP_DATAMSG(msg)); return SCTP_DISPOSITION_CONSUME; } /* * Process the SHUTDOWN primitive. * * Section: 10.1: * C) Shutdown * * Format: SHUTDOWN(association id) * -> result * * Gracefully closes an association. Any locally queued user data * will be delivered to the peer. The association will be terminated only * after the peer acknowledges all the SCTP packets sent. A success code * will be returned on successful termination of the association. If * attempting to terminate the association results in a failure, an error * code shall be returned. * * Mandatory attributes: * * o association id - local handle to the SCTP association * * Optional attributes: * * None. * * The return value is the disposition. */ sctp_disposition_t sctp_sf_do_9_2_prm_shutdown( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { int disposition; /* From 9.2 Shutdown of an Association * Upon receipt of the SHUTDOWN primitive from its upper * layer, the endpoint enters SHUTDOWN-PENDING state and * remains there until all outstanding data has been * acknowledged by its peer. The endpoint accepts no new data * from its upper layer, but retransmits data to the far end * if necessary to fill gaps. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING)); disposition = SCTP_DISPOSITION_CONSUME; if (sctp_outq_is_empty(&asoc->outqueue)) { disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type, arg, commands); } return disposition; } /* * Process the ABORT primitive. * * Section: 10.1: * C) Abort * * Format: Abort(association id [, cause code]) * -> result * * Ungracefully closes an association. Any locally queued user data * will be discarded and an ABORT chunk is sent to the peer. A success code * will be returned on successful abortion of the association. If * attempting to abort the association results in a failure, an error * code shall be returned. * * Mandatory attributes: * * o association id - local handle to the SCTP association * * Optional attributes: * * o cause code - reason of the abort to be passed to the peer * * None. * * The return value is the disposition. */ sctp_disposition_t sctp_sf_do_9_1_prm_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* From 9.1 Abort of an Association * Upon receipt of the ABORT primitive from its upper * layer, the endpoint enters CLOSED state and * discard all outstanding data has been * acknowledged by its peer. The endpoint accepts no new data * from its upper layer, but retransmits data to the far end * if necessary to fill gaps. */ struct sctp_chunk *abort = arg; if (abort) sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); /* Even if we can't send the ABORT due to low memory delete the * TCB. This is a departure from our typical NOMEM handling. */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); /* Delete the established association. */ sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_USER_ABORT)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } /* We tried an illegal operation on an association which is closed. */ sctp_disposition_t sctp_sf_error_closed(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR, SCTP_ERROR(-EINVAL)); return SCTP_DISPOSITION_CONSUME; } /* We tried an illegal operation on an association which is shutting * down. */ sctp_disposition_t sctp_sf_error_shutdown(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR, SCTP_ERROR(-ESHUTDOWN)); return SCTP_DISPOSITION_CONSUME; } /* * sctp_cookie_wait_prm_shutdown * * Section: 4 Note: 2 * Verification Tag: * Inputs * (endpoint, asoc) * * The RFC does not explicitly address this issue, but is the route through the * state table when someone issues a shutdown while in COOKIE_WAIT state. * * Outputs * (timers) */ sctp_disposition_t sctp_sf_cookie_wait_prm_shutdown( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_CLOSED)); SCTP_INC_STATS(net, SCTP_MIB_SHUTDOWNS); sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); return SCTP_DISPOSITION_DELETE_TCB; } /* * sctp_cookie_echoed_prm_shutdown * * Section: 4 Note: 2 * Verification Tag: * Inputs * (endpoint, asoc) * * The RFC does not explcitly address this issue, but is the route through the * state table when someone issues a shutdown while in COOKIE_ECHOED state. * * Outputs * (timers) */ sctp_disposition_t sctp_sf_cookie_echoed_prm_shutdown( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* There is a single T1 timer, so we should be able to use * common function with the COOKIE-WAIT state. */ return sctp_sf_cookie_wait_prm_shutdown(net, ep, asoc, type, arg, commands); } /* * sctp_sf_cookie_wait_prm_abort * * Section: 4 Note: 2 * Verification Tag: * Inputs * (endpoint, asoc) * * The RFC does not explicitly address this issue, but is the route through the * state table when someone issues an abort while in COOKIE_WAIT state. * * Outputs * (timers) */ sctp_disposition_t sctp_sf_cookie_wait_prm_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *abort = arg; /* Stop T1-init timer */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); if (abort) sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_CLOSED)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); /* Even if we can't send the ABORT due to low memory delete the * TCB. This is a departure from our typical NOMEM handling. */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNREFUSED)); /* Delete the established association. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED, SCTP_PERR(SCTP_ERROR_USER_ABORT)); return SCTP_DISPOSITION_ABORT; } /* * sctp_sf_cookie_echoed_prm_abort * * Section: 4 Note: 3 * Verification Tag: * Inputs * (endpoint, asoc) * * The RFC does not explcitly address this issue, but is the route through the * state table when someone issues an abort while in COOKIE_ECHOED state. * * Outputs * (timers) */ sctp_disposition_t sctp_sf_cookie_echoed_prm_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* There is a single T1 timer, so we should be able to use * common function with the COOKIE-WAIT state. */ return sctp_sf_cookie_wait_prm_abort(net, ep, asoc, type, arg, commands); } /* * sctp_sf_shutdown_pending_prm_abort * * Inputs * (endpoint, asoc) * * The RFC does not explicitly address this issue, but is the route through the * state table when someone issues an abort while in SHUTDOWN-PENDING state. * * Outputs * (timers) */ sctp_disposition_t sctp_sf_shutdown_pending_prm_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* Stop the T5-shutdown guard timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD)); return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands); } /* * sctp_sf_shutdown_sent_prm_abort * * Inputs * (endpoint, asoc) * * The RFC does not explicitly address this issue, but is the route through the * state table when someone issues an abort while in SHUTDOWN-SENT state. * * Outputs * (timers) */ sctp_disposition_t sctp_sf_shutdown_sent_prm_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* Stop the T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); /* Stop the T5-shutdown guard timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD)); return sctp_sf_do_9_1_prm_abort(net, ep, asoc, type, arg, commands); } /* * sctp_sf_cookie_echoed_prm_abort * * Inputs * (endpoint, asoc) * * The RFC does not explcitly address this issue, but is the route through the * state table when someone issues an abort while in COOKIE_ECHOED state. * * Outputs * (timers) */ sctp_disposition_t sctp_sf_shutdown_ack_sent_prm_abort( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { /* The same T2 timer, so we should be able to use * common function with the SHUTDOWN-SENT state. */ return sctp_sf_shutdown_sent_prm_abort(net, ep, asoc, type, arg, commands); } /* * Process the REQUESTHEARTBEAT primitive * * 10.1 ULP-to-SCTP * J) Request Heartbeat * * Format: REQUESTHEARTBEAT(association id, destination transport address) * * -> result * * Instructs the local endpoint to perform a HeartBeat on the specified * destination transport address of the given association. The returned * result should indicate whether the transmission of the HEARTBEAT * chunk to the destination address is successful. * * Mandatory attributes: * * o association id - local handle to the SCTP association * * o destination transport address - the transport address of the * association on which a heartbeat should be issued. */ sctp_disposition_t sctp_sf_do_prm_requestheartbeat( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { if (SCTP_DISPOSITION_NOMEM == sctp_sf_heartbeat(ep, asoc, type, (struct sctp_transport *)arg, commands)) return SCTP_DISPOSITION_NOMEM; /* * RFC 2960 (bis), section 8.3 * * D) Request an on-demand HEARTBEAT on a specific destination * transport address of a given association. * * The endpoint should increment the respective error counter of * the destination transport address each time a HEARTBEAT is sent * to that address and not acknowledged within one RTO. * */ sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT, SCTP_TRANSPORT(arg)); return SCTP_DISPOSITION_CONSUME; } /* * ADDIP Section 4.1 ASCONF Chunk Procedures * When an endpoint has an ASCONF signaled change to be sent to the * remote endpoint it should do A1 to A9 */ sctp_disposition_t sctp_sf_do_prm_asconf(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk)); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk)); return SCTP_DISPOSITION_CONSUME; } /* * Ignore the primitive event * * The return value is the disposition of the primitive. */ sctp_disposition_t sctp_sf_ignore_primitive( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { pr_debug("%s: primitive type:%d is ignored\n", __func__, type.primitive); return SCTP_DISPOSITION_DISCARD; } /*************************************************************************** * These are the state functions for the OTHER events. ***************************************************************************/ /* * When the SCTP stack has no more user data to send or retransmit, this * notification is given to the user. Also, at the time when a user app * subscribes to this event, if there is no data to be sent or * retransmit, the stack will immediately send up this notification. */ sctp_disposition_t sctp_sf_do_no_pending_tsn( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_ulpevent *event; event = sctp_ulpevent_make_sender_dry_event(asoc, GFP_ATOMIC); if (!event) return SCTP_DISPOSITION_NOMEM; sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(event)); return SCTP_DISPOSITION_CONSUME; } /* * Start the shutdown negotiation. * * From Section 9.2: * Once all its outstanding data has been acknowledged, the endpoint * shall send a SHUTDOWN chunk to its peer including in the Cumulative * TSN Ack field the last sequential TSN it has received from the peer. * It shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT * state. If the timer expires, the endpoint must re-send the SHUTDOWN * with the updated last sequential TSN received from its peer. * * The return value is the disposition. */ sctp_disposition_t sctp_sf_do_9_2_start_shutdown( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *reply; /* Once all its outstanding data has been acknowledged, the * endpoint shall send a SHUTDOWN chunk to its peer including * in the Cumulative TSN Ack field the last sequential TSN it * has received from the peer. */ reply = sctp_make_shutdown(asoc, NULL); if (!reply) goto nomem; /* Set the transport for the SHUTDOWN chunk and the timeout for the * T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply)); /* It shall then start the T2-shutdown timer */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); /* RFC 4960 Section 9.2 * The sender of the SHUTDOWN MAY also start an overall guard timer * 'T5-shutdown-guard' to bound the overall time for shutdown sequence. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD)); if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); /* and enter the SHUTDOWN-SENT state. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_SHUTDOWN_SENT)); /* sctp-implguide 2.10 Issues with Heartbeating and failover * * HEARTBEAT ... is discontinued after sending either SHUTDOWN * or SHUTDOWN-ACK. */ sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* * Generate a SHUTDOWN ACK now that everything is SACK'd. * * From Section 9.2: * * If it has no more outstanding DATA chunks, the SHUTDOWN receiver * shall send a SHUTDOWN ACK and start a T2-shutdown timer of its own, * entering the SHUTDOWN-ACK-SENT state. If the timer expires, the * endpoint must re-send the SHUTDOWN ACK. * * The return value is the disposition. */ sctp_disposition_t sctp_sf_do_9_2_shutdown_ack( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = (struct sctp_chunk *) arg; struct sctp_chunk *reply; /* There are 2 ways of getting here: * 1) called in response to a SHUTDOWN chunk * 2) called when SCTP_EVENT_NO_PENDING_TSN event is issued. * * For the case (2), the arg parameter is set to NULL. We need * to check that we have a chunk before accessing it's fields. */ if (chunk) { if (!sctp_vtag_verify(chunk, asoc)) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* Make sure that the SHUTDOWN chunk has a valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); } /* If it has no more outstanding DATA chunks, the SHUTDOWN receiver * shall send a SHUTDOWN ACK ... */ reply = sctp_make_shutdown_ack(asoc, chunk); if (!reply) goto nomem; /* Set the transport for the SHUTDOWN ACK chunk and the timeout for * the T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply)); /* and start/restart a T2-shutdown timer of its own, */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); /* Enter the SHUTDOWN-ACK-SENT state. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_SHUTDOWN_ACK_SENT)); /* sctp-implguide 2.10 Issues with Heartbeating and failover * * HEARTBEAT ... is discontinued after sending either SHUTDOWN * or SHUTDOWN-ACK. */ sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* * Ignore the event defined as other * * The return value is the disposition of the event. */ sctp_disposition_t sctp_sf_ignore_other(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { pr_debug("%s: the event other type:%d is ignored\n", __func__, type.other); return SCTP_DISPOSITION_DISCARD; } /************************************************************ * These are the state functions for handling timeout events. ************************************************************/ /* * RTX Timeout * * Section: 6.3.3 Handle T3-rtx Expiration * * Whenever the retransmission timer T3-rtx expires for a destination * address, do the following: * [See below] * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_do_6_3_3_rtx(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_transport *transport = arg; SCTP_INC_STATS(net, SCTP_MIB_T3_RTX_EXPIREDS); if (asoc->overall_error_count >= asoc->max_retrans) { if (asoc->peer.zero_window_announced && asoc->state == SCTP_STATE_SHUTDOWN_PENDING) { /* * We are here likely because the receiver had its rwnd * closed for a while and we have not been able to * transmit the locally queued data within the maximum * retransmission attempts limit. Start the T5 * shutdown guard timer to give the receiver one last * chance and some additional time to recover before * aborting. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START_ONCE, SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD)); } else { sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); /* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */ sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_NO_ERROR)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_DELETE_TCB; } } /* E1) For the destination address for which the timer * expires, adjust its ssthresh with rules defined in Section * 7.2.3 and set the cwnd <- MTU. */ /* E2) For the destination address for which the timer * expires, set RTO <- RTO * 2 ("back off the timer"). The * maximum value discussed in rule C7 above (RTO.max) may be * used to provide an upper bound to this doubling operation. */ /* E3) Determine how many of the earliest (i.e., lowest TSN) * outstanding DATA chunks for the address for which the * T3-rtx has expired will fit into a single packet, subject * to the MTU constraint for the path corresponding to the * destination transport address to which the retransmission * is being sent (this may be different from the address for * which the timer expires [see Section 6.4]). Call this * value K. Bundle and retransmit those K DATA chunks in a * single packet to the destination endpoint. * * Note: Any DATA chunks that were sent to the address for * which the T3-rtx timer expired but did not fit in one MTU * (rule E3 above), should be marked for retransmission and * sent as soon as cwnd allows (normally when a SACK arrives). */ /* Do some failure management (Section 8.2). */ sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport)); /* NB: Rules E4 and F1 are implicit in R1. */ sctp_add_cmd_sf(commands, SCTP_CMD_RETRAN, SCTP_TRANSPORT(transport)); return SCTP_DISPOSITION_CONSUME; } /* * Generate delayed SACK on timeout * * Section: 6.2 Acknowledgement on Reception of DATA Chunks * * The guidelines on delayed acknowledgement algorithm specified in * Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an * acknowledgement SHOULD be generated for at least every second packet * (not every second DATA chunk) received, and SHOULD be generated * within 200 ms of the arrival of any unacknowledged DATA chunk. In * some situations it may be beneficial for an SCTP transmitter to be * more conservative than the algorithms detailed in this document * allow. However, an SCTP transmitter MUST NOT be more aggressive than * the following algorithms allow. */ sctp_disposition_t sctp_sf_do_6_2_sack(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { SCTP_INC_STATS(net, SCTP_MIB_DELAY_SACK_EXPIREDS); sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE()); return SCTP_DISPOSITION_CONSUME; } /* * sctp_sf_t1_init_timer_expire * * Section: 4 Note: 2 * Verification Tag: * Inputs * (endpoint, asoc) * * RFC 2960 Section 4 Notes * 2) If the T1-init timer expires, the endpoint MUST retransmit INIT * and re-start the T1-init timer without changing state. This MUST * be repeated up to 'Max.Init.Retransmits' times. After that, the * endpoint MUST abort the initialization process and report the * error to SCTP user. * * Outputs * (timers, events) * */ sctp_disposition_t sctp_sf_t1_init_timer_expire(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *repl = NULL; struct sctp_bind_addr *bp; int attempts = asoc->init_err_counter + 1; pr_debug("%s: timer T1 expired (INIT)\n", __func__); SCTP_INC_STATS(net, SCTP_MIB_T1_INIT_EXPIREDS); if (attempts <= asoc->max_init_attempts) { bp = (struct sctp_bind_addr *) &asoc->base.bind_addr; repl = sctp_make_init(asoc, bp, GFP_ATOMIC, 0); if (!repl) return SCTP_DISPOSITION_NOMEM; /* Choose transport for INIT. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT, SCTP_CHUNK(repl)); /* Issue a sideeffect to do the needed accounting. */ sctp_add_cmd_sf(commands, SCTP_CMD_INIT_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); } else { pr_debug("%s: giving up on INIT, attempts:%d " "max_init_attempts:%d\n", __func__, attempts, asoc->max_init_attempts); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED, SCTP_PERR(SCTP_ERROR_NO_ERROR)); return SCTP_DISPOSITION_DELETE_TCB; } return SCTP_DISPOSITION_CONSUME; } /* * sctp_sf_t1_cookie_timer_expire * * Section: 4 Note: 2 * Verification Tag: * Inputs * (endpoint, asoc) * * RFC 2960 Section 4 Notes * 3) If the T1-cookie timer expires, the endpoint MUST retransmit * COOKIE ECHO and re-start the T1-cookie timer without changing * state. This MUST be repeated up to 'Max.Init.Retransmits' times. * After that, the endpoint MUST abort the initialization process and * report the error to SCTP user. * * Outputs * (timers, events) * */ sctp_disposition_t sctp_sf_t1_cookie_timer_expire(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *repl = NULL; int attempts = asoc->init_err_counter + 1; pr_debug("%s: timer T1 expired (COOKIE-ECHO)\n", __func__); SCTP_INC_STATS(net, SCTP_MIB_T1_COOKIE_EXPIREDS); if (attempts <= asoc->max_init_attempts) { repl = sctp_make_cookie_echo(asoc, NULL); if (!repl) return SCTP_DISPOSITION_NOMEM; sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT, SCTP_CHUNK(repl)); /* Issue a sideeffect to do the needed accounting. */ sctp_add_cmd_sf(commands, SCTP_CMD_COOKIEECHO_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); } else { sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED, SCTP_PERR(SCTP_ERROR_NO_ERROR)); return SCTP_DISPOSITION_DELETE_TCB; } return SCTP_DISPOSITION_CONSUME; } /* RFC2960 9.2 If the timer expires, the endpoint must re-send the SHUTDOWN * with the updated last sequential TSN received from its peer. * * An endpoint should limit the number of retransmissions of the * SHUTDOWN chunk to the protocol parameter 'Association.Max.Retrans'. * If this threshold is exceeded the endpoint should destroy the TCB and * MUST report the peer endpoint unreachable to the upper layer (and * thus the association enters the CLOSED state). The reception of any * packet from its peer (i.e. as the peer sends all of its queued DATA * chunks) should clear the endpoint's retransmission count and restart * the T2-Shutdown timer, giving its peer ample opportunity to transmit * all of its queued DATA chunks that have not yet been sent. */ sctp_disposition_t sctp_sf_t2_timer_expire(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *reply = NULL; pr_debug("%s: timer T2 expired\n", __func__); SCTP_INC_STATS(net, SCTP_MIB_T2_SHUTDOWN_EXPIREDS); ((struct sctp_association *)asoc)->shutdown_retries++; if (asoc->overall_error_count >= asoc->max_retrans) { sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); /* Note: CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */ sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_NO_ERROR)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_DELETE_TCB; } switch (asoc->state) { case SCTP_STATE_SHUTDOWN_SENT: reply = sctp_make_shutdown(asoc, NULL); break; case SCTP_STATE_SHUTDOWN_ACK_SENT: reply = sctp_make_shutdown_ack(asoc, NULL); break; default: BUG(); break; } if (!reply) goto nomem; /* Do some failure management (Section 8.2). * If we remove the transport an SHUTDOWN was last sent to, don't * do failure management. */ if (asoc->shutdown_last_sent_to) sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(asoc->shutdown_last_sent_to)); /* Set the transport for the SHUTDOWN/ACK chunk and the timeout for * the T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply)); /* Restart the T2-shutdown timer. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); return SCTP_DISPOSITION_CONSUME; nomem: return SCTP_DISPOSITION_NOMEM; } /* * ADDIP Section 4.1 ASCONF CHunk Procedures * If the T4 RTO timer expires the endpoint should do B1 to B5 */ sctp_disposition_t sctp_sf_t4_timer_expire( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = asoc->addip_last_asconf; struct sctp_transport *transport = chunk->transport; SCTP_INC_STATS(net, SCTP_MIB_T4_RTO_EXPIREDS); /* ADDIP 4.1 B1) Increment the error counters and perform path failure * detection on the appropriate destination address as defined in * RFC2960 [5] section 8.1 and 8.2. */ if (transport) sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport)); /* Reconfig T4 timer and transport. */ sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk)); /* ADDIP 4.1 B2) Increment the association error counters and perform * endpoint failure detection on the association as defined in * RFC2960 [5] section 8.1 and 8.2. * association error counter is incremented in SCTP_CMD_STRIKE. */ if (asoc->overall_error_count >= asoc->max_retrans) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_NO_ERROR)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } /* ADDIP 4.1 B3) Back-off the destination address RTO value to which * the ASCONF chunk was sent by doubling the RTO timer value. * This is done in SCTP_CMD_STRIKE. */ /* ADDIP 4.1 B4) Re-transmit the ASCONF Chunk last sent and if possible * choose an alternate destination address (please refer to RFC2960 * [5] section 6.4.1). An endpoint MUST NOT add new parameters to this * chunk, it MUST be the same (including its serial number) as the last * ASCONF sent. */ sctp_chunk_hold(asoc->addip_last_asconf); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asoc->addip_last_asconf)); /* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different * destination is selected, then the RTO used will be that of the new * destination address. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); return SCTP_DISPOSITION_CONSUME; } /* sctpimpguide-05 Section 2.12.2 * The sender of the SHUTDOWN MAY also start an overall guard timer * 'T5-shutdown-guard' to bound the overall time for shutdown sequence. * At the expiration of this timer the sender SHOULD abort the association * by sending an ABORT chunk. */ sctp_disposition_t sctp_sf_t5_timer_expire(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *reply = NULL; pr_debug("%s: timer T5 expired\n", __func__); SCTP_INC_STATS(net, SCTP_MIB_T5_SHUTDOWN_GUARD_EXPIREDS); reply = sctp_make_abort(asoc, NULL, 0); if (!reply) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply)); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ETIMEDOUT)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_NO_ERROR)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_DELETE_TCB; nomem: return SCTP_DISPOSITION_NOMEM; } /* Handle expiration of AUTOCLOSE timer. When the autoclose timer expires, * the association is automatically closed by starting the shutdown process. * The work that needs to be done is same as when SHUTDOWN is initiated by * the user. So this routine looks same as sctp_sf_do_9_2_prm_shutdown(). */ sctp_disposition_t sctp_sf_autoclose_timer_expire( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { int disposition; SCTP_INC_STATS(net, SCTP_MIB_AUTOCLOSE_EXPIREDS); /* From 9.2 Shutdown of an Association * Upon receipt of the SHUTDOWN primitive from its upper * layer, the endpoint enters SHUTDOWN-PENDING state and * remains there until all outstanding data has been * acknowledged by its peer. The endpoint accepts no new data * from its upper layer, but retransmits data to the far end * if necessary to fill gaps. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING)); disposition = SCTP_DISPOSITION_CONSUME; if (sctp_outq_is_empty(&asoc->outqueue)) { disposition = sctp_sf_do_9_2_start_shutdown(net, ep, asoc, type, arg, commands); } return disposition; } /***************************************************************************** * These are sa state functions which could apply to all types of events. ****************************************************************************/ /* * This table entry is not implemented. * * Inputs * (endpoint, asoc, chunk) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_not_impl(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { return SCTP_DISPOSITION_NOT_IMPL; } /* * This table entry represents a bug. * * Inputs * (endpoint, asoc, chunk) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_bug(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { return SCTP_DISPOSITION_BUG; } /* * This table entry represents the firing of a timer in the wrong state. * Since timer deletion cannot be guaranteed a timer 'may' end up firing * when the association is in the wrong state. This event should * be ignored, so as to prevent any rearming of the timer. * * Inputs * (endpoint, asoc, chunk) * * The return value is the disposition of the chunk. */ sctp_disposition_t sctp_sf_timer_ignore(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { pr_debug("%s: timer %d ignored\n", __func__, type.chunk); return SCTP_DISPOSITION_CONSUME; } /******************************************************************** * 2nd Level Abstractions ********************************************************************/ /* Pull the SACK chunk based on the SACK header. */ static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk) { struct sctp_sackhdr *sack; unsigned int len; __u16 num_blocks; __u16 num_dup_tsns; /* Protect ourselves from reading too far into * the skb from a bogus sender. */ sack = (struct sctp_sackhdr *) chunk->skb->data; num_blocks = ntohs(sack->num_gap_ack_blocks); num_dup_tsns = ntohs(sack->num_dup_tsns); len = sizeof(struct sctp_sackhdr); len += (num_blocks + num_dup_tsns) * sizeof(__u32); if (len > chunk->skb->len) return NULL; skb_pull(chunk->skb, len); return sack; } /* Create an ABORT packet to be sent as a response, with the specified * error causes. */ static struct sctp_packet *sctp_abort_pkt_new(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, struct sctp_chunk *chunk, const void *payload, size_t paylen) { struct sctp_packet *packet; struct sctp_chunk *abort; packet = sctp_ootb_pkt_new(net, asoc, chunk); if (packet) { /* Make an ABORT. * The T bit will be set if the asoc is NULL. */ abort = sctp_make_abort(asoc, chunk, paylen); if (!abort) { sctp_ootb_pkt_free(packet); return NULL; } /* Reflect vtag if T-Bit is set */ if (sctp_test_T_bit(abort)) packet->vtag = ntohl(chunk->sctp_hdr->vtag); /* Add specified error causes, i.e., payload, to the * end of the chunk. */ sctp_addto_chunk(abort, paylen, payload); /* Set the skb to the belonging sock for accounting. */ abort->skb->sk = ep->base.sk; sctp_packet_append_chunk(packet, abort); } return packet; } /* Allocate a packet for responding in the OOTB conditions. */ static struct sctp_packet *sctp_ootb_pkt_new(struct net *net, const struct sctp_association *asoc, const struct sctp_chunk *chunk) { struct sctp_packet *packet; struct sctp_transport *transport; __u16 sport; __u16 dport; __u32 vtag; /* Get the source and destination port from the inbound packet. */ sport = ntohs(chunk->sctp_hdr->dest); dport = ntohs(chunk->sctp_hdr->source); /* The V-tag is going to be the same as the inbound packet if no * association exists, otherwise, use the peer's vtag. */ if (asoc) { /* Special case the INIT-ACK as there is no peer's vtag * yet. */ switch (chunk->chunk_hdr->type) { case SCTP_CID_INIT_ACK: { sctp_initack_chunk_t *initack; initack = (sctp_initack_chunk_t *)chunk->chunk_hdr; vtag = ntohl(initack->init_hdr.init_tag); break; } default: vtag = asoc->peer.i.init_tag; break; } } else { /* Special case the INIT and stale COOKIE_ECHO as there is no * vtag yet. */ switch (chunk->chunk_hdr->type) { case SCTP_CID_INIT: { sctp_init_chunk_t *init; init = (sctp_init_chunk_t *)chunk->chunk_hdr; vtag = ntohl(init->init_hdr.init_tag); break; } default: vtag = ntohl(chunk->sctp_hdr->vtag); break; } } /* Make a transport for the bucket, Eliza... */ transport = sctp_transport_new(net, sctp_source(chunk), GFP_ATOMIC); if (!transport) goto nomem; /* Cache a route for the transport with the chunk's destination as * the source address. */ sctp_transport_route(transport, (union sctp_addr *)&chunk->dest, sctp_sk(net->sctp.ctl_sock)); packet = sctp_packet_init(&transport->packet, transport, sport, dport); packet = sctp_packet_config(packet, vtag, 0); return packet; nomem: return NULL; } /* Free the packet allocated earlier for responding in the OOTB condition. */ void sctp_ootb_pkt_free(struct sctp_packet *packet) { sctp_transport_free(packet->transport); } /* Send a stale cookie error when a invalid COOKIE ECHO chunk is found */ static void sctp_send_stale_cookie_err(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const struct sctp_chunk *chunk, sctp_cmd_seq_t *commands, struct sctp_chunk *err_chunk) { struct sctp_packet *packet; if (err_chunk) { packet = sctp_ootb_pkt_new(net, asoc, chunk); if (packet) { struct sctp_signed_cookie *cookie; /* Override the OOTB vtag from the cookie. */ cookie = chunk->subh.cookie_hdr; packet->vtag = cookie->c.peer_vtag; /* Set the skb to the belonging sock for accounting. */ err_chunk->skb->sk = ep->base.sk; sctp_packet_append_chunk(packet, err_chunk); sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(packet)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); } else sctp_chunk_free (err_chunk); } } /* Process a data chunk */ static int sctp_eat_data(const struct sctp_association *asoc, struct sctp_chunk *chunk, sctp_cmd_seq_t *commands) { sctp_datahdr_t *data_hdr; struct sctp_chunk *err; size_t datalen; sctp_verb_t deliver; int tmp; __u32 tsn; struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map; struct sock *sk = asoc->base.sk; struct net *net = sock_net(sk); u16 ssn; u16 sid; u8 ordered = 0; data_hdr = chunk->subh.data_hdr = (sctp_datahdr_t *)chunk->skb->data; skb_pull(chunk->skb, sizeof(sctp_datahdr_t)); tsn = ntohl(data_hdr->tsn); pr_debug("%s: TSN 0x%x\n", __func__, tsn); /* ASSERT: Now skb->data is really the user data. */ /* Process ECN based congestion. * * Since the chunk structure is reused for all chunks within * a packet, we use ecn_ce_done to track if we've already * done CE processing for this packet. * * We need to do ECN processing even if we plan to discard the * chunk later. */ if (asoc->peer.ecn_capable && !chunk->ecn_ce_done) { struct sctp_af *af = SCTP_INPUT_CB(chunk->skb)->af; chunk->ecn_ce_done = 1; if (af->is_ce(sctp_gso_headskb(chunk->skb))) { /* Do real work as sideffect. */ sctp_add_cmd_sf(commands, SCTP_CMD_ECN_CE, SCTP_U32(tsn)); } } tmp = sctp_tsnmap_check(&asoc->peer.tsn_map, tsn); if (tmp < 0) { /* The TSN is too high--silently discard the chunk and * count on it getting retransmitted later. */ if (chunk->asoc) chunk->asoc->stats.outofseqtsns++; return SCTP_IERROR_HIGH_TSN; } else if (tmp > 0) { /* This is a duplicate. Record it. */ sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_DUP, SCTP_U32(tsn)); return SCTP_IERROR_DUP_TSN; } /* This is a new TSN. */ /* Discard if there is no room in the receive window. * Actually, allow a little bit of overflow (up to a MTU). */ datalen = ntohs(chunk->chunk_hdr->length); datalen -= sizeof(sctp_data_chunk_t); deliver = SCTP_CMD_CHUNK_ULP; /* Think about partial delivery. */ if ((datalen >= asoc->rwnd) && (!asoc->ulpq.pd_mode)) { /* Even if we don't accept this chunk there is * memory pressure. */ sctp_add_cmd_sf(commands, SCTP_CMD_PART_DELIVER, SCTP_NULL()); } /* Spill over rwnd a little bit. Note: While allowed, this spill over * seems a bit troublesome in that frag_point varies based on * PMTU. In cases, such as loopback, this might be a rather * large spill over. */ if ((!chunk->data_accepted) && (!asoc->rwnd || asoc->rwnd_over || (datalen > asoc->rwnd + asoc->frag_point))) { /* If this is the next TSN, consider reneging to make * room. Note: Playing nice with a confused sender. A * malicious sender can still eat up all our buffer * space and in the future we may want to detect and * do more drastic reneging. */ if (sctp_tsnmap_has_gap(map) && (sctp_tsnmap_get_ctsn(map) + 1) == tsn) { pr_debug("%s: reneging for tsn:%u\n", __func__, tsn); deliver = SCTP_CMD_RENEGE; } else { pr_debug("%s: discard tsn:%u len:%zu, rwnd:%d\n", __func__, tsn, datalen, asoc->rwnd); return SCTP_IERROR_IGNORE_TSN; } } /* * Also try to renege to limit our memory usage in the event that * we are under memory pressure * If we can't renege, don't worry about it, the sk_rmem_schedule * in sctp_ulpevent_make_rcvmsg will drop the frame if we grow our * memory usage too much */ if (*sk->sk_prot_creator->memory_pressure) { if (sctp_tsnmap_has_gap(map) && (sctp_tsnmap_get_ctsn(map) + 1) == tsn) { pr_debug("%s: under pressure, reneging for tsn:%u\n", __func__, tsn); deliver = SCTP_CMD_RENEGE; } } /* * Section 3.3.10.9 No User Data (9) * * Cause of error * --------------- * No User Data: This error cause is returned to the originator of a * DATA chunk if a received DATA chunk has no user data. */ if (unlikely(0 == datalen)) { err = sctp_make_abort_no_data(asoc, chunk, tsn); if (err) { sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(err)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_NO_DATA)); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); return SCTP_IERROR_NO_DATA; } chunk->data_accepted = 1; /* Note: Some chunks may get overcounted (if we drop) or overcounted * if we renege and the chunk arrives again. */ if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) { SCTP_INC_STATS(net, SCTP_MIB_INUNORDERCHUNKS); if (chunk->asoc) chunk->asoc->stats.iuodchunks++; } else { SCTP_INC_STATS(net, SCTP_MIB_INORDERCHUNKS); if (chunk->asoc) chunk->asoc->stats.iodchunks++; ordered = 1; } /* RFC 2960 6.5 Stream Identifier and Stream Sequence Number * * If an endpoint receive a DATA chunk with an invalid stream * identifier, it shall acknowledge the reception of the DATA chunk * following the normal procedure, immediately send an ERROR chunk * with cause set to "Invalid Stream Identifier" (See Section 3.3.10) * and discard the DATA chunk. */ sid = ntohs(data_hdr->stream); if (sid >= asoc->c.sinit_max_instreams) { /* Mark tsn as received even though we drop it */ sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_TSN, SCTP_U32(tsn)); err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_INV_STRM, &data_hdr->stream, sizeof(data_hdr->stream), sizeof(u16)); if (err) sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(err)); return SCTP_IERROR_BAD_STREAM; } /* Check to see if the SSN is possible for this TSN. * The biggest gap we can record is 4K wide. Since SSNs wrap * at an unsigned short, there is no way that an SSN can * wrap and for a valid TSN. We can simply check if the current * SSN is smaller then the next expected one. If it is, it wrapped * and is invalid. */ ssn = ntohs(data_hdr->ssn); if (ordered && SSN_lt(ssn, sctp_ssn_peek(&asoc->ssnmap->in, sid))) { return SCTP_IERROR_PROTO_VIOLATION; } /* Send the data up to the user. Note: Schedule the * SCTP_CMD_CHUNK_ULP cmd before the SCTP_CMD_GEN_SACK, as the SACK * chunk needs the updated rwnd. */ sctp_add_cmd_sf(commands, deliver, SCTP_CHUNK(chunk)); return SCTP_IERROR_NO_ERROR; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5483_0
crossvul-cpp_data_bad_351_14
/* * ef-atr.c: Stuff for handling EF(GDO) * * Copyright (C) 2017 Frank Morgner <frankmorgner@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "asn1.h" #include "internal.h" #include <stdlib.h> #include <string.h> static int sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len, unsigned char *iccsn, size_t *iccsn_len, unsigned char *chn, size_t *chn_len) { int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0; const unsigned char *p = gdo; size_t left = gdo_len; while (left >= 2) { unsigned int cla, tag; size_t tag_len; r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len); if (r != SC_SUCCESS) { if (r == SC_ERROR_ASN1_END_OF_CONTENTS) { /* not enough data */ r = SC_SUCCESS; } break; } if (p == NULL) { /* done parsing */ break; } if (cla == SC_ASN1_TAG_APPLICATION) { switch (tag) { case 0x1A: iccsn_found = 1; if (iccsn && iccsn_len) { memcpy(iccsn, p, MIN(tag_len, *iccsn_len)); *iccsn_len = MIN(tag_len, *iccsn_len); } break; case 0x1F20: chn_found = 1; if (chn && chn_len) { memcpy(chn, p, MIN(tag_len, *chn_len)); *chn_len = MIN(tag_len, *chn_len); } break; } } p += tag_len; left -= (p - gdo); } if (!iccsn_found && iccsn_len) *iccsn_len = 0; if (!chn_found && chn_len) *chn_len = 0; return r; } int sc_parse_ef_gdo(struct sc_card *card, unsigned char *iccsn, size_t *iccsn_len, unsigned char *chn, size_t *chn_len) { struct sc_context *ctx; struct sc_path path; struct sc_file *file; unsigned char *gdo = NULL; size_t gdo_len = 0; int r; if (!card) return SC_ERROR_INVALID_ARGUMENTS; ctx = card->ctx; LOG_FUNC_CALLED(ctx); sc_format_path("3F002F02", &path); r = sc_select_file(card, &path, &file); LOG_TEST_GOTO_ERR(ctx, r, "Cannot select EF(GDO) file"); if (file->size) { gdo_len = file->size; } else { gdo_len = 64; } gdo = malloc(gdo_len); if (!gdo) { r = SC_ERROR_OUT_OF_MEMORY; goto err; } r = sc_read_binary(card, 0, gdo, gdo_len, 0); LOG_TEST_GOTO_ERR(ctx, r, "Cannot read EF(GDO) file"); r = sc_parse_ef_gdo_content(gdo, r, iccsn, iccsn_len, chn, chn_len); err: sc_file_free(file); free(gdo); LOG_FUNC_RETURN(ctx, r); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_14
crossvul-cpp_data_bad_3396_1
/* Copyright (c) 2014. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdlib.h> #include <ctype.h> #include <yara/globals.h> #include <yara/limits.h> #include <yara/utils.h> #include <yara/re.h> #include <yara/types.h> #include <yara/error.h> #include <yara/libyara.h> #include <yara/scan.h> typedef struct _CALLBACK_ARGS { YR_STRING* string; YR_SCAN_CONTEXT* context; uint8_t* data; size_t data_size; size_t data_base; int forward_matches; int full_word; } CALLBACK_ARGS; int _yr_scan_compare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length) return 0; while (i < string_length && *s1++ == *s2++) i++; return (int) ((i == string_length) ? i : 0); } int _yr_scan_icompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length) return 0; while (i < string_length && yr_lowercase[*s1++] == yr_lowercase[*s2++]) i++; return (int) ((i == string_length) ? i : 0); } int _yr_scan_wcompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length * 2) return 0; while (i < string_length && *s1 == *s2) { s1+=2; s2++; i++; } return (int) ((i == string_length) ? i * 2 : 0); } int _yr_scan_wicompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length * 2) return 0; while (i < string_length && yr_lowercase[*s1] == yr_lowercase[*s2]) { s1+=2; s2++; i++; } return (int) ((i == string_length) ? i * 2 : 0); } void _yr_scan_update_match_chain_length( int tidx, YR_STRING* string, YR_MATCH* match_to_update, int chain_length) { YR_MATCH* match; if (match_to_update->chain_length == chain_length) return; match_to_update->chain_length = chain_length; if (string->chained_to == NULL) return; match = string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { int64_t ending_offset = match->offset + match->match_length; if (ending_offset + string->chain_gap_max >= match_to_update->offset && ending_offset + string->chain_gap_min <= match_to_update->offset) { _yr_scan_update_match_chain_length( tidx, string->chained_to, match, chain_length + 1); } match = match->next; } } int _yr_scan_add_match_to_list( YR_MATCH* match, YR_MATCHES* matches_list, int replace_if_exists) { YR_MATCH* insertion_point = matches_list->tail; if (matches_list->count == MAX_STRING_MATCHES) return ERROR_TOO_MANY_MATCHES; while (insertion_point != NULL) { if (match->offset == insertion_point->offset) { if (replace_if_exists) { insertion_point->match_length = match->match_length; insertion_point->data_length = match->data_length; insertion_point->data = match->data; } return ERROR_SUCCESS; } if (match->offset > insertion_point->offset) break; insertion_point = insertion_point->prev; } match->prev = insertion_point; if (insertion_point != NULL) { match->next = insertion_point->next; insertion_point->next = match; } else { match->next = matches_list->head; matches_list->head = match; } matches_list->count++; if (match->next != NULL) match->next->prev = match; else matches_list->tail = match; return ERROR_SUCCESS; } void _yr_scan_remove_match_from_list( YR_MATCH* match, YR_MATCHES* matches_list) { if (match->prev != NULL) match->prev->next = match->next; if (match->next != NULL) match->next->prev = match->prev; if (matches_list->head == match) matches_list->head = match->next; if (matches_list->tail == match) matches_list->tail = match->prev; matches_list->count--; match->next = NULL; match->prev = NULL; } int _yr_scan_verify_chained_string_match( YR_STRING* matching_string, YR_SCAN_CONTEXT* context, uint8_t* match_data, uint64_t match_base, uint64_t match_offset, int32_t match_length) { YR_STRING* string; YR_MATCH* match; YR_MATCH* next_match; YR_MATCH* new_match; uint64_t lower_offset; uint64_t ending_offset; int32_t full_chain_length; int tidx = context->tidx; int add_match = FALSE; if (matching_string->chained_to == NULL) { add_match = TRUE; } else { if (matching_string->unconfirmed_matches[tidx].head != NULL) lower_offset = matching_string->unconfirmed_matches[tidx].head->offset; else lower_offset = match_offset; match = matching_string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { next_match = match->next; ending_offset = match->offset + match->match_length; if (ending_offset + matching_string->chain_gap_max < lower_offset) { _yr_scan_remove_match_from_list( match, &matching_string->chained_to->unconfirmed_matches[tidx]); } else { if (ending_offset + matching_string->chain_gap_max >= match_offset && ending_offset + matching_string->chain_gap_min <= match_offset) { add_match = TRUE; break; } } match = next_match; } } if (add_match) { if (STRING_IS_CHAIN_TAIL(matching_string)) { // Chain tails must be chained to some other string assert(matching_string->chained_to != NULL); match = matching_string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { ending_offset = match->offset + match->match_length; if (ending_offset + matching_string->chain_gap_max >= match_offset && ending_offset + matching_string->chain_gap_min <= match_offset) { _yr_scan_update_match_chain_length( tidx, matching_string->chained_to, match, 1); } match = match->next; } full_chain_length = 0; string = matching_string; while(string->chained_to != NULL) { full_chain_length++; string = string->chained_to; } // "string" points now to the head of the strings chain match = string->unconfirmed_matches[tidx].head; while (match != NULL) { next_match = match->next; if (match->chain_length == full_chain_length) { _yr_scan_remove_match_from_list( match, &string->unconfirmed_matches[tidx]); match->match_length = (int32_t) \ (match_offset - match->offset + match_length); match->data_length = yr_min(match->match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( context->matches_arena, match_data - match_offset + match->offset, match->data_length, (void**) &match->data)); FAIL_ON_ERROR(_yr_scan_add_match_to_list( match, &string->matches[tidx], FALSE)); } match = next_match; } } else { if (matching_string->matches[tidx].count == 0 && matching_string->unconfirmed_matches[tidx].count == 0) { // If this is the first match for the string, put the string in the // list of strings whose flags needs to be cleared after the scan. FAIL_ON_ERROR(yr_arena_write_data( context->matching_strings_arena, &matching_string, sizeof(matching_string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); new_match->base = match_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->chain_length = 0; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &matching_string->unconfirmed_matches[tidx], FALSE)); } } return ERROR_SUCCESS; } int _yr_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; // total match length is the sum of backward and forward matches. match_length += callback_args->forward_matches; if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { // If this is the first match for the string, put the string in the // list of strings whose flags needs to be cleared after the scan. FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; } typedef int (*RE_EXEC_FUNC)( uint8_t* code, uint8_t* input, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args, int* matches); int _yr_scan_verify_re_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { CALLBACK_ARGS callback_args; RE_EXEC_FUNC exec; int forward_matches = -1; int backward_matches = -1; int flags = 0; if (STRING_IS_GREEDY_REGEXP(ac_match->string)) flags |= RE_FLAGS_GREEDY; if (STRING_IS_NO_CASE(ac_match->string)) flags |= RE_FLAGS_NO_CASE; if (STRING_IS_DOT_ALL(ac_match->string)) flags |= RE_FLAGS_DOT_ALL; if (STRING_IS_FAST_REGEXP(ac_match->string)) exec = yr_re_fast_exec; else exec = yr_re_exec; if (STRING_IS_ASCII(ac_match->string)) { FAIL_ON_ERROR(exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL, &forward_matches)); } if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1) { flags |= RE_FLAGS_WIDE; FAIL_ON_ERROR(exec( ac_match->forward_code, data + offset, data_size - offset, offset, flags, NULL, NULL, &forward_matches)); } if (forward_matches == -1) return ERROR_SUCCESS; if (forward_matches == 0 && ac_match->backward_code == NULL) return ERROR_SUCCESS; callback_args.string = ac_match->string; callback_args.context = context; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string); if (ac_match->backward_code != NULL) { FAIL_ON_ERROR(exec( ac_match->backward_code, data + offset, data_size - offset, offset, flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE, _yr_scan_match_callback, (void*) &callback_args, &backward_matches)); } else { FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); } return ERROR_SUCCESS; } int _yr_scan_verify_literal_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { int flags = 0; int forward_matches = 0; CALLBACK_ARGS callback_args; YR_STRING* string = ac_match->string; if (STRING_FITS_IN_ATOM(string)) { forward_matches = ac_match->backtrack; } else if (STRING_IS_NO_CASE(string)) { if (STRING_IS_ASCII(string)) { forward_matches = _yr_scan_icompare( data + offset, data_size - offset, string->string, string->length); } if (STRING_IS_WIDE(string) && forward_matches == 0) { forward_matches = _yr_scan_wicompare( data + offset, data_size - offset, string->string, string->length); } } else { if (STRING_IS_ASCII(string)) { forward_matches = _yr_scan_compare( data + offset, data_size - offset, string->string, string->length); } if (STRING_IS_WIDE(string) && forward_matches == 0) { forward_matches = _yr_scan_wcompare( data + offset, data_size - offset, string->string, string->length); } } if (forward_matches == 0) return ERROR_SUCCESS; if (forward_matches == string->length * 2) flags |= RE_FLAGS_WIDE; if (STRING_IS_NO_CASE(string)) flags |= RE_FLAGS_NO_CASE; callback_args.context = context; callback_args.string = string; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(string); FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); return ERROR_SUCCESS; } int yr_scan_verify_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { YR_STRING* string = ac_match->string; #ifdef PROFILING_ENABLED clock_t start = clock(); #endif if (data_size - offset <= 0) return ERROR_SUCCESS; if (context->flags & SCAN_FLAGS_FAST_MODE && STRING_IS_SINGLE_MATCH(string) && string->matches[context->tidx].head != NULL) return ERROR_SUCCESS; if (STRING_IS_FIXED_OFFSET(string) && string->fixed_offset != data_base + offset) return ERROR_SUCCESS; if (STRING_IS_LITERAL(string)) { FAIL_ON_ERROR(_yr_scan_verify_literal_match( context, ac_match, data, data_size, data_base, offset)); } else { FAIL_ON_ERROR(_yr_scan_verify_re_match( context, ac_match, data, data_size, data_base, offset)); } #ifdef PROFILING_ENABLED string->clock_ticks += clock() - start; #endif return ERROR_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3396_1
crossvul-cpp_data_good_2749_0
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Authentication Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep2, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); ND_TCHECK_16BITS(&p[2]); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else { if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4)); if (ntohs(e.len) > 4) { if (ndo->ndo_vflag > 2) { ND_PRINT((ndo, " ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " ")); if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep)) goto trunc; } } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, ep2); if (cp == NULL) goto trunc; } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*k); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_id *idp; struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; idp = (const struct ikev2_id *)ext; ND_TCHECK(*idp); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK2(*ext, sizeof(a)); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if (cp < ep) { if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if (showsomedata) { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { ND_TCHECK(bp[0]); if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } ND_TCHECK(bp[3]); /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2749_0
crossvul-cpp_data_good_3190_2
/* etterfilter -- the actual compiler Copyright (C) ALoR & NaGA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ef.h> #include <ef_functions.h> #include <ec_filter.h> #include <ec_version.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> /* protos */ static void print_progress_bar(struct filter_op *fop); static u_char * create_data_segment(struct filter_header *fh, struct filter_op *fop, size_t n); static size_t add_data_segment(u_char **data, size_t base, u_char **string, size_t slen); /*******************************************/ int write_output(void) { int fd; struct filter_op *fop; struct filter_header fh; size_t ninst, i; u_char *data; /* conver the tree to an array of filter_op */ ninst = compile_tree(&fop); if (fop == NULL) return -E_NOTHANDLED; if (ninst == 0) return -E_INVALID; /* create the file */ fd = open(EF_GBL_OPTIONS->output_file, O_CREAT | O_RDWR | O_TRUNC | O_BINARY, 0644); ON_ERROR(fd, -1, "Can't create file %s", EF_GBL_OPTIONS->output_file); /* display the message */ fprintf(stdout, " Writing output to \'%s\' ", EF_GBL_OPTIONS->output_file); fflush(stdout); /* compute the header */ fh.magic = htons(EC_FILTER_MAGIC); strncpy(fh.version, EC_VERSION, sizeof(fh.version)); fh.data = sizeof(fh); data = create_data_segment(&fh, fop, ninst); /* write the header */ write(fd, &fh, sizeof(struct filter_header)); /* write the data segment */ write(fd, data, fh.code - fh.data); /* write the instructions */ for (i = 0; i <= ninst; i++) { print_progress_bar(&fop[i]); write(fd, &fop[i], sizeof(struct filter_op)); } close(fd); fprintf(stdout, " done.\n\n"); fprintf(stdout, " -> Script encoded into %d instructions.\n\n", (int)(i - 1)); return E_SUCCESS; } /* * creates the data segment into an array * and update the file header */ static u_char * create_data_segment(struct filter_header *fh, struct filter_op *fop, size_t n) { size_t i, len = 0; u_char *data = NULL; for (i = 0; i < n; i++) { switch(fop[i].opcode) { case FOP_FUNC: if (fop[i].op.func.slen) { ef_debug(1, "@"); len += add_data_segment(&data, len, &fop[i].op.func.string, fop[i].op.func.slen); } if (fop[i].op.func.rlen) { ef_debug(1, "@"); len += add_data_segment(&data, len, &fop[i].op.func.replace, fop[i].op.func.rlen); } break; case FOP_TEST: if (fop[i].op.test.slen) { ef_debug(1, "@"); len += add_data_segment(&data, len, &fop[i].op.test.string, fop[i].op.test.slen); } break; case FOP_ASSIGN: if (fop[i].op.assign.slen) { ef_debug(1, "@"); len += add_data_segment(&data, len, &fop[i].op.test.string, fop[i].op.test.slen); } break; } } /* where starts the code ? */ fh->code = fh->data + len; return data; } /* * add a string to the buffer */ static size_t add_data_segment(u_char **data, size_t base, u_char **string, size_t slen) { /* make room for the new string */ SAFE_REALLOC(*data, base + slen + 1); /* copy the string, NULL separated */ memcpy(*data + base, *string, slen + 1); /* * change the pointer to the new string location * it is an offset from the base of the data segment */ *string = (u_char *)base; /* retur the len of the added string */ return slen + 1; } /* * prints a differnt sign for every different instruction */ static void print_progress_bar(struct filter_op *fop) { switch(fop->opcode) { case FOP_EXIT: ef_debug(1, "!"); break; case FOP_TEST: ef_debug(1, "?"); break; case FOP_ASSIGN: ef_debug(1, "="); break; case FOP_FUNC: ef_debug(1, "."); break; case FOP_JMP: ef_debug(1, ":"); break; case FOP_JTRUE: case FOP_JFALSE: ef_debug(1, ";"); break; } } /* EOF */ // vim:ts=3:expandtab
./CrossVul/dataset_final_sorted/CWE-125/c/good_3190_2
crossvul-cpp_data_bad_3328_0
/* Copyright (c) 2013-2014. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define _GNU_SOURCE #include <string.h> #include <assert.h> #include <time.h> #include <math.h> #include <yara/endian.h> #include <yara/exec.h> #include <yara/limits.h> #include <yara/error.h> #include <yara/object.h> #include <yara/modules.h> #include <yara/re.h> #include <yara/strutils.h> #include <yara/utils.h> #include <yara/mem.h> #include <yara.h> #define MEM_SIZE MAX_LOOP_NESTING * LOOP_LOCAL_VARS #define push(x) \ if (sp < stack_size) \ { \ stack[sp++] = (x); \ } \ else \ { \ result = ERROR_EXEC_STACK_OVERFLOW; \ stop = TRUE; \ break; \ } \ #define pop(x) x = stack[--sp] #define is_undef(x) IS_UNDEFINED((x).i) #define ensure_defined(x) \ if (is_undef(x)) \ { \ r1.i = UNDEFINED; \ push(r1); \ break; \ } #define little_endian_uint8_t(x) (x) #define little_endian_int8_t(x) (x) #define little_endian_uint16_t(x) yr_le16toh(x) #define little_endian_int16_t(x) yr_le16toh(x) #define little_endian_uint32_t(x) yr_le32toh(x) #define little_endian_int32_t(x) yr_le32toh(x) #define big_endian_uint8_t(x) (x) #define big_endian_int8_t(x) (x) #define big_endian_uint16_t(x) yr_be16toh(x) #define big_endian_int16_t(x) yr_be16toh(x) #define big_endian_uint32_t(x) yr_be32toh(x) #define big_endian_int32_t(x) yr_be32toh(x) #define function_read(type, endianess) \ int64_t read_##type##_##endianess(YR_MEMORY_BLOCK_ITERATOR* iterator, size_t offset) \ { \ YR_MEMORY_BLOCK* block = iterator->first(iterator); \ while (block != NULL) \ { \ if (offset >= block->base && \ block->size >= sizeof(type) && \ offset <= block->base + block->size - sizeof(type)) \ { \ type result; \ uint8_t* data = block->fetch_data(block); \ if (data == NULL) \ return UNDEFINED; \ result = *(type *)(data + offset - block->base); \ result = endianess##_##type(result); \ return result; \ } \ block = iterator->next(iterator); \ } \ return UNDEFINED; \ }; function_read(uint8_t, little_endian) function_read(uint16_t, little_endian) function_read(uint32_t, little_endian) function_read(int8_t, little_endian) function_read(int16_t, little_endian) function_read(int32_t, little_endian) function_read(uint8_t, big_endian) function_read(uint16_t, big_endian) function_read(uint32_t, big_endian) function_read(int8_t, big_endian) function_read(int16_t, big_endian) function_read(int32_t, big_endian) static uint8_t* jmp_if( int condition, uint8_t* ip) { uint8_t* result; if (condition) { result = *(uint8_t**)(ip + 1); // ip will be incremented at the end of the execution loop, // decrement it here to compensate. result--; } else { result = ip + sizeof(uint64_t); } return result; } int yr_execute_code( YR_RULES* rules, YR_SCAN_CONTEXT* context, int timeout, time_t start_time) { int64_t mem[MEM_SIZE]; int32_t sp = 0; uint8_t* ip = rules->code_start; YR_VALUE args[MAX_FUNCTION_ARGS]; YR_VALUE *stack; YR_VALUE r1; YR_VALUE r2; YR_VALUE r3; #ifdef PROFILING_ENABLED YR_RULE* current_rule = NULL; #endif YR_RULE* rule; YR_MATCH* match; YR_OBJECT_FUNCTION* function; char* identifier; char* args_fmt; int i; int found; int count; int result = ERROR_SUCCESS; int stop = FALSE; int cycle = 0; int tidx = context->tidx; int stack_size; #ifdef PROFILING_ENABLED clock_t start = clock(); #endif yr_get_configuration(YR_CONFIG_STACK_SIZE, (void*) &stack_size); stack = (YR_VALUE*) yr_malloc(stack_size * sizeof(YR_VALUE)); if (stack == NULL) return ERROR_INSUFFICIENT_MEMORY; while(!stop) { switch(*ip) { case OP_HALT: assert(sp == 0); // When HALT is reached the stack should be empty. stop = TRUE; break; case OP_PUSH: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); push(r1); break; case OP_POP: pop(r1); break; case OP_CLEAR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i] = 0; break; case OP_ADD_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (!is_undef(r2)) mem[r1.i] += r2.i; break; case OP_INCR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i]++; break; case OP_PUSH_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r1.i = mem[r1.i]; push(r1); break; case OP_POP_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); mem[r1.i] = r2.i; break; case OP_SWAPUNDEF: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (is_undef(r2)) { r1.i = mem[r1.i]; push(r1); } else { push(r2); } break; case OP_JNUNDEF: pop(r1); push(r1); ip = jmp_if(!is_undef(r1), ip); break; case OP_JLE: pop(r2); pop(r1); push(r1); push(r2); ip = jmp_if(r1.i <= r2.i, ip); break; case OP_JTRUE: pop(r1); push(r1); ip = jmp_if(!is_undef(r1) && r1.i, ip); break; case OP_JFALSE: pop(r1); push(r1); ip = jmp_if(is_undef(r1) || !r1.i, ip); break; case OP_AND: pop(r2); pop(r1); if (is_undef(r1) || is_undef(r2)) r1.i = 0; else r1.i = r1.i && r2.i; push(r1); break; case OP_OR: pop(r2); pop(r1); if (is_undef(r1)) { push(r2); } else if (is_undef(r2)) { push(r1); } else { r1.i = r1.i || r2.i; push(r1); } break; case OP_NOT: pop(r1); if (is_undef(r1)) r1.i = UNDEFINED; else r1.i= !r1.i; push(r1); break; case OP_MOD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i % r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_SHR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >> r2.i; push(r1); break; case OP_SHL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i << r2.i; push(r1); break; case OP_BITWISE_NOT: pop(r1); ensure_defined(r1); r1.i = ~r1.i; push(r1); break; case OP_BITWISE_AND: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i & r2.i; push(r1); break; case OP_BITWISE_OR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i | r2.i; push(r1); break; case OP_BITWISE_XOR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i ^ r2.i; push(r1); break; case OP_PUSH_RULE: rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); r1.i = rule->t_flags[tidx] & RULE_TFLAGS_MATCH ? 1 : 0; push(r1); break; case OP_INIT_RULE: #ifdef PROFILING_ENABLED current_rule = *(YR_RULE**)(ip + 1); #endif ip += sizeof(uint64_t); break; case OP_MATCH_RULE: pop(r1); rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); if (!is_undef(r1) && r1.i) rule->t_flags[tidx] |= RULE_TFLAGS_MATCH; else if (RULE_IS_GLOBAL(rule)) rule->ns->t_flags[tidx] |= NAMESPACE_TFLAGS_UNSATISFIED_GLOBAL; #ifdef PROFILING_ENABLED rule->clock_ticks += clock() - start; start = clock(); #endif break; case OP_OBJ_LOAD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); r1.o = (YR_OBJECT*) yr_hash_table_lookup( context->objects_table, identifier, NULL); assert(r1.o != NULL); push(r1); break; case OP_OBJ_FIELD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); pop(r1); ensure_defined(r1); r1.o = yr_object_lookup_field(r1.o, identifier); assert(r1.o != NULL); push(r1); break; case OP_OBJ_VALUE: pop(r1); ensure_defined(r1); switch(r1.o->type) { case OBJECT_TYPE_INTEGER: r1.i = ((YR_OBJECT_INTEGER*) r1.o)->value; break; case OBJECT_TYPE_FLOAT: if (isnan(((YR_OBJECT_DOUBLE*) r1.o)->value)) r1.i = UNDEFINED; else r1.d = ((YR_OBJECT_DOUBLE*) r1.o)->value; break; case OBJECT_TYPE_STRING: if (((YR_OBJECT_STRING*) r1.o)->value == NULL) r1.i = UNDEFINED; else r1.p = ((YR_OBJECT_STRING*) r1.o)->value; break; default: assert(FALSE); } push(r1); break; case OP_INDEX_ARRAY: pop(r1); // index pop(r2); // array ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_ARRAY); r1.o = yr_object_array_get_item(r2.o, 0, (int) r1.i); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_LOOKUP_DICT: pop(r1); // key pop(r2); // dictionary ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_DICTIONARY); r1.o = yr_object_dict_get_item( r2.o, 0, r1.ss->c_string); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_CALL: args_fmt = *(char**)(ip + 1); ip += sizeof(uint64_t); i = (int) strlen(args_fmt); count = 0; // pop arguments from stack and copy them to args array while (i > 0) { pop(r1); if (is_undef(r1)) // count the number of undefined args count++; args[i - 1] = r1; i--; } pop(r2); ensure_defined(r2); if (count > 0) { // if there are undefined args, result for function call // is undefined as well. r1.i = UNDEFINED; push(r1); break; } function = (YR_OBJECT_FUNCTION*) r2.o; result = ERROR_INTERNAL_FATAL_ERROR; for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) { if (function->prototypes[i].arguments_fmt == NULL) break; if (strcmp(function->prototypes[i].arguments_fmt, args_fmt) == 0) { result = function->prototypes[i].code(args, context, function); break; } } assert(i < MAX_OVERLOADED_FUNCTIONS); if (result == ERROR_SUCCESS) { r1.o = function->return_obj; push(r1); } else { stop = TRUE; } break; case OP_FOUND: pop(r1); r1.i = r1.s->matches[tidx].tail != NULL ? 1 : 0; push(r1); break; case OP_FOUND_AT: pop(r2); pop(r1); if (is_undef(r1)) { r1.i = 0; push(r1); break; } match = r2.s->matches[tidx].head; r3.i = FALSE; while (match != NULL) { if (r1.i == match->base + match->offset) { r3.i = TRUE; break; } if (r1.i < match->base + match->offset) break; match = match->next; } push(r3); break; case OP_FOUND_IN: pop(r3); pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); match = r3.s->matches[tidx].head; r3.i = FALSE; while (match != NULL && !r3.i) { if (match->base + match->offset >= r1.i && match->base + match->offset <= r2.i) { r3.i = TRUE; } if (match->base + match->offset > r2.i) break; match = match->next; } push(r3); break; case OP_COUNT: pop(r1); r1.i = r1.s->matches[tidx].count; push(r1); break; case OP_OFFSET: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->base + match->offset; i++; match = match->next; } push(r3); break; case OP_LENGTH: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->match_length; i++; match = match->next; } push(r3); break; case OP_OF: found = 0; count = 0; pop(r1); while (!is_undef(r1)) { if (r1.s->matches[tidx].tail != NULL) found++; count++; pop(r1); } pop(r2); if (is_undef(r2)) r1.i = found >= count ? 1 : 0; else r1.i = found >= r2.i ? 1 : 0; push(r1); break; case OP_FILESIZE: r1.i = context->file_size; push(r1); break; case OP_ENTRYPOINT: r1.i = context->entry_point; push(r1); break; case OP_INT8: pop(r1); r1.i = read_int8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16: pop(r1); r1.i = read_int16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32: pop(r1); r1.i = read_int32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8: pop(r1); r1.i = read_uint8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16: pop(r1); r1.i = read_uint16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32: pop(r1); r1.i = read_uint32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT8BE: pop(r1); r1.i = read_int8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16BE: pop(r1); r1.i = read_int16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32BE: pop(r1); r1.i = read_int32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8BE: pop(r1); r1.i = read_uint8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16BE: pop(r1); r1.i = read_uint16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32BE: pop(r1); r1.i = read_uint32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_CONTAINS: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); r1.i = memmem(r1.ss->c_string, r1.ss->length, r2.ss->c_string, r2.ss->length) != NULL; push(r1); break; case OP_IMPORT: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); result = yr_modules_load((char*) r1.p, context); if (result != ERROR_SUCCESS) stop = TRUE; break; case OP_MATCHES: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r1.ss->length == 0) { r1.i = FALSE; push(r1); break; } r1.i = yr_re_exec( (uint8_t*) r2.re->code, (uint8_t*) r1.ss->c_string, r1.ss->length, r2.re->flags | RE_FLAGS_SCAN, NULL, NULL) >= 0; push(r1); break; case OP_INT_TO_DBL: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r2 = stack[sp - r1.i]; if (is_undef(r2)) stack[sp - r1.i].i = UNDEFINED; else stack[sp - r1.i].d = (double) r2.i; break; case OP_STR_TO_BOOL: pop(r1); ensure_defined(r1); r1.i = r1.ss->length > 0; push(r1); break; case OP_INT_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i == r2.i; push(r1); break; case OP_INT_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i != r2.i; push(r1); break; case OP_INT_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i < r2.i; push(r1); break; case OP_INT_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i > r2.i; push(r1); break; case OP_INT_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i <= r2.i; push(r1); break; case OP_INT_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >= r2.i; push(r1); break; case OP_INT_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i + r2.i; push(r1); break; case OP_INT_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i - r2.i; push(r1); break; case OP_INT_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i * r2.i; push(r1); break; case OP_INT_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i / r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_INT_MINUS: pop(r1); ensure_defined(r1); r1.i = -r1.i; push(r1); break; case OP_DBL_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d < r2.d; push(r1); break; case OP_DBL_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d > r2.d; push(r1); break; case OP_DBL_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d <= r2.d; push(r1); break; case OP_DBL_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d >= r2.d; push(r1); break; case OP_DBL_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d == r2.d; push(r1); break; case OP_DBL_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d != r2.d; push(r1); break; case OP_DBL_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d + r2.d; push(r1); break; case OP_DBL_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d - r2.d; push(r1); break; case OP_DBL_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d * r2.d; push(r1); break; case OP_DBL_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d / r2.d; push(r1); break; case OP_DBL_MINUS: pop(r1); ensure_defined(r1); r1.d = -r1.d; push(r1); break; case OP_STR_EQ: case OP_STR_NEQ: case OP_STR_LT: case OP_STR_LE: case OP_STR_GT: case OP_STR_GE: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); switch(*ip) { case OP_STR_EQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) == 0); break; case OP_STR_NEQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) != 0); break; case OP_STR_LT: r1.i = (sized_string_cmp(r1.ss, r2.ss) < 0); break; case OP_STR_LE: r1.i = (sized_string_cmp(r1.ss, r2.ss) <= 0); break; case OP_STR_GT: r1.i = (sized_string_cmp(r1.ss, r2.ss) > 0); break; case OP_STR_GE: r1.i = (sized_string_cmp(r1.ss, r2.ss) >= 0); break; } push(r1); break; default: // Unknown instruction, this shouldn't happen. assert(FALSE); } if (timeout > 0) // timeout == 0 means no timeout { // Check for timeout every 10 instruction cycles. if (++cycle == 10) { if (difftime(time(NULL), start_time) > timeout) { #ifdef PROFILING_ENABLED assert(current_rule != NULL); current_rule->clock_ticks += clock() - start; #endif result = ERROR_SCAN_TIMEOUT; stop = TRUE; } cycle = 0; } } ip++; } yr_modules_unload_all(context); yr_free(stack); return result; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3328_0
crossvul-cpp_data_bad_2667_0
/* * Copyright (C) 1999 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 /* draft-ietf-idr-shutdown-07 */ #define BGP_NOTIFY_MINOR_CEASE_SHUT 2 #define BGP_NOTIFY_MINOR_CEASE_RESET 4 #define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"}, { 3, "Peer Unconfigured"}, { BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 0, "Unspecified Error"}, { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (0 == plen) { snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; plen-=32; /* adjust prefix length */ if (64 < plen) return -1; memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[1], (plen + 7) / 8); memcpy(&route_target, &pptr[1], (plen + 7) / 8); if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, { 0, NULL} }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_TCHECK2(tptr[0], 5); ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; ND_TCHECK2(tptr[0], 3); tlen = len; while (tlen >= 3) { type = *tptr; length = EXTRACT_16BITS(tptr+1); ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length - 3); switch (type) { case BGP_AIGP_TLV: ND_TCHECK2(tptr[3], 8); ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr+3))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr+3,"\n\t ", length-3); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; uint8_t shutdown_comm_length; uint8_t remainder_offset; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } /* * draft-ietf-idr-shutdown describes a method to send a communication * intended for human consumption regarding the Administrative Shutdown */ if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT || bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) && length >= BGP_NOTIFICATION_SIZE + 1) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 1); shutdown_comm_length = *(tptr); remainder_offset = 0; /* garbage, hexdump it all */ if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN || shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) { ND_PRINT((ndo, ", invalid Shutdown Communication length")); } else if (shutdown_comm_length == 0) { ND_PRINT((ndo, ", empty Shutdown Communication")); remainder_offset += 1; } /* a proper shutdown communication */ else { ND_TCHECK2(*(tptr+1), shutdown_comm_length); ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length)); (void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL); ND_PRINT((ndo, "\"")); remainder_offset += shutdown_comm_length + 1; } /* if there is trailing data, hexdump it */ if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) { ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE))); hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE)); } } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2667_0
crossvul-cpp_data_bad_163_1
/* * This file is part of Espruino, a JavaScript interpreter for Microcontrollers * * Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * ---------------------------------------------------------------------------- * Recursive descent parser for code execution * ---------------------------------------------------------------------------- */ #include "jsparse.h" #include "jsinteractive.h" #include "jswrapper.h" #include "jsnative.h" #include "jswrap_object.h" // for function_replacewith #include "jswrap_functions.h" // insane check for eval in jspeFunctionCall #include "jswrap_json.h" // for jsfPrintJSON #include "jswrap_espruino.h" // for jswrap_espruino_memoryArea #ifndef SAVE_ON_FLASH #include "jswrap_regexp.h" // for jswrap_regexp_constructor #endif /* Info about execution when Parsing - this saves passing it on the stack * for each call */ JsExecInfo execInfo; // ----------------------------------------------- Forward decls JsVar *jspeAssignmentExpression(); JsVar *jspeExpression(); JsVar *jspeUnaryExpression(); void jspeBlock(); void jspeBlockNoBrackets(); JsVar *jspeStatement(); JsVar *jspeFactor(); void jspEnsureIsPrototype(JsVar *instanceOf, JsVar *prototypeName); #ifndef SAVE_ON_FLASH JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a); #endif // ----------------------------------------------- Utils #define JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, CLEANUP_CODE, RETURN_VAL) { if (!jslMatch((TOKEN))) { CLEANUP_CODE; return RETURN_VAL; } } #define JSP_MATCH_WITH_RETURN(TOKEN, RETURN_VAL) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , RETURN_VAL) #define JSP_MATCH(TOKEN) JSP_MATCH_WITH_CLEANUP_AND_RETURN(TOKEN, , 0) // Match where the user could have given us the wrong token #define JSP_ASSERT_MATCH(TOKEN) { assert(lex->tk==(TOKEN));jslGetNextToken(); } // Match where if we have the wrong token, it's an internal error #define JSP_SHOULD_EXECUTE (((execInfo.execute)&EXEC_RUN_MASK)==EXEC_YES) #define JSP_SAVE_EXECUTE() JsExecFlags oldExecute = execInfo.execute #define JSP_RESTORE_EXECUTE() execInfo.execute = (execInfo.execute&(JsExecFlags)(~EXEC_SAVE_RESTORE_MASK)) | (oldExecute&EXEC_SAVE_RESTORE_MASK); #define JSP_HAS_ERROR (((execInfo.execute)&EXEC_ERROR_MASK)!=0) #define JSP_SHOULDNT_PARSE (((execInfo.execute)&EXEC_NO_PARSE_MASK)!=0) ALWAYS_INLINE void jspDebuggerLoopIfCtrlC() { #ifdef USE_DEBUGGER if (execInfo.execute & EXEC_CTRL_C_WAIT && JSP_SHOULD_EXECUTE) jsiDebuggerLoop(); #endif } /// if interrupting execution, this is set bool jspIsInterrupted() { return (execInfo.execute & EXEC_INTERRUPTED)!=0; } /// if interrupting execution, this is set void jspSetInterrupted(bool interrupt) { if (interrupt) execInfo.execute = execInfo.execute | EXEC_INTERRUPTED; else execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_INTERRUPTED; } /// Set the error flag - set lineReported if we've already output the line number void jspSetError(bool lineReported) { execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_YES) | EXEC_ERROR; if (lineReported) execInfo.execute |= EXEC_ERROR_LINE_REPORTED; } bool jspHasError() { return JSP_HAS_ERROR; } void jspReplaceWith(JsVar *dst, JsVar *src) { // If this is an index in an array buffer, write directly into the array buffer if (jsvIsArrayBufferName(dst)) { size_t idx = (size_t)jsvGetInteger(dst); JsVar *arrayBuffer = jsvLock(jsvGetFirstChild(dst)); jsvArrayBufferSet(arrayBuffer, idx, src); jsvUnLock(arrayBuffer); return; } // if destination isn't there, isn't a 'name', or is used, give an error if (!jsvIsName(dst)) { jsExceptionHere(JSET_ERROR, "Unable to assign value to non-reference %t", dst); return; } jsvSetValueOfName(dst, src); /* If dst is flagged as a new child, it means that * it was previously undefined, and we need to add it to * the given object when it is set. */ if (jsvIsNewChild(dst)) { // Get what it should have been a child of JsVar *parent = jsvLock(jsvGetNextSibling(dst)); if (!jsvIsString(parent)) { // if we can't find a char in a string we still return a NewChild, // but we can't add character back in if (!jsvHasChildren(parent)) { jsExceptionHere(JSET_ERROR, "Field or method \"%s\" does not already exist, and can't create it on %t", dst, parent); } else { // Remove the 'new child' flagging jsvUnRef(parent); jsvSetNextSibling(dst, 0); jsvUnRef(parent); jsvSetPrevSibling(dst, 0); // Add to the parent jsvAddName(parent, dst); } } jsvUnLock(parent); } } bool jspeiAddScope(JsVar *scope) { if (execInfo.scopeCount >= JSPARSE_MAX_SCOPES) { jsExceptionHere(JSET_ERROR, "Maximum number of scopes exceeded"); jspSetError(false); return false; } execInfo.scopes[execInfo.scopeCount++] = jsvLockAgain(scope); return true; } void jspeiRemoveScope() { if (execInfo.scopeCount <= 0) { jsExceptionHere(JSET_INTERNALERROR, "Too many scopes removed"); jspSetError(false); return; } jsvUnLock(execInfo.scopes[--execInfo.scopeCount]); } JsVar *jspeiFindInScopes(const char *name) { int i; for (i=execInfo.scopeCount-1;i>=0;i--) { JsVar *ref = jsvFindChildFromString(execInfo.scopes[i], name, false); if (ref) return ref; } return jsvFindChildFromString(execInfo.root, name, false); } // TODO: get rid of these, use jspeiGetTopScope instead JsVar *jspeiFindOnTop(const char *name, bool createIfNotFound) { if (execInfo.scopeCount>0) return jsvFindChildFromString(execInfo.scopes[execInfo.scopeCount-1], name, createIfNotFound); return jsvFindChildFromString(execInfo.root, name, createIfNotFound); } JsVar *jspeiFindNameOnTop(JsVar *childName, bool createIfNotFound) { if (execInfo.scopeCount>0) return jsvFindChildFromVar(execInfo.scopes[execInfo.scopeCount-1], childName, createIfNotFound); return jsvFindChildFromVar(execInfo.root, childName, createIfNotFound); } /** Here we assume that we have already looked in the parent itself - * and are now going down looking at the stuff it inherited */ JsVar *jspeiFindChildFromStringInParents(JsVar *parent, const char *name) { if (jsvIsObject(parent)) { // If an object, look for an 'inherits' var JsVar *inheritsFrom = jsvObjectGetChild(parent, JSPARSE_INHERITS_VAR, 0); // if there's no inheritsFrom, just default to 'Object.prototype' if (!inheritsFrom) { JsVar *obj = jsvObjectGetChild(execInfo.root, "Object", 0); if (obj) { inheritsFrom = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0); jsvUnLock(obj); } } if (inheritsFrom && inheritsFrom!=parent) { // we have what it inherits from (this is ACTUALLY the prototype var) // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/proto JsVar *child = jsvFindChildFromString(inheritsFrom, name, false); if (!child) child = jspeiFindChildFromStringInParents(inheritsFrom, name); jsvUnLock(inheritsFrom); if (child) return child; } else jsvUnLock(inheritsFrom); } else { // Not actually an object - but might be an array/string/etc const char *objectName = jswGetBasicObjectName(parent); while (objectName) { JsVar *objName = jsvFindChildFromString(execInfo.root, objectName, false); if (objName) { JsVar *result = 0; JsVar *obj = jsvSkipNameAndUnLock(objName); // could be something the user has made - eg. 'Array=1' if (jsvHasChildren(obj)) { // We have found an object with this name - search for the prototype var JsVar *proto = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0); if (proto) { result = jsvFindChildFromString(proto, name, false); jsvUnLock(proto); } } jsvUnLock(obj); if (result) return result; } /* We haven't found anything in the actual object, we should check the 'Object' itself eg, we tried 'String', so now we should try 'Object'. Built-in types don't have room for a prototype field, so we hard-code it */ objectName = jswGetBasicObjectPrototypeName(objectName); } } // no luck! return 0; } JsVar *jspeiGetScopesAsVar() { if (execInfo.scopeCount==0) return 0; if (execInfo.scopeCount==1) return jsvLockAgain(execInfo.scopes[0]); JsVar *arr = jsvNewEmptyArray(); int i; for (i=0;i<execInfo.scopeCount;i++) { JsVar *idx = jsvMakeIntoVariableName(jsvNewFromInteger(i), execInfo.scopes[i]); if (!idx) { // out of memory jspSetError(false); return arr; } jsvAddName(arr, idx); jsvUnLock(idx); } return arr; } void jspeiLoadScopesFromVar(JsVar *arr) { execInfo.scopeCount = 0; if (jsvIsArray(arr)) { JsvObjectIterator it; jsvObjectIteratorNew(&it, arr); while (jsvObjectIteratorHasValue(&it)) { execInfo.scopes[execInfo.scopeCount++] = jsvObjectIteratorGetValue(&it); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); } else execInfo.scopes[execInfo.scopeCount++] = jsvLockAgain(arr); } // ----------------------------------------------- bool jspCheckStackPosition() { if (jsuGetFreeStack() < 512) { // giving us 512 bytes leeway jsExceptionHere(JSET_ERROR, "Too much recursion - the stack is about to overflow"); jspSetInterrupted(true); return false; } return true; } // Set execFlags such that we are not executing void jspSetNoExecute() { execInfo.execute = (execInfo.execute & (JsExecFlags)(int)~EXEC_RUN_MASK) | EXEC_NO; } void jspAppendStackTrace(JsVar *stackTrace) { JsvStringIterator it; jsvStringIteratorNew(&it, stackTrace, 0); jsvStringIteratorGotoEnd(&it); jslPrintPosition((vcbprintf_callback)jsvStringIteratorPrintfCallback, &it, lex->tokenLastStart); jslPrintTokenLineMarker((vcbprintf_callback)jsvStringIteratorPrintfCallback, &it, lex->tokenLastStart, 0); jsvStringIteratorFree(&it); } /// We had an exception (argument is the exception's value) void jspSetException(JsVar *value) { // Add the exception itself to a variable in root scope JsVar *exception = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_EXCEPTION_VAR, true); if (exception) { jsvSetValueOfName(exception, value); jsvUnLock(exception); } // Set the exception flag execInfo.execute = execInfo.execute | EXEC_EXCEPTION; // Try and do a stack trace if (lex) { JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, " at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); // stop us from printing the trace in the same block execInfo.execute = execInfo.execute | EXEC_ERROR_LINE_REPORTED; } } } /** Return the reported exception if there was one (and clear it) */ JsVar *jspGetException() { JsVar *exceptionName = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_EXCEPTION_VAR, false); if (exceptionName) { JsVar *exception = jsvSkipName(exceptionName); jsvRemoveChild(execInfo.hiddenRoot, exceptionName); jsvUnLock(exceptionName); JsVar *stack = jspGetStackTrace(); if (stack && jsvHasChildren(exception)) { jsvObjectSetChild(exception, "stack", stack); } jsvUnLock(stack); return exception; } return 0; } /** Return a stack trace string if there was one (and clear it) */ JsVar *jspGetStackTrace() { JsVar *stackTraceName = jsvFindChildFromString(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, false); if (stackTraceName) { JsVar *stackTrace = jsvSkipName(stackTraceName); jsvRemoveChild(execInfo.hiddenRoot, stackTraceName); jsvUnLock(stackTraceName); return stackTrace; } return 0; } // ---------------------------------------------- // we return a value so that JSP_MATCH can return 0 if it fails (if we pass 0, we just parse all args) NO_INLINE bool jspeFunctionArguments(JsVar *funcVar) { JSP_MATCH('('); while (lex->tk!=')') { if (funcVar) { char buf[JSLEX_MAX_TOKEN_LENGTH+1]; buf[0] = '\xFF'; strcpy(&buf[1], jslGetTokenValueAsString(lex)); JsVar *param = jsvAddNamedChild(funcVar, 0, buf); if (!param) { // out of memory jspSetError(false); return false; } jsvMakeFunctionParameter(param); // force this to be called a function parameter jsvUnLock(param); } JSP_MATCH(LEX_ID); if (lex->tk!=')') JSP_MATCH(','); } JSP_MATCH(')'); return true; } // Parse function, assuming we're on '{'. funcVar can be 0 NO_INLINE bool jspeFunctionDefinitionInternal(JsVar *funcVar, bool expressionOnly) { if (expressionOnly) { if (funcVar) funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN; } else { JSP_MATCH('{'); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_STR && !strcmp(jslGetTokenValueAsString(lex), "compiled")) { jsWarn("Function marked with \"compiled\" uploaded in source form"); } #endif /* If the function starts with return, treat it specially - * we don't want to store the 'return' part of it */ if (funcVar && lex->tk==LEX_R_RETURN) { funcVar->flags = (funcVar->flags & ~JSV_VARTYPEMASK) | JSV_FUNCTION_RETURN; JSP_ASSERT_MATCH(LEX_R_RETURN); } } // Get the line number (if needed) JsVarInt lineNumber = 0; if (funcVar && lex->lineNumberOffset) { // jslGetLineNumber is slow, so we only do it if we have debug info lineNumber = (JsVarInt)jslGetLineNumber(lex) + (JsVarInt)lex->lineNumberOffset - 1; } // Get the code - parse it and figure out where it stops JslCharPos funcBegin = jslCharPosClone(&lex->tokenStart); int lastTokenEnd = -1; if (!expressionOnly) { int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->it)-1; JSP_ASSERT_MATCH(lex->tk); } } else { JsExecFlags oldExec = execInfo.execute; execInfo.execute = EXEC_NO; jsvUnLock(jspeAssignmentExpression()); execInfo.execute = oldExec; lastTokenEnd = (int)jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; } // Then create var and set (if there was any code!) if (funcVar && lastTokenEnd>0) { // code var JsVar *funcCodeVar; if (jsvIsNativeString(lex->sourceVar)) { /* If we're parsing from a Native String (eg. E.memoryArea, E.setBootCode) then use another Native String to load function code straight from flash */ int s = (int)jsvStringIteratorGetIndex(&funcBegin.it) - 1; funcCodeVar = jsvNewNativeString(lex->sourceVar->varData.nativeStr.ptr + s, (unsigned int)(lastTokenEnd - s)); } else { if (jsfGetFlag(JSF_PRETOKENISE)) { funcCodeVar = jslNewTokenisedStringFromLexer(&funcBegin, (size_t)lastTokenEnd); } else { funcCodeVar = jslNewStringFromLexer(&funcBegin, (size_t)lastTokenEnd); } } jsvUnLock2(jsvAddNamedChild(funcVar, funcCodeVar, JSPARSE_FUNCTION_CODE_NAME), funcCodeVar); // scope var JsVar *funcScopeVar = jspeiGetScopesAsVar(); if (funcScopeVar) { jsvUnLock2(jsvAddNamedChild(funcVar, funcScopeVar, JSPARSE_FUNCTION_SCOPE_NAME), funcScopeVar); } // If we've got a line number, add a var for it if (lineNumber) { JsVar *funcLineNumber = jsvNewFromInteger(lineNumber); if (funcLineNumber) { jsvUnLock2(jsvAddNamedChild(funcVar, funcLineNumber, JSPARSE_FUNCTION_LINENUMBER_NAME), funcLineNumber); } } } jslCharPosFree(&funcBegin); if (!expressionOnly) JSP_MATCH('}'); return 0; } // Parse function (after 'function' has occurred NO_INLINE JsVar *jspeFunctionDefinition(bool parseNamedFunction) { // actually parse a function... We assume that the LEX_FUNCTION and name // have already been parsed JsVar *funcVar = 0; bool actuallyCreateFunction = JSP_SHOULD_EXECUTE; if (actuallyCreateFunction) funcVar = jsvNewWithFlags(JSV_FUNCTION); JsVar *functionInternalName = 0; if (parseNamedFunction && lex->tk==LEX_ID) { // you can do `var a = function foo() { foo(); };` - so cope with this if (funcVar) functionInternalName = jslGetTokenValueAsVar(lex); // note that we don't add it to the beginning, because it would mess up our function call code JSP_ASSERT_MATCH(LEX_ID); } // Get arguments save them to the structure if (!jspeFunctionArguments(funcVar)) { jsvUnLock2(functionInternalName, funcVar); // parse failed return 0; } // Parse the actual function block jspeFunctionDefinitionInternal(funcVar, false); // if we had a function name, add it to the end (if we don't it gets confused with arguments) if (funcVar && functionInternalName) jsvObjectSetChildAndUnLock(funcVar, JSPARSE_FUNCTION_NAME_NAME, functionInternalName); return funcVar; } /* Parse just the brackets of a function - and throw * everything away */ NO_INLINE bool jspeParseFunctionCallBrackets() { assert(!JSP_SHOULD_EXECUTE); JSP_MATCH('('); while (!JSP_SHOULDNT_PARSE && lex->tk != ')') { jsvUnLock(jspeAssignmentExpression()); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_ARROW_FUNCTION) { jsvUnLock(jspeArrowFunction(0, 0)); } #endif if (lex->tk!=')') JSP_MATCH(','); } if (!JSP_SHOULDNT_PARSE) JSP_MATCH(')'); return 0; } /** Handle a function call (assumes we've parsed the function name and we're * on the start bracket). 'thisArg' is the value of the 'this' variable when the * function is executed (it's usually the parent object) * * * NOTE: this does not set the execInfo flags - so if execInfo==EXEC_NO, it won't execute * * If !isParsing and arg0!=0, argument 0 is set to what is supplied (same with arg1) * * functionName is used only for error reporting - and can be 0 */ NO_INLINE JsVar *jspeFunctionCall(JsVar *function, JsVar *functionName, JsVar *thisArg, bool isParsing, int argCount, JsVar **argPtr) { if (JSP_SHOULD_EXECUTE && !function) { if (functionName) jsExceptionHere(JSET_ERROR, "Function %q not found!", functionName); else jsExceptionHere(JSET_ERROR, "Function not found!", functionName); return 0; } if (JSP_SHOULD_EXECUTE) if (!jspCheckStackPosition()) return 0; // try and ensure that we won't overflow our stack if (JSP_SHOULD_EXECUTE && function) { JsVar *returnVar = 0; if (!jsvIsFunction(function)) { jsExceptionHere(JSET_ERROR, "Expecting a function to call, got %t", function); return 0; } JsVar *thisVar = jsvLockAgainSafe(thisArg); if (isParsing) JSP_MATCH('('); /* Ok, so we have 4 options here. * * 1: we're native. * a) args have been pre-parsed, which is awesome * b) we have to parse our own args into an array * 2: we're not native * a) args were pre-parsed and we have to populate the function * b) we parse our own args, which is possibly better */ if (jsvIsNative(function)) { // ------------------------------------- NATIVE unsigned int argPtrSize = 0; int boundArgs = 0; // Add 'bound' parameters if there were any JsvObjectIterator it; jsvObjectIteratorNew(&it, function); JsVar *param = jsvObjectIteratorGetKey(&it); while (jsvIsFunctionParameter(param)) { if ((unsigned)argCount>=argPtrSize) { // allocate more space on stack if needed unsigned int newArgPtrSize = argPtrSize?argPtrSize*4:16; JsVar **newArgPtr = (JsVar**)alloca(sizeof(JsVar*)*newArgPtrSize); memcpy(newArgPtr, argPtr, (unsigned)argCount*sizeof(JsVar*)); argPtr = newArgPtr; argPtrSize = newArgPtrSize; } // if we already had arguments - shift them up... int i; for (i=argCount-1;i>=boundArgs;i--) argPtr[i+1] = argPtr[i]; // add bound argument argPtr[boundArgs] = jsvSkipName(param); argCount++; boundArgs++; jsvUnLock(param); jsvObjectIteratorNext(&it); param = jsvObjectIteratorGetKey(&it); } // check if 'this' was defined while (param) { if (jsvIsStringEqual(param, JSPARSE_FUNCTION_THIS_NAME)) { jsvUnLock(thisVar); thisVar = jsvSkipName(param); break; } jsvUnLock(param); jsvObjectIteratorNext(&it); param = jsvObjectIteratorGetKey(&it); } jsvUnLock(param); jsvObjectIteratorFree(&it); // Now, if we're parsing add the rest of the arguments int allocatedArgCount = boundArgs; if (isParsing) { while (!JSP_HAS_ERROR && lex->tk!=')' && lex->tk!=LEX_EOF) { if ((unsigned)argCount>=argPtrSize) { // allocate more space on stack unsigned int newArgPtrSize = argPtrSize?argPtrSize*4:16; JsVar **newArgPtr = (JsVar**)alloca(sizeof(JsVar*)*newArgPtrSize); memcpy(newArgPtr, argPtr, (unsigned)argCount*sizeof(JsVar*)); argPtr = newArgPtr; argPtrSize = newArgPtrSize; } argPtr[argCount++] = jsvSkipNameAndUnLock(jspeAssignmentExpression()); if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',',jsvUnLockMany((unsigned)argCount, argPtr);jsvUnLock(thisVar);, 0); } JSP_MATCH(')'); allocatedArgCount = argCount; } void *nativePtr = jsvGetNativeFunctionPtr(function); JsVar *oldThisVar = execInfo.thisVar; if (thisVar) execInfo.thisVar = jsvRef(thisVar); else { if (nativePtr==jswrap_eval) { // eval gets to use the current scope /* Note: proper JS has some utterly insane code that depends on whether * eval is an lvalue or not: * * http://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript * * Doing this in Espruino is quite an upheaval for that one * slightly insane case - so it's not implemented. */ if (execInfo.thisVar) execInfo.thisVar = jsvRef(execInfo.thisVar); } else { execInfo.thisVar = jsvRef(execInfo.root); // 'this' should always default to root } } if (nativePtr && !JSP_HAS_ERROR) { returnVar = jsnCallFunction(nativePtr, function->varData.native.argTypes, thisVar, argPtr, argCount); } else { returnVar = 0; } // unlock values if we locked them jsvUnLockMany((unsigned)allocatedArgCount, argPtr); /* Return to old 'this' var. No need to unlock as we never locked before */ if (execInfo.thisVar) jsvUnRef(execInfo.thisVar); execInfo.thisVar = oldThisVar; } else { // ----------------------------------------------------- NOT NATIVE // create a new symbol table entry for execution of this function // OPT: can we cache this function execution environment + param variables? // OPT: Probably when calling a function ONCE, use it, otherwise when recursing, make new? JsVar *functionRoot = jsvNewWithFlags(JSV_FUNCTION); if (!functionRoot) { // out of memory jspSetError(false); jsvUnLock(thisVar); return 0; } JsVar *functionScope = 0; JsVar *functionCode = 0; JsVar *functionInternalName = 0; uint16_t functionLineNumber = 0; /** NOTE: We expect that the function object will have: * * * Parameters * * Code/Scope/Name * * IN THAT ORDER. */ JsvObjectIterator it; jsvObjectIteratorNew(&it, function); JsVar *param = jsvObjectIteratorGetKey(&it); JsVar *value = jsvObjectIteratorGetValue(&it); while (jsvIsFunctionParameter(param) && value) { JsVar *paramName = jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH); if (paramName) { // could be out of memory jsvMakeFunctionParameter(paramName); // force this to be called a function parameter jsvSetValueOfName(paramName, value); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } else jspSetError(false); jsvUnLock2(value, param); jsvObjectIteratorNext(&it); param = jsvObjectIteratorGetKey(&it); value = jsvObjectIteratorGetValue(&it); } jsvUnLock2(value, param); if (isParsing) { int hadParams = 0; // grab in all parameters. We go around this loop until we've run out // of named parameters AND we've parsed all the supplied arguments while (!JSP_SHOULDNT_PARSE && lex->tk!=')') { JsVar *param = jsvObjectIteratorGetKey(&it); bool paramDefined = jsvIsFunctionParameter(param); if (lex->tk!=')' || paramDefined) { hadParams++; JsVar *value = 0; // ONLY parse this if it was supplied, otherwise leave 0 (undefined) if (lex->tk!=')') value = jspeAssignmentExpression(); // and if execute, copy it over value = jsvSkipNameAndUnLock(value); JsVar *paramName = paramDefined ? jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH) : jsvNewFromEmptyString(); if (paramName) { // could be out of memory jsvMakeFunctionParameter(paramName); // force this to be called a function parameter jsvSetValueOfName(paramName, value); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } else jspSetError(false); jsvUnLock(value); if (lex->tk!=')') JSP_MATCH(','); } jsvUnLock(param); if (paramDefined) jsvObjectIteratorNext(&it); } JSP_MATCH(')'); } else { // and NOT isParsing int args = 0; while (args<argCount) { JsVar *param = jsvObjectIteratorGetKey(&it); bool paramDefined = jsvIsFunctionParameter(param); JsVar *paramName = paramDefined ? jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH) : jsvNewFromEmptyString(); if (paramName) { jsvMakeFunctionParameter(paramName); // force this to be called a function parameter jsvSetValueOfName(paramName, argPtr[args]); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } else jspSetError(false); args++; jsvUnLock(param); if (paramDefined) jsvObjectIteratorNext(&it); } } // Now go through what's left while (jsvObjectIteratorHasValue(&it)) { JsVar *param = jsvObjectIteratorGetKey(&it); if (jsvIsString(param)) { if (jsvIsStringEqual(param, JSPARSE_FUNCTION_SCOPE_NAME)) functionScope = jsvSkipName(param); else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_CODE_NAME)) functionCode = jsvSkipName(param); else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_NAME_NAME)) functionInternalName = jsvSkipName(param); else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_THIS_NAME)) { jsvUnLock(thisVar); thisVar = jsvSkipName(param); } else if (jsvIsStringEqual(param, JSPARSE_FUNCTION_LINENUMBER_NAME)) functionLineNumber = (uint16_t)jsvGetIntegerAndUnLock(jsvSkipName(param)); else if (jsvIsFunctionParameter(param)) { JsVar *paramName = jsvNewFromStringVar(param,1,JSVAPPENDSTRINGVAR_MAXLENGTH); // paramName is already a name (it's a function parameter) if (paramName) {// could be out of memory - or maybe just not supplied! jsvMakeFunctionParameter(paramName); JsVar *defaultVal = jsvSkipName(param); if (defaultVal) jsvUnLock(jsvSetValueOfName(paramName, defaultVal)); jsvAddName(functionRoot, paramName); jsvUnLock(paramName); } } } jsvUnLock(param); jsvObjectIteratorNext(&it); } jsvObjectIteratorFree(&it); // setup a the function's name (if a named function) if (functionInternalName) { JsVar *name = jsvMakeIntoVariableName(jsvNewFromStringVar(functionInternalName,0,JSVAPPENDSTRINGVAR_MAXLENGTH), function); jsvAddName(functionRoot, name); jsvUnLock2(name, functionInternalName); } if (!JSP_HAS_ERROR) { // save old scopes JsVar *oldScopes[JSPARSE_MAX_SCOPES]; int oldScopeCount; int i; oldScopeCount = execInfo.scopeCount; for (i=0;i<execInfo.scopeCount;i++) oldScopes[i] = execInfo.scopes[i]; // if we have a scope var, load it up. We may not have one if there were no scopes apart from root if (functionScope) { jspeiLoadScopesFromVar(functionScope); jsvUnLock(functionScope); } else { // no scope var defined? We have no scopes at all! execInfo.scopeCount = 0; } // add the function's execute space to the symbol table so we can recurse if (jspeiAddScope(functionRoot)) { /* Adding scope may have failed - we may have descended too deep - so be sure * not to pull somebody else's scope off */ JsVar *oldThisVar = execInfo.thisVar; if (thisVar) execInfo.thisVar = jsvRef(thisVar); else execInfo.thisVar = jsvRef(execInfo.root); // 'this' should always default to root /* we just want to execute the block, but something could * have messed up and left us with the wrong Lexer, so * we want to be careful here... */ if (functionCode) { #ifdef USE_DEBUGGER bool hadDebuggerNextLineOnly = false; if (execInfo.execute&EXEC_DEBUGGER_STEP_INTO) { if (functionName) jsiConsolePrintf("Stepping into %v\n", functionName); else jsiConsolePrintf("Stepping into function\n", functionName); } else { hadDebuggerNextLineOnly = execInfo.execute&EXEC_DEBUGGER_NEXT_LINE; if (hadDebuggerNextLineOnly) execInfo.execute &= (JsExecFlags)~EXEC_DEBUGGER_NEXT_LINE; } #endif JsLex newLex; JsLex *oldLex = jslSetLex(&newLex); jslInit(functionCode); newLex.lineNumberOffset = functionLineNumber; JSP_SAVE_EXECUTE(); // force execute without any previous state #ifdef USE_DEBUGGER execInfo.execute = EXEC_YES | (execInfo.execute&(EXEC_CTRL_C_MASK|EXEC_ERROR_MASK|EXEC_DEBUGGER_NEXT_LINE)); #else execInfo.execute = EXEC_YES | (execInfo.execute&(EXEC_CTRL_C_MASK|EXEC_ERROR_MASK)); #endif if (jsvIsFunctionReturn(function)) { #ifdef USE_DEBUGGER // we didn't parse a statement so wouldn't trigger the debugger otherwise if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE && JSP_SHOULD_EXECUTE) { lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; jsiDebuggerLoop(); } #endif // implicit return - we just need an expression (optional) if (lex->tk != ';' && lex->tk != '}') returnVar = jsvSkipNameAndUnLock(jspeExpression()); } else { // setup a return variable JsVar *returnVarName = jsvAddNamedChild(functionRoot, 0, JSPARSE_RETURN_VAR); // parse the whole block jspeBlockNoBrackets(); /* get the real return var before we remove it from our function. * We can unlock below because returnVarName is still part of * functionRoot, so won't get freed. */ returnVar = jsvSkipNameAndUnLock(returnVarName); if (returnVarName) // could have failed with out of memory jsvSetValueOfName(returnVarName, 0); // remove return value (which helps stops circular references) } // Store a stack trace if we had an error JsExecFlags hasError = execInfo.execute&EXEC_ERROR_MASK; JSP_RESTORE_EXECUTE(); // because return will probably have set execute to false #ifdef USE_DEBUGGER bool calledDebugger = false; if (execInfo.execute & EXEC_DEBUGGER_MASK) { jsiConsolePrint("Value returned is ="); jsfPrintJSON(returnVar, JSON_LIMIT | JSON_SOME_NEWLINES | JSON_PRETTY | JSON_SHOW_DEVICES); jsiConsolePrintChar('\n'); if (execInfo.execute & EXEC_DEBUGGER_FINISH_FUNCTION) { calledDebugger = true; jsiDebuggerLoop(); } } if (hadDebuggerNextLineOnly && !calledDebugger) execInfo.execute |= EXEC_DEBUGGER_NEXT_LINE; #endif jslKill(); jslSetLex(oldLex); if (hasError) { execInfo.execute |= hasError; // propogate error JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, jsvIsString(functionName)?"in function %q called from ": "in function called from ", functionName); if (lex) { jspAppendStackTrace(stackTrace); } else jsvAppendPrintf(stackTrace, "system\n"); jsvUnLock(stackTrace); } } } /* Return to old 'this' var. No need to unlock as we never locked before */ if (execInfo.thisVar) jsvUnRef(execInfo.thisVar); execInfo.thisVar = oldThisVar; jspeiRemoveScope(); } // Unref old scopes for (i=0;i<execInfo.scopeCount;i++) jsvUnLock(execInfo.scopes[i]); // restore function scopes for (i=0;i<oldScopeCount;i++) execInfo.scopes[i] = oldScopes[i]; execInfo.scopeCount = oldScopeCount; } jsvUnLock(functionCode); jsvUnLock(functionRoot); } jsvUnLock(thisVar); return returnVar; } else if (isParsing) { // ---------------------------------- function, but not executing - just parse args and be done jspeParseFunctionCallBrackets(); /* Do not return function, as it will be unlocked! */ return 0; } else return 0; } // Find a variable (or built-in function) based on the current scopes JsVar *jspGetNamedVariable(const char *tokenName) { JsVar *a = JSP_SHOULD_EXECUTE ? jspeiFindInScopes(tokenName) : 0; if (JSP_SHOULD_EXECUTE && !a) { /* Special case! We haven't found the variable, so check out * and see if it's one of our builtins... */ if (jswIsBuiltInObject(tokenName)) { // Check if we have a built-in function for it // OPT: Could we instead have jswIsBuiltInObjectWithoutConstructor? JsVar *obj = jswFindBuiltInFunction(0, tokenName); // If not, make one if (!obj) obj = jspNewBuiltin(tokenName); if (obj) { // not out of memory a = jsvAddNamedChild(execInfo.root, obj, tokenName); jsvUnLock(obj); } } else { a = jswFindBuiltInFunction(0, tokenName); if (!a) { /* Variable doesn't exist! JavaScript says we should create it * (we won't add it here. This is done in the assignment operator)*/ a = jsvMakeIntoVariableName(jsvNewFromString(tokenName), 0); } } } return a; } /// Used by jspGetNamedField / jspGetVarNamedField static NO_INLINE JsVar *jspGetNamedFieldInParents(JsVar *object, const char* name, bool returnName) { // Now look in prototypes JsVar * child = jspeiFindChildFromStringInParents(object, name); /* Check for builtins via separate function * This way we save on RAM for built-ins because everything comes out of program code */ if (!child) { child = jswFindBuiltInFunction(object, name); } /* We didn't get here if we found a child in the object itself, so * if we're here then we probably have the wrong name - so for example * with `a.b = c;` could end up setting `a.prototype.b` (bug #360) * * Also we might have got a built-in, which wouldn't have a name on it * anyway - so in both cases, strip the name if it is there, and create * a new name. */ if (child && returnName) { // Get rid of existing name child = jsvSkipNameAndUnLock(child); // create a new name JsVar *nameVar = jsvNewFromString(name); JsVar *newChild = jsvCreateNewChild(object, nameVar, child); jsvUnLock2(nameVar, child); child = newChild; } // If not found and is the prototype, create it if (!child) { if (jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) { // prototype is supposed to be an object JsVar *proto = jsvNewObject(); // make sure it has a 'constructor' variable that points to the object it was part of jsvObjectSetChild(proto, JSPARSE_CONSTRUCTOR_VAR, object); child = jsvAddNamedChild(object, proto, JSPARSE_PROTOTYPE_VAR); jspEnsureIsPrototype(object, child); jsvUnLock(proto); } else if (strcmp(name, JSPARSE_INHERITS_VAR)==0) { const char *objName = jswGetBasicObjectName(object); if (objName) { child = jspNewPrototype(objName); } } } return child; } /** Get the named function/variable on the object - whether it's built in, or predefined. * If !returnName, returns the function/variable itself or undefined, but * if returnName, return a name (could be fake) referencing the parent. * * NOTE: ArrayBuffer/Strings are not handled here. We assume that if we're * passing a char* rather than a JsVar it's because we're looking up via * a symbol rather than a variable. To handle these use jspGetVarNamedField */ JsVar *jspGetNamedField(JsVar *object, const char* name, bool returnName) { JsVar *child = 0; // if we're an object (or pretending to be one) if (jsvHasChildren(object)) child = jsvFindChildFromString(object, name, false); if (!child) { child = jspGetNamedFieldInParents(object, name, returnName); // If not found and is the prototype, create it if (!child && jsvIsFunction(object) && strcmp(name, JSPARSE_PROTOTYPE_VAR)==0) { JsVar *value = jsvNewObject(); // prototype is supposed to be an object child = jsvAddNamedChild(object, value, JSPARSE_PROTOTYPE_VAR); jsvUnLock(value); } } if (returnName) return child; else return jsvSkipNameAndUnLock(child); } /// see jspGetNamedField - note that nameVar should have had jsvAsArrayIndex called on it first JsVar *jspGetVarNamedField(JsVar *object, JsVar *nameVar, bool returnName) { JsVar *child = 0; // if we're an object (or pretending to be one) if (jsvHasChildren(object)) child = jsvFindChildFromVar(object, nameVar, false); if (!child) { if (jsvIsArrayBuffer(object) && jsvIsInt(nameVar)) { // for array buffers, we actually create a NAME, and hand that back - then when we assign (or use SkipName) we pull out the correct data child = jsvMakeIntoVariableName(jsvNewFromInteger(jsvGetInteger(nameVar)), object); if (child) // turn into an 'array buffer name' child->flags = (child->flags & ~JSV_VARTYPEMASK) | JSV_ARRAYBUFFERNAME; } else if (jsvIsString(object) && jsvIsInt(nameVar)) { JsVarInt idx = jsvGetInteger(nameVar); if (idx>=0 && idx<(JsVarInt)jsvGetStringLength(object)) { char ch = jsvGetCharInString(object, (size_t)idx); child = jsvNewStringOfLength(1, &ch); } else if (returnName) child = jsvCreateNewChild(object, nameVar, 0); // just return *something* to show this is handled } else { // get the name as a string char name[JSLEX_MAX_TOKEN_LENGTH]; jsvGetString(nameVar, name, JSLEX_MAX_TOKEN_LENGTH); // try and find it in parents child = jspGetNamedFieldInParents(object, name, returnName); // If not found and is the prototype, create it if (!child && jsvIsFunction(object) && jsvIsStringEqual(nameVar, JSPARSE_PROTOTYPE_VAR)) { JsVar *value = jsvNewObject(); // prototype is supposed to be an object child = jsvAddNamedChild(object, value, JSPARSE_PROTOTYPE_VAR); jsvUnLock(value); } } } if (returnName) return child; else return jsvSkipNameAndUnLock(child); } /// Call the named function on the object - whether it's built in, or predefined. Returns the return value of the function. JsVar *jspCallNamedFunction(JsVar *object, char* name, int argCount, JsVar **argPtr) { JsVar *child = jspGetNamedField(object, name, false); JsVar *r = 0; if (jsvIsFunction(child)) r = jspeFunctionCall(child, 0, object, false, argCount, argPtr); jsvUnLock(child); return r; } NO_INLINE JsVar *jspeFactorMember(JsVar *a, JsVar **parentResult) { /* The parent if we're executing a method call */ JsVar *parent = 0; while (lex->tk=='.' || lex->tk=='[') { if (lex->tk == '.') { // ------------------------------------- Record Access JSP_ASSERT_MATCH('.'); if (jslIsIDOrReservedWord(lex)) { if (JSP_SHOULD_EXECUTE) { // Note: name will go away when we parse something else! const char *name = jslGetTokenValueAsString(lex); JsVar *aVar = jsvSkipName(a); JsVar *child = 0; if (aVar) child = jspGetNamedField(aVar, name, true); if (!child) { if (!jsvIsUndefined(aVar)) { // if no child found, create a pointer to where it could be // as we don't want to allocate it until it's written JsVar *nameVar = jslGetTokenValueAsVar(lex); child = jsvCreateNewChild(aVar, nameVar, 0); jsvUnLock(nameVar); } else { // could have been a string... jsExceptionHere(JSET_ERROR, "Cannot read property '%s' of undefined", name); } } jsvUnLock(parent); parent = aVar; jsvUnLock(a); a = child; } // skip over current token (we checked above that it was an ID or reserved word) jslGetNextToken(lex); } else { // incorrect token - force a match fail by asking for an ID JSP_MATCH_WITH_RETURN(LEX_ID, a); } } else if (lex->tk == '[') { // ------------------------------------- Array Access JsVar *index; JSP_ASSERT_MATCH('['); if (!jspCheckStackPosition()) return parent; index = jsvSkipNameAndUnLock(jspeAssignmentExpression()); JSP_MATCH_WITH_CLEANUP_AND_RETURN(']', jsvUnLock2(parent, index);, a); if (JSP_SHOULD_EXECUTE) { index = jsvAsArrayIndexAndUnLock(index); JsVar *aVar = jsvSkipName(a); JsVar *child = 0; if (aVar) child = jspGetVarNamedField(aVar, index, true); if (!child) { if (jsvHasChildren(aVar)) { // if no child found, create a pointer to where it could be // as we don't want to allocate it until it's written child = jsvCreateNewChild(aVar, index, 0); } else { jsExceptionHere(JSET_ERROR, "Field or method %q does not already exist, and can't create it on %t", index, aVar); } } jsvUnLock(parent); parent = jsvLockAgainSafe(aVar); jsvUnLock(a); a = child; jsvUnLock(aVar); } jsvUnLock(index); } else { assert(0); } } if (parentResult) *parentResult = parent; else jsvUnLock(parent); return a; } NO_INLINE JsVar *jspeConstruct(JsVar *func, JsVar *funcName, bool hasArgs) { assert(JSP_SHOULD_EXECUTE); if (!jsvIsFunction(func)) { jsExceptionHere(JSET_ERROR, "Constructor should be a function, but is %t", func); return 0; } JsVar *thisObj = jsvNewObject(); if (!thisObj) return 0; // out of memory // Make sure the function has a 'prototype' var JsVar *prototypeName = jsvFindChildFromString(func, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(func, prototypeName); // make sure it's an object JsVar *prototypeVar = jsvSkipName(prototypeName); jsvUnLock3(jsvAddNamedChild(thisObj, prototypeVar, JSPARSE_INHERITS_VAR), prototypeVar, prototypeName); JsVar *a = jspeFunctionCall(func, funcName, thisObj, hasArgs, 0, 0); /* FIXME: we should ignore return values that aren't objects (bug #848), but then we need * to be aware of `new String()` and `new Uint8Array()`. Ideally we'd let through * arrays/etc, and then String/etc should return 'boxed' values. * * But they don't return boxed values at the moment, so let's just * pass the return value through. If you try and return a string from * a function it's broken JS code anyway. */ if (a) { jsvUnLock(thisObj); thisObj = a; } else { jsvUnLock(a); } return thisObj; } NO_INLINE JsVar *jspeFactorFunctionCall() { /* The parent if we're executing a method call */ bool isConstructor = false; if (lex->tk==LEX_R_NEW) { JSP_ASSERT_MATCH(LEX_R_NEW); isConstructor = true; if (lex->tk==LEX_R_NEW) { jsExceptionHere(JSET_ERROR, "Nesting 'new' operators is unsupported"); jspSetError(false); return 0; } } JsVar *parent = 0; #ifndef SAVE_ON_FLASH bool wasSuper = lex->tk==LEX_R_SUPER; #endif JsVar *a = jspeFactorMember(jspeFactor(), &parent); #ifndef SAVE_ON_FLASH if (wasSuper) { /* if this was 'super.something' then we need * to overwrite the parent, because it'll be * set to the prototype otherwise. */ jsvUnLock(parent); parent = jsvLockAgainSafe(execInfo.thisVar); } #endif while ((lex->tk=='(' || (isConstructor && JSP_SHOULD_EXECUTE)) && !jspIsInterrupted()) { JsVar *funcName = a; JsVar *func = jsvSkipName(funcName); /* The constructor function doesn't change parsing, so if we're * not executing, just short-cut it. */ if (isConstructor && JSP_SHOULD_EXECUTE) { // If we have '(' parse an argument list, otherwise don't look for any args bool parseArgs = lex->tk=='('; a = jspeConstruct(func, funcName, parseArgs); isConstructor = false; // don't treat subsequent brackets as constructors } else a = jspeFunctionCall(func, funcName, parent, true, 0, 0); jsvUnLock3(funcName, func, parent); parent=0; a = jspeFactorMember(a, &parent); } jsvUnLock(parent); return a; } NO_INLINE JsVar *jspeFactorObject() { if (JSP_SHOULD_EXECUTE) { JsVar *contents = jsvNewObject(); if (!contents) { // out of memory jspSetError(false); return 0; } /* JSON-style object definition */ JSP_MATCH_WITH_RETURN('{', contents); while (!JSP_SHOULDNT_PARSE && lex->tk != '}') { JsVar *varName = 0; // we only allow strings or IDs on the left hand side of an initialisation if (jslIsIDOrReservedWord(lex)) { if (JSP_SHOULD_EXECUTE) varName = jslGetTokenValueAsVar(lex); jslGetNextToken(lex); // skip over current token } else if ( lex->tk==LEX_STR || lex->tk==LEX_TEMPLATE_LITERAL || lex->tk==LEX_FLOAT || lex->tk==LEX_INT || lex->tk==LEX_R_TRUE || lex->tk==LEX_R_FALSE || lex->tk==LEX_R_NULL || lex->tk==LEX_R_UNDEFINED) { varName = jspeFactor(); } else { JSP_MATCH_WITH_RETURN(LEX_ID, contents); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock(varName), contents); if (JSP_SHOULD_EXECUTE) { varName = jsvAsArrayIndexAndUnLock(varName); JsVar *contentsName = jsvFindChildFromVar(contents, varName, true); if (contentsName) { JsVar *value = jsvSkipNameAndUnLock(jspeAssignmentExpression()); // value can be 0 (could be undefined!) jsvUnLock2(jsvSetValueOfName(contentsName, value), value); } } jsvUnLock(varName); // no need to clean here, as it will definitely be used if (lex->tk != '}') JSP_MATCH_WITH_RETURN(',', contents); } JSP_MATCH_WITH_RETURN('}', contents); return contents; } else { // Not executing so do fast skip jspeBlock(); return 0; } } NO_INLINE JsVar *jspeFactorArray() { int idx = 0; JsVar *contents = 0; if (JSP_SHOULD_EXECUTE) { contents = jsvNewEmptyArray(); if (!contents) { // out of memory jspSetError(false); return 0; } } /* JSON-style array */ JSP_MATCH_WITH_RETURN('[', contents); while (!JSP_SHOULDNT_PARSE && lex->tk != ']') { if (JSP_SHOULD_EXECUTE) { JsVar *aVar = 0; JsVar *indexName = 0; if (lex->tk != ',') { // #287 - [,] and [1,2,,4] are allowed aVar = jsvSkipNameAndUnLock(jspeAssignmentExpression()); indexName = jsvMakeIntoVariableName(jsvNewFromInteger(idx), aVar); } if (indexName) { // could be out of memory jsvAddName(contents, indexName); jsvUnLock(indexName); } jsvUnLock(aVar); } else { jsvUnLock(jspeAssignmentExpression()); } // no need to clean here, as it will definitely be used if (lex->tk != ']') JSP_MATCH_WITH_RETURN(',', contents); idx++; } if (contents) jsvSetArrayLength(contents, idx, false); JSP_MATCH_WITH_RETURN(']', contents); return contents; } NO_INLINE void jspEnsureIsPrototype(JsVar *instanceOf, JsVar *prototypeName) { if (!prototypeName) return; JsVar *prototypeVar = jsvSkipName(prototypeName); if (!jsvIsObject(prototypeVar)) { if (!jsvIsUndefined(prototypeVar)) jsExceptionHere(JSET_TYPEERROR, "Prototype should be an object, got %t", prototypeVar); jsvUnLock(prototypeVar); prototypeVar = jsvNewObject(); // prototype is supposed to be an object JsVar *lastName = jsvSkipToLastName(prototypeName); jsvSetValueOfName(lastName, prototypeVar); jsvUnLock(lastName); } JsVar *constructor = jsvFindChildFromString(prototypeVar, JSPARSE_CONSTRUCTOR_VAR, true); if (constructor) jsvSetValueOfName(constructor, instanceOf); jsvUnLock2(constructor, prototypeVar); } NO_INLINE JsVar *jspeFactorTypeOf() { JSP_ASSERT_MATCH(LEX_R_TYPEOF); JsVar *a = jspeUnaryExpression(); JsVar *result = 0; if (JSP_SHOULD_EXECUTE) { if (!jsvIsVariableDefined(a)) { // so we don't get a ReferenceError when accessing an undefined var result=jsvNewFromString("undefined"); } else { a = jsvSkipNameAndUnLock(a); result=jsvNewFromString(jsvGetTypeOf(a)); } } jsvUnLock(a); return result; } NO_INLINE JsVar *jspeFactorDelete() { JSP_ASSERT_MATCH(LEX_R_DELETE); JsVar *parent = 0; JsVar *a = jspeFactorMember(jspeFactor(), &parent); JsVar *result = 0; if (JSP_SHOULD_EXECUTE) { bool ok = false; if (jsvIsName(a) && !jsvIsNewChild(a)) { // if no parent, check in root? if (!parent && jsvIsChild(execInfo.root, a)) parent = jsvLockAgain(execInfo.root); if (parent && !jsvIsFunction(parent)) { // else remove properly. if (jsvIsArray(parent)) { // For arrays, we must make sure we don't change the length JsVarInt l = jsvGetArrayLength(parent); jsvRemoveChild(parent, a); jsvSetArrayLength(parent, l, false); } else { jsvRemoveChild(parent, a); } ok = true; } } result = jsvNewFromBool(ok); } jsvUnLock2(a, parent); return result; } #ifndef SAVE_ON_FLASH JsVar *jspeTemplateLiteral() { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) { JsVar *template = jslGetTokenValueAsVar(lex); a = jsvNewFromEmptyString(); if (a && template) { JsvStringIterator it, dit; jsvStringIteratorNew(&it, template, 0); jsvStringIteratorNew(&dit, a, 0); while (jsvStringIteratorHasChar(&it)) { char ch = jsvStringIteratorGetChar(&it); if (ch=='$') { jsvStringIteratorNext(&it); ch = jsvStringIteratorGetChar(&it); if (ch=='{') { // Now parse out the expression jsvStringIteratorNext(&it); int brackets = 1; JsVar *expr = jsvNewFromEmptyString(); if (!expr) break; JsvStringIterator eit; jsvStringIteratorNew(&eit, expr, 0); while (jsvStringIteratorHasChar(&it)) { ch = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); if (ch=='{') brackets++; if (ch=='}') { brackets--; if (!brackets) break; } jsvStringIteratorAppend(&eit, ch); } jsvStringIteratorFree(&eit); JsVar *result = jspEvaluateExpressionVar(expr); jsvUnLock(expr); result = jsvAsString(result, true); jsvStringIteratorAppendString(&dit, result, 0); jsvUnLock(result); } else { jsvStringIteratorAppend(&dit, '$'); } } else { jsvStringIteratorAppend(&dit, ch); jsvStringIteratorNext(&it); } } jsvStringIteratorFree(&it); jsvStringIteratorFree(&dit); } jsvUnLock(template); } JSP_ASSERT_MATCH(LEX_TEMPLATE_LITERAL); return a; } #endif NO_INLINE JsVar *jspeAddNamedFunctionParameter(JsVar *funcVar, JsVar *name) { if (!funcVar) funcVar = jsvNewWithFlags(JSV_FUNCTION); char buf[JSLEX_MAX_TOKEN_LENGTH+1]; buf[0] = '\xFF'; jsvGetString(name, &buf[1], JSLEX_MAX_TOKEN_LENGTH); JsVar *param = jsvAddNamedChild(funcVar, 0, buf); jsvMakeFunctionParameter(param); jsvUnLock(param); return funcVar; } #ifndef SAVE_ON_FLASH // parse an arrow function NO_INLINE JsVar *jspeArrowFunction(JsVar *funcVar, JsVar *a) { assert(!a || jsvIsName(a)); JSP_ASSERT_MATCH(LEX_ARROW_FUNCTION); funcVar = jspeAddNamedFunctionParameter(funcVar, a); bool expressionOnly = lex->tk!='{'; jspeFunctionDefinitionInternal(funcVar, expressionOnly); if (execInfo.thisVar) { jsvObjectSetChild(funcVar, JSPARSE_FUNCTION_THIS_NAME, execInfo.thisVar); } return funcVar; } // parse expressions with commas, maybe followed by an arrow function (bracket already matched) NO_INLINE JsVar *jspeExpressionOrArrowFunction() { JsVar *a = 0; JsVar *funcVar = 0; bool allNames = true; while (lex->tk!=')' && !JSP_SHOULDNT_PARSE) { if (allNames && a) { // we never get here if this isn't a name and a string funcVar = jspeAddNamedFunctionParameter(funcVar, a); } jsvUnLock(a); a = jspeAssignmentExpression(); if (!(jsvIsName(a) && jsvIsString(a))) allNames = false; if (lex->tk!=')') JSP_MATCH_WITH_CLEANUP_AND_RETURN(',', jsvUnLock2(a,funcVar), 0); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(a,funcVar), 0); // if arrow is found, create a function if (allNames && lex->tk==LEX_ARROW_FUNCTION) { funcVar = jspeArrowFunction(funcVar, a); jsvUnLock(a); return funcVar; } else { jsvUnLock(funcVar); return a; } } /// Parse an ES6 class, expects LEX_R_CLASS already parsed NO_INLINE JsVar *jspeClassDefinition(bool parseNamedClass) { JsVar *classFunction = 0; JsVar *classPrototype = 0; JsVar *classInternalName = 0; bool actuallyCreateClass = JSP_SHOULD_EXECUTE; if (actuallyCreateClass) classFunction = jsvNewWithFlags(JSV_FUNCTION); if (parseNamedClass && lex->tk==LEX_ID) { if (classFunction) classInternalName = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_ID); } if (classFunction) { JsVar *prototypeName = jsvFindChildFromString(classFunction, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(classFunction, prototypeName); // make sure it's an object classPrototype = jsvSkipName(prototypeName); jsvUnLock(prototypeName); } if (lex->tk==LEX_R_EXTENDS) { JSP_ASSERT_MATCH(LEX_R_EXTENDS); JsVar *extendsFrom = actuallyCreateClass ? jsvSkipNameAndUnLock(jspGetNamedVariable(jslGetTokenValueAsString(lex))) : 0; JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock4(extendsFrom,classFunction,classInternalName,classPrototype),0); if (classPrototype) { if (jsvIsFunction(extendsFrom)) { jsvObjectSetChild(classPrototype, JSPARSE_INHERITS_VAR, extendsFrom); // link in default constructor if ours isn't supplied jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_CODE_NAME, jsvNewFromString("if(this.__proto__.__proto__)this.__proto__.__proto__.apply(this,arguments)")); } else jsExceptionHere(JSET_SYNTAXERROR, "'extends' argument should be a function, got %t", extendsFrom); } jsvUnLock(extendsFrom); } JSP_MATCH_WITH_CLEANUP_AND_RETURN('{',jsvUnLock3(classFunction,classInternalName,classPrototype),0); while ((lex->tk==LEX_ID || lex->tk==LEX_R_STATIC) && !jspIsInterrupted()) { bool isStatic = lex->tk==LEX_R_STATIC; if (isStatic) JSP_ASSERT_MATCH(LEX_R_STATIC); JsVar *funcName = jslGetTokenValueAsVar(lex); JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock3(classFunction,classInternalName,classPrototype),0); JsVar *method = jspeFunctionDefinition(false); if (classFunction && classPrototype) { if (jsvIsStringEqual(funcName, "get") || jsvIsStringEqual(funcName, "set")) { jsExceptionHere(JSET_SYNTAXERROR, "'get' and 'set' and not supported in Espruino"); } else if (jsvIsStringEqual(funcName, "constructor")) { jswrap_function_replaceWith(classFunction, method); } else { funcName = jsvMakeIntoVariableName(funcName, 0); jsvSetValueOfName(funcName, method); jsvAddName(isStatic ? classFunction : classPrototype, funcName); } } jsvUnLock2(method,funcName); } jsvUnLock(classPrototype); // If we had a name, add it to the end (or it gets confused with the constructor arguments) if (classInternalName) jsvObjectSetChildAndUnLock(classFunction, JSPARSE_FUNCTION_NAME_NAME, classInternalName); JSP_MATCH_WITH_CLEANUP_AND_RETURN('}',jsvUnLock(classFunction),0); return classFunction; } #endif NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH // Just parse a normal expression (which can include commas) JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { // 'this' is an object - must be calling a normal method JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor // But if we're doing something else - eg '.' or '[' then it needs to reference the prototype JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { // 'this' is a function - must be calling a static method JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; } NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); // in-place add/subtract jspReplaceWith(a, res); jsvUnLock(res); // but then use the old value jsvUnLock(a); a = oldValue; } } return a; } NO_INLINE JsVar *jspePostfixExpression() { JsVar *a; // TODO: should be in jspeUnaryExpression if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); a = jspePostfixExpression(); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); // in-place add/subtract jspReplaceWith(a, res); jsvUnLock(res); } } else a = jspeFactorFunctionCall(); return __jspePostfixExpression(a); } NO_INLINE JsVar *jspeUnaryExpression() { if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { short tk = lex->tk; JSP_ASSERT_MATCH(tk); if (!JSP_SHOULD_EXECUTE) { return jspeUnaryExpression(); } if (tk=='!') { // logical not return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='~') { // bitwise not return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='-') { // unary minus return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped } else if (tk=='+') { // unary plus (convert to number) JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); JsVar *r = jsvAsNumber(v); // names already skipped jsvUnLock(v); return r; } assert(0); return 0; } else return jspePostfixExpression(); } // Get the precedence of a BinaryExpression - or return 0 if not one unsigned int jspeGetBinaryExpressionPrecedence(int op) { switch (op) { case LEX_OROR: return 1; break; case LEX_ANDAND: return 2; break; case '|' : return 3; break; case '^' : return 4; break; case '&' : return 5; break; case LEX_EQUAL: case LEX_NEQUAL: case LEX_TYPEEQUAL: case LEX_NTYPEEQUAL: return 6; case LEX_LEQUAL: case LEX_GEQUAL: case '<': case '>': case LEX_R_INSTANCEOF: return 7; case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; case LEX_LSHIFT: case LEX_RSHIFT: case LEX_RSHIFTUNSIGNED: return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 10; default: return 0; } } NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { /* This one's a bit strange. Basically all the ops have their own precedence, it's not * like & and | share the same precedence. We don't want to recurse for each one, * so instead we do this. * * We deal with an expression in recursion ONLY if it's of higher precedence * than the current one, otherwise we stick in the while loop. */ unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); while (precedence && precedence>lastPrecedence) { int op = lex->tk; JSP_ASSERT_MATCH(op); // if we have short-circuit ops, then if we know the outcome // we don't bother to execute the other op. Even if not // we need to tell mathsOp it's an & or | if (op==LEX_ANDAND || op==LEX_OROR) { bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); if ((!aValue && op==LEX_ANDAND) || (aValue && op==LEX_OROR)) { // use first argument (A) JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); JSP_RESTORE_EXECUTE(); } else { // use second argument (B) jsvUnLock(a); a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); } } else { // else it's a more 'normal' logical expression - just use Maths JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); if (JSP_SHOULD_EXECUTE) { if (op==LEX_R_IN) { JsVar *av = jsvSkipName(a); // needle JsVar *bv = jsvSkipName(b); // haystack if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values av = jsvAsArrayIndexAndUnLock(av); JsVar *varFound = jspGetVarNamedField( bv, av, true); jsvUnLock(a); a = jsvNewFromBool(varFound!=0); jsvUnLock(varFound); } else {// else it will be undefined jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv); jsvUnLock(a); a = 0; } jsvUnLock2(av, bv); } else if (op==LEX_R_INSTANCEOF) { bool inst = false; JsVar *av = jsvSkipName(a); JsVar *bv = jsvSkipName(b); if (!jsvIsFunction(bv)) { jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv); } else { if (jsvIsObject(av) || jsvIsFunction(av)) { JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); while (proto) { if (proto == bproto) inst=true; // search prototype chain JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); jsvUnLock(proto); proto = childProto; } if (jspIsConstructor(bv, "Object")) inst = true; jsvUnLock(bproto); } if (!inst) { const char *name = jswGetBasicObjectName(av); if (name) { inst = jspIsConstructor(bv, name); } // Hack for built-ins that should also be instances of Object if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && jspIsConstructor(bv, "Object")) inst = true; } } jsvUnLock3(av, bv, a); a = jsvNewFromBool(inst); } else { // --------------------------------------------- NORMAL JsVar *res = jsvMathsOpSkipNames(a, b, op); jsvUnLock(a); a = res; } } jsvUnLock(b); } precedence = jspeGetBinaryExpressionPrecedence(lex->tk); } return a; } JsVar *jspeBinaryExpression() { return __jspeBinaryExpression(jspeUnaryExpression(),0); } NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { if (lex->tk=='?') { JSP_ASSERT_MATCH('?'); if (!JSP_SHOULD_EXECUTE) { // just let lhs pass through jsvUnLock(jspeAssignmentExpression()); JSP_MATCH(':'); jsvUnLock(jspeAssignmentExpression()); } else { bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); jsvUnLock(lhs); if (first) { lhs = jspeAssignmentExpression(); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); } else { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); JSP_MATCH(':'); lhs = jspeAssignmentExpression(); } } } return lhs; } JsVar *jspeConditionalExpression() { return __jspeConditionalExpression(jspeBinaryExpression()); } NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } JsVar *jspeAssignmentExpression() { return __jspeAssignmentExpression(jspeConditionalExpression()); } // ',' is allowed to add multiple expressions, this is not allowed in jspeAssignmentExpression NO_INLINE JsVar *jspeExpression() { while (!JSP_SHOULDNT_PARSE) { JsVar *a = jspeAssignmentExpression(); if (lex->tk!=',') return a; // if we get a comma, we just forget this data and parse the next bit... jsvCheckReferenceError(a); jsvUnLock(a); JSP_ASSERT_MATCH(','); } return 0; } /** Parse a block `{ ... }` but assume brackets are already parsed */ NO_INLINE void jspeBlockNoBrackets() { if (JSP_SHOULD_EXECUTE) { while (lex->tk && lex->tk!='}') { JsVar *a = jspeStatement(); jsvCheckReferenceError(a); jsvUnLock(a); if (JSP_HAS_ERROR) { if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, "at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); } } } if (JSP_SHOULDNT_PARSE) return; } } else { // fast skip of blocks int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; JSP_ASSERT_MATCH(lex->tk); } } return; } /** Parse a block `{ ... }` */ NO_INLINE void jspeBlock() { JSP_MATCH_WITH_RETURN('{',); jspeBlockNoBrackets(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN('}',); return; } NO_INLINE JsVar *jspeBlockOrStatement() { if (lex->tk=='{') { jspeBlock(); return 0; } else { JsVar *v = jspeStatement(); if (lex->tk==';') JSP_ASSERT_MATCH(';'); return v; } } /** Parse using current lexer until we hit the end of * input or there was some problem. */ NO_INLINE JsVar *jspParse() { JsVar *v = 0; while (!JSP_SHOULDNT_PARSE && lex->tk != LEX_EOF) { jsvUnLock(v); v = jspeBlockOrStatement(); } return v; } NO_INLINE JsVar *jspeStatementVar() { JsVar *lastDefined = 0; /* variable creation. TODO - we need a better way of parsing the left * hand side. Maybe just have a flag called can_create_var that we * set and then we parse as if we're doing a normal equals.*/ assert(lex->tk==LEX_R_VAR || lex->tk==LEX_R_LET || lex->tk==LEX_R_CONST); jslGetNextToken(); ///TODO: Correctly implement CONST and LET - we just treat them like 'var' at the moment bool hasComma = true; // for first time in loop while (hasComma && lex->tk == LEX_ID && !jspIsInterrupted()) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) { a = jspeiFindOnTop(jslGetTokenValueAsString(lex), true); if (!a) { // out of memory jspSetError(false); return lastDefined; } } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(a), lastDefined); // sort out initialiser if (lex->tk == '=') { JsVar *var; JSP_MATCH_WITH_CLEANUP_AND_RETURN('=', jsvUnLock(a), lastDefined); var = jsvSkipNameAndUnLock(jspeAssignmentExpression()); if (JSP_SHOULD_EXECUTE) jspReplaceWith(a, var); jsvUnLock(var); } jsvUnLock(lastDefined); lastDefined = a; hasComma = lex->tk == ','; if (hasComma) JSP_MATCH_WITH_RETURN(',', lastDefined); } return lastDefined; } NO_INLINE JsVar *jspeStatementIf() { bool cond; JsVar *var, *result = 0; JSP_ASSERT_MATCH(LEX_R_IF); JSP_MATCH('('); var = jspeExpression(); if (JSP_SHOULDNT_PARSE) return var; JSP_MATCH(')'); cond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(var)); jsvUnLock(var); JSP_SAVE_EXECUTE(); if (!cond) jspSetNoExecute(); JsVar *a = jspeBlockOrStatement(); if (!cond) { jsvUnLock(a); JSP_RESTORE_EXECUTE(); } else { result = a; } if (lex->tk==LEX_R_ELSE) { JSP_ASSERT_MATCH(LEX_R_ELSE); JSP_SAVE_EXECUTE(); if (cond) jspSetNoExecute(); JsVar *a = jspeBlockOrStatement(); if (cond) { jsvUnLock(a); JSP_RESTORE_EXECUTE(); } else { result = a; } } return result; } NO_INLINE JsVar *jspeStatementSwitch() { JSP_ASSERT_MATCH(LEX_R_SWITCH); JSP_MATCH('('); JsVar *switchOn = jspeExpression(); JSP_SAVE_EXECUTE(); bool execute = JSP_SHOULD_EXECUTE; JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock(switchOn), 0); // shortcut if not executing... if (!execute) { jsvUnLock(switchOn); jspeBlock(); return 0; } JSP_MATCH_WITH_CLEANUP_AND_RETURN('{', jsvUnLock(switchOn), 0); bool executeDefault = true; if (execute) execInfo.execute=EXEC_NO|EXEC_IN_SWITCH; while (lex->tk==LEX_R_CASE) { JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_CASE, jsvUnLock(switchOn), 0); JsExecFlags oldFlags = execInfo.execute; if (execute) execInfo.execute=EXEC_YES|EXEC_IN_SWITCH; JsVar *test = jspeAssignmentExpression(); execInfo.execute = oldFlags|EXEC_IN_SWITCH;; JSP_MATCH_WITH_CLEANUP_AND_RETURN(':', jsvUnLock2(switchOn, test), 0); bool cond = false; if (execute) cond = jsvGetBoolAndUnLock(jsvMathsOpSkipNames(switchOn, test, LEX_TYPEEQUAL)); if (cond) executeDefault = false; jsvUnLock(test); if (cond && (execInfo.execute&EXEC_RUN_MASK)==EXEC_NO) execInfo.execute=EXEC_YES|EXEC_IN_SWITCH; while (!JSP_SHOULDNT_PARSE && lex->tk!=LEX_EOF && lex->tk!=LEX_R_CASE && lex->tk!=LEX_R_DEFAULT && lex->tk!='}') jsvUnLock(jspeBlockOrStatement()); oldExecute |= execInfo.execute & (EXEC_ERROR_MASK|EXEC_RETURN); // copy across any errors/exceptions/returns } jsvUnLock(switchOn); if (execute && (execInfo.execute&EXEC_RUN_MASK)==EXEC_BREAK) { execInfo.execute=EXEC_YES|EXEC_IN_SWITCH; } else { executeDefault = true; } JSP_RESTORE_EXECUTE(); if (lex->tk==LEX_R_DEFAULT) { JSP_ASSERT_MATCH(LEX_R_DEFAULT); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); if (!executeDefault) jspSetNoExecute(); else execInfo.execute |= EXEC_IN_SWITCH; while (!JSP_SHOULDNT_PARSE && lex->tk!=LEX_EOF && lex->tk!='}') jsvUnLock(jspeBlockOrStatement()); oldExecute |= execInfo.execute & (EXEC_ERROR_MASK|EXEC_RETURN); // copy across any errors/exceptions/returns execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_BREAK; JSP_RESTORE_EXECUTE(); } JSP_MATCH('}'); return 0; } NO_INLINE JsVar *jspeStatementDoOrWhile(bool isWhile) { #ifdef JSPARSE_MAX_LOOP_ITERATIONS int loopCount = JSPARSE_MAX_LOOP_ITERATIONS; #endif JsVar *cond; bool loopCond = true; // true for do...while loops bool hasHadBreak = false; JslCharPos whileCondStart; // We do repetition by pulling out the string representing our statement // there's definitely some opportunity for optimisation here JSP_ASSERT_MATCH(isWhile ? LEX_R_WHILE : LEX_R_DO); bool wasInLoop = (execInfo.execute&EXEC_IN_LOOP)!=0; if (isWhile) { // while loop JSP_MATCH('('); whileCondStart = jslCharPosClone(&lex->tokenStart); cond = jspeAssignmentExpression(); loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&whileCondStart);,0); } JslCharPos whileBodyStart = jslCharPosClone(&lex->tokenStart); JSP_SAVE_EXECUTE(); // actually try and execute first bit of while loop (we'll do the rest in the actual loop later) if (!loopCond) jspSetNoExecute(); execInfo.execute |= EXEC_IN_LOOP; jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES; hasHadBreak = true; // fail loop condition, so we exit } if (!loopCond) JSP_RESTORE_EXECUTE(); if (!isWhile) { // do..while loop JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_WHILE,jslCharPosFree(&whileBodyStart);,0); JSP_MATCH_WITH_CLEANUP_AND_RETURN('(',jslCharPosFree(&whileBodyStart);if (isWhile)jslCharPosFree(&whileCondStart);,0); whileCondStart = jslCharPosClone(&lex->tokenStart); cond = jspeAssignmentExpression(); loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&whileBodyStart);jslCharPosFree(&whileCondStart);,0); } JslCharPos whileBodyEnd; whileBodyEnd = jslCharPosClone(&lex->tokenStart); while (!hasHadBreak && loopCond #ifdef JSPARSE_MAX_LOOP_ITERATIONS && loopCount-->0 #endif ) { jslSeekToP(&whileCondStart); cond = jspeAssignmentExpression(); loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); if (loopCond) { jslSeekToP(&whileBodyStart); execInfo.execute |= EXEC_IN_LOOP; jspDebuggerLoopIfCtrlC(); jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = (execInfo.execute & ~EXEC_RUN_MASK) | EXEC_YES; hasHadBreak = true; } } } jslSeekToP(&whileBodyEnd); jslCharPosFree(&whileCondStart); jslCharPosFree(&whileBodyStart); jslCharPosFree(&whileBodyEnd); #ifdef JSPARSE_MAX_LOOP_ITERATIONS if (loopCount<=0) { jsExceptionHere(JSET_ERROR, "WHILE Loop exceeded the maximum number of iterations (" STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS) ")"); } #endif return 0; } NO_INLINE JsVar *jspeStatementFor() { JSP_ASSERT_MATCH(LEX_R_FOR); JSP_MATCH('('); bool wasInLoop = (execInfo.execute&EXEC_IN_LOOP)!=0; execInfo.execute |= EXEC_FOR_INIT; // initialisation JsVar *forStatement = 0; // we could have 'for (;;)' - so don't munch up our semicolon if that's all we have if (lex->tk != ';') forStatement = jspeStatement(); if (jspIsInterrupted()) { jsvUnLock(forStatement); return 0; } execInfo.execute &= (JsExecFlags)~EXEC_FOR_INIT; if (lex->tk == LEX_R_IN) { // for (i in array) // where i = jsvUnLock(forStatement); if (JSP_SHOULD_EXECUTE && !jsvIsName(forStatement)) { jsvUnLock(forStatement); jsExceptionHere(JSET_ERROR, "FOR a IN b - 'a' must be a variable name, not %t", forStatement); return 0; } bool addedIteratorToScope = false; if (JSP_SHOULD_EXECUTE && !jsvGetRefs(forStatement)) { // if the variable did not exist, add it to the scope addedIteratorToScope = true; jsvAddName(execInfo.root, forStatement); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_R_IN, jsvUnLock(forStatement), 0); JsVar *array = jsvSkipNameAndUnLock(jspeExpression()); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(forStatement, array), 0); JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart); JSP_SAVE_EXECUTE(); jspSetNoExecute(); execInfo.execute |= EXEC_IN_LOOP; jsvUnLock(jspeBlockOrStatement()); JslCharPos forBodyEnd = jslCharPosClone(&lex->tokenStart); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; JSP_RESTORE_EXECUTE(); if (JSP_SHOULD_EXECUTE) { if (jsvIsIterable(array)) { JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(array); JsVar *foundPrototype = 0; JsvIterator it; jsvIteratorNew(&it, array, JSIF_DEFINED_ARRAY_ElEMENTS); bool hasHadBreak = false; while (JSP_SHOULD_EXECUTE && jsvIteratorHasElement(&it) && !hasHadBreak) { JsVar *loopIndexVar = jsvIteratorGetKey(&it); bool ignore = false; if (checkerFunction && checkerFunction(loopIndexVar)) { ignore = true; if (jsvIsString(loopIndexVar) && jsvIsStringEqual(loopIndexVar, JSPARSE_INHERITS_VAR)) foundPrototype = jsvSkipName(loopIndexVar); } if (!ignore) { JsVar *indexValue = jsvIsName(loopIndexVar) ? jsvCopyNameOnly(loopIndexVar, false/*no copy children*/, false/*not a name*/) : loopIndexVar; if (indexValue) { // could be out of memory assert(!jsvIsName(indexValue) && jsvGetRefs(indexValue)==0); jsvSetValueOfName(forStatement, indexValue); if (indexValue!=loopIndexVar) jsvUnLock(indexValue); jsvIteratorNext(&it); jslSeekToP(&forBodyStart); execInfo.execute |= EXEC_IN_LOOP; jspDebuggerLoopIfCtrlC(); jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; } } } else jsvIteratorNext(&it); jsvUnLock(loopIndexVar); if (!jsvIteratorHasElement(&it) && foundPrototype) { jsvIteratorFree(&it); jsvIteratorNew(&it, foundPrototype, JSIF_DEFINED_ARRAY_ElEMENTS); jsvUnLock(foundPrototype); foundPrototype = 0; } } assert(!foundPrototype); jsvIteratorFree(&it); } else if (!jsvIsUndefined(array)) { jsExceptionHere(JSET_ERROR, "FOR loop can only iterate over Arrays, Strings or Objects, not %t", array); } } jslSeekToP(&forBodyEnd); jslCharPosFree(&forBodyStart); jslCharPosFree(&forBodyEnd); if (addedIteratorToScope) { jsvRemoveChild(execInfo.root, forStatement); } jsvUnLock2(forStatement, array); } else { // ----------------------------------------------- NORMAL FOR LOOP #ifdef JSPARSE_MAX_LOOP_ITERATIONS int loopCount = JSPARSE_MAX_LOOP_ITERATIONS; #endif bool loopCond = true; bool hasHadBreak = false; jsvUnLock(forStatement); JSP_MATCH(';'); JslCharPos forCondStart = jslCharPosClone(&lex->tokenStart); if (lex->tk != ';') { JsVar *cond = jspeAssignmentExpression(); // condition loopCond = JSP_SHOULD_EXECUTE && jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(';',jslCharPosFree(&forCondStart);,0); JslCharPos forIterStart = jslCharPosClone(&lex->tokenStart); if (lex->tk != ')') { // we could have 'for (;;)' JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeExpression()); // iterator JSP_RESTORE_EXECUTE(); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jslCharPosFree(&forCondStart);jslCharPosFree(&forIterStart);,0); JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart); // actual for body JSP_SAVE_EXECUTE(); if (!loopCond) jspSetNoExecute(); execInfo.execute |= EXEC_IN_LOOP; jsvUnLock(jspeBlockOrStatement()); JslCharPos forBodyEnd = jslCharPosClone(&lex->tokenStart); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (loopCond || !JSP_SHOULD_EXECUTE) { if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; } } if (!loopCond) JSP_RESTORE_EXECUTE(); if (loopCond) { jslSeekToP(&forIterStart); if (lex->tk != ')') jsvUnLock(jspeExpression()); } while (!hasHadBreak && JSP_SHOULD_EXECUTE && loopCond #ifdef JSPARSE_MAX_LOOP_ITERATIONS && loopCount-->0 #endif ) { jslSeekToP(&forCondStart); ; if (lex->tk == ';') { loopCond = true; } else { JsVar *cond = jspeAssignmentExpression(); loopCond = jsvGetBoolAndUnLock(jsvSkipName(cond)); jsvUnLock(cond); } if (JSP_SHOULD_EXECUTE && loopCond) { jslSeekToP(&forBodyStart); execInfo.execute |= EXEC_IN_LOOP; jspDebuggerLoopIfCtrlC(); jsvUnLock(jspeBlockOrStatement()); if (!wasInLoop) execInfo.execute &= (JsExecFlags)~EXEC_IN_LOOP; if (execInfo.execute & EXEC_CONTINUE) execInfo.execute = EXEC_YES; else if (execInfo.execute & EXEC_BREAK) { execInfo.execute = EXEC_YES; hasHadBreak = true; } } if (JSP_SHOULD_EXECUTE && loopCond && !hasHadBreak) { jslSeekToP(&forIterStart); if (lex->tk != ')') jsvUnLock(jspeExpression()); } } jslSeekToP(&forBodyEnd); jslCharPosFree(&forCondStart); jslCharPosFree(&forIterStart); jslCharPosFree(&forBodyStart); jslCharPosFree(&forBodyEnd); #ifdef JSPARSE_MAX_LOOP_ITERATIONS if (loopCount<=0) { jsExceptionHere(JSET_ERROR, "FOR Loop exceeded the maximum number of iterations ("STRINGIFY(JSPARSE_MAX_LOOP_ITERATIONS)")"); } #endif } return 0; } NO_INLINE JsVar *jspeStatementTry() { // execute the try block JSP_ASSERT_MATCH(LEX_R_TRY); bool shouldExecuteBefore = JSP_SHOULD_EXECUTE; jspeBlock(); bool hadException = shouldExecuteBefore && ((execInfo.execute & EXEC_EXCEPTION)!=0); bool hadCatch = false; if (lex->tk == LEX_R_CATCH) { JSP_ASSERT_MATCH(LEX_R_CATCH); hadCatch = true; JSP_MATCH('('); JsVar *scope = 0; JsVar *exceptionVar = 0; if (hadException) { scope = jsvNewObject(); if (scope) exceptionVar = jsvFindChildFromString(scope, jslGetTokenValueAsString(lex), true); } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID,jsvUnLock2(scope,exceptionVar),0); JSP_MATCH_WITH_CLEANUP_AND_RETURN(')',jsvUnLock2(scope,exceptionVar),0); if (exceptionVar) { // set the exception var up properly JsVar *exception = jspGetException(); if (exception) { jsvSetValueOfName(exceptionVar, exception); jsvUnLock(exception); } // Now clear the exception flag (it's handled - we hope!) execInfo.execute = execInfo.execute & (JsExecFlags)~(EXEC_EXCEPTION|EXEC_ERROR_LINE_REPORTED); jsvUnLock(exceptionVar); } if (shouldExecuteBefore && !hadException) { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jspeBlock(); JSP_RESTORE_EXECUTE(); } else { if (!scope || jspeiAddScope(scope)) { jspeBlock(); if (scope) jspeiRemoveScope(); } } jsvUnLock(scope); } if (lex->tk == LEX_R_FINALLY || (!hadCatch && ((execInfo.execute&(EXEC_ERROR|EXEC_INTERRUPTED))==0))) { JSP_MATCH(LEX_R_FINALLY); // clear the exception flag - but only momentarily! if (hadException) execInfo.execute = execInfo.execute & (JsExecFlags)~EXEC_EXCEPTION; jspeBlock(); // put the flag back! if (hadException && !hadCatch) execInfo.execute = execInfo.execute | EXEC_EXCEPTION; } return 0; } NO_INLINE JsVar *jspeStatementReturn() { JsVar *result = 0; JSP_ASSERT_MATCH(LEX_R_RETURN); if (lex->tk != ';' && lex->tk != '}') { // we only want the value, so skip the name if there was one result = jsvSkipNameAndUnLock(jspeExpression()); } if (JSP_SHOULD_EXECUTE) { JsVar *resultVar = jspeiFindInScopes(JSPARSE_RETURN_VAR); if (resultVar) { jspReplaceWith(resultVar, result); jsvUnLock(resultVar); execInfo.execute |= EXEC_RETURN; // Stop anything else in this function executing } else { jsExceptionHere(JSET_SYNTAXERROR, "RETURN statement, but not in a function.\n"); } } jsvUnLock(result); return 0; } NO_INLINE JsVar *jspeStatementThrow() { JsVar *result = 0; JSP_ASSERT_MATCH(LEX_R_THROW); result = jsvSkipNameAndUnLock(jspeExpression()); if (JSP_SHOULD_EXECUTE) { jspSetException(result); // Stop anything else in this function executing } jsvUnLock(result); return 0; } NO_INLINE JsVar *jspeStatementFunctionDecl(bool isClass) { JsVar *funcName = 0; JsVar *funcVar; #ifndef SAVE_ON_FLASH JSP_ASSERT_MATCH(isClass ? LEX_R_CLASS : LEX_R_FUNCTION); #else JSP_ASSERT_MATCH(LEX_R_FUNCTION); #endif bool actuallyCreateFunction = JSP_SHOULD_EXECUTE; if (actuallyCreateFunction) { funcName = jsvMakeIntoVariableName(jslGetTokenValueAsVar(lex), 0); if (!funcName) { // out of memory return 0; } } JSP_MATCH_WITH_CLEANUP_AND_RETURN(LEX_ID, jsvUnLock(funcName), 0); #ifndef SAVE_ON_FLASH funcVar = isClass ? jspeClassDefinition(false) : jspeFunctionDefinition(false); #else funcVar = jspeFunctionDefinition(false); #endif if (actuallyCreateFunction) { // find a function with the same name (or make one) // OPT: can Find* use just a JsVar that is a 'name'? JsVar *existingName = jspeiFindNameOnTop(funcName, true); JsVar *existingFunc = jsvSkipName(existingName); if (jsvIsFunction(existingFunc)) { // 'proper' replace, that keeps the original function var and swaps the children funcVar = jsvSkipNameAndUnLock(funcVar); jswrap_function_replaceWith(existingFunc, funcVar); } else { jspReplaceWith(existingName, funcVar); } jsvUnLock(funcName); funcName = existingName; jsvUnLock(existingFunc); // existingName is used - don't UnLock } jsvUnLock(funcVar); return funcName; } NO_INLINE JsVar *jspeStatement() { #ifdef USE_DEBUGGER if (execInfo.execute&EXEC_DEBUGGER_NEXT_LINE && lex->tk!=';' && JSP_SHOULD_EXECUTE) { lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; jsiDebuggerLoop(); } #endif if (lex->tk==LEX_ID || lex->tk==LEX_INT || lex->tk==LEX_FLOAT || lex->tk==LEX_STR || lex->tk==LEX_TEMPLATE_LITERAL || lex->tk==LEX_REGEX || lex->tk==LEX_R_NEW || lex->tk==LEX_R_NULL || lex->tk==LEX_R_UNDEFINED || lex->tk==LEX_R_TRUE || lex->tk==LEX_R_FALSE || lex->tk==LEX_R_THIS || lex->tk==LEX_R_DELETE || lex->tk==LEX_R_TYPEOF || lex->tk==LEX_R_VOID || lex->tk==LEX_R_SUPER || lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS || lex->tk=='!' || lex->tk=='-' || lex->tk=='+' || lex->tk=='~' || lex->tk=='[' || lex->tk=='(') { /* Execute a simple statement that only contains basic arithmetic... */ return jspeExpression(); } else if (lex->tk=='{') { /* A block of code */ jspeBlock(); return 0; } else if (lex->tk==';') { /* Empty statement - to allow things like ;;; */ JSP_ASSERT_MATCH(';'); return 0; } else if (lex->tk==LEX_R_VAR || lex->tk==LEX_R_LET || lex->tk==LEX_R_CONST) { return jspeStatementVar(); } else if (lex->tk==LEX_R_IF) { return jspeStatementIf(); } else if (lex->tk==LEX_R_DO) { return jspeStatementDoOrWhile(false); } else if (lex->tk==LEX_R_WHILE) { return jspeStatementDoOrWhile(true); } else if (lex->tk==LEX_R_FOR) { return jspeStatementFor(); } else if (lex->tk==LEX_R_TRY) { return jspeStatementTry(); } else if (lex->tk==LEX_R_RETURN) { return jspeStatementReturn(); } else if (lex->tk==LEX_R_THROW) { return jspeStatementThrow(); } else if (lex->tk==LEX_R_FUNCTION) { return jspeStatementFunctionDecl(false/* function */); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { return jspeStatementFunctionDecl(true/* class */); #endif } else if (lex->tk==LEX_R_CONTINUE) { JSP_ASSERT_MATCH(LEX_R_CONTINUE); if (JSP_SHOULD_EXECUTE) { if (!(execInfo.execute & EXEC_IN_LOOP)) jsExceptionHere(JSET_SYNTAXERROR, "CONTINUE statement outside of FOR or WHILE loop"); else execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_CONTINUE; } } else if (lex->tk==LEX_R_BREAK) { JSP_ASSERT_MATCH(LEX_R_BREAK); if (JSP_SHOULD_EXECUTE) { if (!(execInfo.execute & (EXEC_IN_LOOP|EXEC_IN_SWITCH))) jsExceptionHere(JSET_SYNTAXERROR, "BREAK statement outside of SWITCH, FOR or WHILE loop"); else execInfo.execute = (execInfo.execute & (JsExecFlags)~EXEC_RUN_MASK) | EXEC_BREAK; } } else if (lex->tk==LEX_R_SWITCH) { return jspeStatementSwitch(); } else if (lex->tk==LEX_R_DEBUGGER) { JSP_ASSERT_MATCH(LEX_R_DEBUGGER); #ifdef USE_DEBUGGER if (JSP_SHOULD_EXECUTE) jsiDebuggerLoop(); #endif } else JSP_MATCH(LEX_EOF); return 0; } // ----------------------------------------------------------------------------- /// Create a new built-in object that jswrapper can use to check for built-in functions JsVar *jspNewBuiltin(const char *instanceOf) { JsVar *objFunc = jswFindBuiltInFunction(0, instanceOf); if (!objFunc) return 0; // out of memory return objFunc; } /// Create a new Class of the given instance and return its prototype NO_INLINE JsVar *jspNewPrototype(const char *instanceOf) { JsVar *objFuncName = jsvFindChildFromString(execInfo.root, instanceOf, true); if (!objFuncName) // out of memory return 0; JsVar *objFunc = jsvSkipName(objFuncName); if (!objFunc) { objFunc = jspNewBuiltin(instanceOf); if (!objFunc) { // out of memory jsvUnLock(objFuncName); return 0; } // set up name jsvSetValueOfName(objFuncName, objFunc); } JsVar *prototypeName = jsvFindChildFromString(objFunc, JSPARSE_PROTOTYPE_VAR, true); jspEnsureIsPrototype(objFunc, prototypeName); // make sure it's an object jsvUnLock2(objFunc, objFuncName); return prototypeName; } /** Create a new object of the given instance and add it to root with name 'name'. * If name!=0, added to root with name, and the name is returned * If name==0, not added to root and Object itself returned */ NO_INLINE JsVar *jspNewObject(const char *name, const char *instanceOf) { JsVar *prototypeName = jspNewPrototype(instanceOf); JsVar *obj = jsvNewObject(); if (!obj) { // out of memory jsvUnLock(prototypeName); return 0; } if (name) { // If it's a device, set the device number up as the Object data // See jsiGetDeviceFromClass IOEventFlags device = jshFromDeviceString(name); if (device!=EV_NONE) { obj->varData.str[0] = 'D'; obj->varData.str[1] = 'E'; obj->varData.str[2] = 'V'; obj->varData.str[3] = (char)device; } } // add __proto__ JsVar *prototypeVar = jsvSkipName(prototypeName); jsvUnLock3(jsvAddNamedChild(obj, prototypeVar, JSPARSE_INHERITS_VAR), prototypeVar, prototypeName);prototypeName=0; if (name) { JsVar *objName = jsvFindChildFromString(execInfo.root, name, true); if (objName) jsvSetValueOfName(objName, obj); jsvUnLock(obj); if (!objName) { // out of memory return 0; } return objName; } else return obj; } /** Returns true if the constructor function given is the same as that * of the object with the given name. */ bool jspIsConstructor(JsVar *constructor, const char *constructorName) { JsVar *objFunc = jsvObjectGetChild(execInfo.root, constructorName, 0); if (!objFunc) return false; bool isConstructor = objFunc == constructor; jsvUnLock(objFunc); return isConstructor; } /** Get the constructor of the given object, or return 0 if ot found, or not a function */ JsVar *jspGetConstructor(JsVar *object) { if (!jsvIsObject(object)) return 0; JsVar *proto = jsvObjectGetChild(object, JSPARSE_INHERITS_VAR, 0); if (jsvIsObject(proto)) { JsVar *constr = jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0); if (jsvIsFunction(constr)) { jsvUnLock(proto); return constr; } jsvUnLock(constr); } jsvUnLock(proto); return 0; } // ----------------------------------------------------------------------------- void jspSoftInit() { execInfo.root = jsvFindOrCreateRoot(); // Root now has a lock and a ref execInfo.hiddenRoot = jsvObjectGetChild(execInfo.root, JS_HIDDEN_CHAR_STR, JSV_OBJECT); execInfo.execute = EXEC_YES; } void jspSoftKill() { jsvUnLock(execInfo.hiddenRoot); execInfo.hiddenRoot = 0; jsvUnLock(execInfo.root); execInfo.root = 0; // Root is now left with just a ref } void jspInit() { jspSoftInit(); } void jspKill() { jspSoftKill(); // Unreffing this should completely kill everything attached to root JsVar *r = jsvFindOrCreateRoot(); jsvUnRef(r); jsvUnLock(r); } /** Evaluate the given variable as an expression (in current scope) */ JsVar *jspEvaluateExpressionVar(JsVar *str) { JsLex lex; assert(jsvIsString(str)); JsLex *oldLex = jslSetLex(&lex); jslInit(str); lex.lineNumberOffset = oldLex->lineNumberOffset; // actually do the parsing JsVar *v = jspeExpression(); jslKill(); jslSetLex(oldLex); return jsvSkipNameAndUnLock(v); } /** Execute code form a variable and return the result. If lineNumberOffset * is nonzero it's added to the line numbers that get reported for errors/debug */ JsVar *jspEvaluateVar(JsVar *str, JsVar *scope, uint16_t lineNumberOffset) { JsLex lex; assert(jsvIsString(str)); JsLex *oldLex = jslSetLex(&lex); jslInit(str); lex.lineNumberOffset = lineNumberOffset; JsExecInfo oldExecInfo = execInfo; execInfo.execute = EXEC_YES; bool scopeAdded = false; if (scope) { // if we're adding a scope, make sure it's the *only* scope execInfo.scopeCount = 0; scopeAdded = jspeiAddScope(scope); } // actually do the parsing JsVar *v = jspParse(); // clean up if (scopeAdded) jspeiRemoveScope(); jslKill(); jslSetLex(oldLex); // restore state and execInfo JsExecFlags mask = EXEC_FOR_INIT|EXEC_IN_LOOP|EXEC_IN_SWITCH; oldExecInfo.execute = (oldExecInfo.execute & mask) | (execInfo.execute & ~mask); execInfo = oldExecInfo; // It may have returned a reference, but we just want the value... return jsvSkipNameAndUnLock(v); } JsVar *jspEvaluate(const char *str, bool stringIsStatic) { /* using a memory area is more efficient, but the interpreter * may use substrings from it for function code. This means that * if the string goes away, everything gets corrupted - hence * the option here. */ JsVar *evCode; if (stringIsStatic) evCode = jsvNewNativeString((char*)str, strlen(str)); else evCode = jsvNewFromString(str); if (!evCode) return 0; JsVar *v = 0; if (!jsvIsMemoryFull()) v = jspEvaluateVar(evCode, 0, 0); jsvUnLock(evCode); return v; } JsVar *jspExecuteFunction(JsVar *func, JsVar *thisArg, int argCount, JsVar **argPtr) { JsExecInfo oldExecInfo = execInfo; execInfo.scopeCount = 0; execInfo.execute = EXEC_YES; execInfo.thisVar = 0; JsVar *result = jspeFunctionCall(func, 0, thisArg, false, argCount, argPtr); // clean up assert(execInfo.scopeCount==0); // restore state oldExecInfo.execute = execInfo.execute; // JSP_RESTORE_EXECUTE has made this ok. execInfo = oldExecInfo; return result; } /// Evaluate a JavaScript module and return its exports JsVar *jspEvaluateModule(JsVar *moduleContents) { assert(jsvIsString(moduleContents) || jsvIsFunction(moduleContents)); if (jsvIsFunction(moduleContents)) { moduleContents = jsvObjectGetChild(moduleContents,JSPARSE_FUNCTION_CODE_NAME,0); if (!jsvIsString(moduleContents)) { jsvUnLock(moduleContents); return 0; } } else jsvLockAgain(moduleContents); JsVar *scope = jsvNewObject(); JsVar *scopeExports = jsvNewObject(); if (!scope || !scopeExports) { // out of mem jsvUnLock3(scope, scopeExports, moduleContents); return 0; } JsVar *exportsName = jsvAddNamedChild(scope, scopeExports, "exports"); jsvUnLock2(scopeExports, jsvAddNamedChild(scope, scope, "module")); JsExecFlags oldExecute = execInfo.execute; JsVar *oldThisVar = execInfo.thisVar; execInfo.thisVar = scopeExports; // set 'this' variable to exports jsvUnLock(jspEvaluateVar(moduleContents, scope, 0)); execInfo.thisVar = oldThisVar; execInfo.execute = oldExecute; // make sure we fully restore state after parsing a module jsvUnLock2(moduleContents, scope); return jsvSkipNameAndUnLock(exportsName); } /** Get the owner of the current prototype. We assume that it's * the first item in the array, because that's what we will * have added when we created it. It's safe to call this on * non-prototypes and non-objects. */ JsVar *jspGetPrototypeOwner(JsVar *proto) { if (jsvIsObject(proto) || jsvIsArray(proto)) { return jsvSkipNameAndUnLock(jsvObjectGetChild(proto, JSPARSE_CONSTRUCTOR_VAR, 0)); } return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_163_1
crossvul-cpp_data_bad_4215_1
/* * h323.c * * Copyright (C) 2015-18 ntop.org * Copyright (C) 2013 Remy Mudingay <mudingay@ill.fr> * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_H323 #include "ndpi_api.h" struct tpkt { u_int8_t version, reserved; u_int16_t len; }; void ndpi_search_h323(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int16_t dport = 0, sport = 0; NDPI_LOG_DBG(ndpi_struct, "search H323\n"); /* The TPKT protocol is used by ISO 8072 (on port 102) and H.323. So this check below is to avoid ambiguities */ if((packet->tcp != NULL) && (packet->tcp->dest != ntohs(102))) { NDPI_LOG_DBG2(ndpi_struct, "calculated dport over tcp\n"); /* H323 */ if(packet->payload_packet_len >= 4 && (packet->payload[0] == 0x03) && (packet->payload[1] == 0x00)) { struct tpkt *t = (struct tpkt*)packet->payload; u_int16_t len = ntohs(t->len); if(packet->payload_packet_len == len) { /* We need to check if this packet is in reality a RDP (Remote Desktop) packet encapsulated on TPTK */ if(packet->payload[4] == (packet->payload_packet_len - sizeof(struct tpkt) - 1)) { /* ISO 8073/X.224 */ if((packet->payload[5] == 0xE0 /* CC Connect Request */) || (packet->payload[5] == 0xD0 /* CC Connect Confirm */)) { NDPI_LOG_INFO(ndpi_struct, "found RDP\n"); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_RDP, NDPI_PROTOCOL_UNKNOWN); return; } } flow->l4.tcp.h323_valid_packets++; if(flow->l4.tcp.h323_valid_packets >= 2) { NDPI_LOG_INFO(ndpi_struct, "found H323 broadcast\n"); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); } } else { /* This is not H.323 */ NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return; } } } else if(packet->udp != NULL) { sport = ntohs(packet->udp->source), dport = ntohs(packet->udp->dest); NDPI_LOG_DBG2(ndpi_struct, "calculated dport over udp\n"); if(packet->payload_packet_len >= 6 && packet->payload[0] == 0x80 && packet->payload[1] == 0x08 && (packet->payload[2] == 0xe7 || packet->payload[2] == 0x26) && packet->payload[4] == 0x00 && packet->payload[5] == 0x00) { NDPI_LOG_INFO(ndpi_struct, "found H323 broadcast\n"); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); return; } /* H323 */ if(sport == 1719 || dport == 1719) { if(packet->payload[0] == 0x16 && packet->payload[1] == 0x80 && packet->payload[4] == 0x06 && packet->payload[5] == 0x00) { NDPI_LOG_INFO(ndpi_struct, "found H323 broadcast\n"); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); return; } else if(packet->payload_packet_len >= 20 && packet->payload_packet_len <= 117) { NDPI_LOG_INFO(ndpi_struct, "found H323 broadcast\n"); ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_H323, NDPI_PROTOCOL_UNKNOWN); return; } else { NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return; } } } } void init_h323_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("H323", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_H323, ndpi_search_h323, NDPI_SELECTION_BITMASK_PROTOCOL_TCP_OR_UDP_WITH_PAYLOAD, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4215_1
crossvul-cpp_data_good_5201_0
#ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "gd_tga.h" #include "gd.h" #include "gd_errors.h" #include "gdhelpers.h" /*! \brief Creates a gdImage from a TGA file * Creates a gdImage from a TGA binary file via a gdIOCtx. * \param infile Pointer to TGA binary file * \return gdImagePtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTga(FILE *fp) { gdImagePtr image; gdIOCtx* in = gdNewFileCtx(fp); if (in == NULL) return NULL; image = gdImageCreateFromTgaCtx(in); in->gd_free( in ); return image; } BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaPtr(int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0); if (in == NULL) return NULL; im = gdImageCreateFromTgaCtx(in); in->gd_free(in); return im; } /*! \brief Creates a gdImage from a gdIOCtx * Creates a gdImage from a gdIOCtx referencing a TGA binary file. * \param ctx Pointer to a gdIOCtx structure * \return gdImagePtr */ BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx) { int bitmap_caret = 0; oTga *tga = NULL; /* int pixel_block_size = 0; int image_block_size = 0; */ volatile gdImagePtr image = NULL; int x = 0; int y = 0; tga = (oTga *) gdMalloc(sizeof(oTga)); if (!tga) { return NULL; } tga->bitmap = NULL; tga->ident = NULL; if (read_header_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } /*TODO: Will this be used? pixel_block_size = tga->bits / 8; image_block_size = (tga->width * tga->height) * pixel_block_size; */ if (read_image_tga(ctx, tga) < 0) { free_tga(tga); return NULL; } image = gdImageCreateTrueColor((int)tga->width, (int)tga->height ); if (image == 0) { free_tga( tga ); return NULL; } /*! \brief Populate GD image object * Copy the pixel data from our tga bitmap buffer into the GD image * Disable blending and save the alpha channel per default */ if (tga->alphabits) { gdImageAlphaBlending(image, 0); gdImageSaveAlpha(image, 1); } /* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */ for (y = 0; y < tga->height; y++) { register int *tpix = image->tpixels[y]; for ( x = 0; x < tga->width; x++, tpix++) { if (tga->bits == TGA_BPP_24) { *tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]); bitmap_caret += 3; } else if (tga->bits == TGA_BPP_32 && tga->alphabits) { register int a = tga->bitmap[bitmap_caret + 3]; *tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1)); bitmap_caret += 4; } } } if (tga->flipv && tga->fliph) { gdImageFlipBoth(image); } else if (tga->flipv) { gdImageFlipVertical(image); } else if (tga->fliph) { gdImageFlipHorizontal(image); } free_tga(tga); return image; } /*! \brief Reads a TGA header. * Reads the header block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 1 on sucess, -1 on failure */ int read_header_tga(gdIOCtx *ctx, oTga *tga) { unsigned char header[18]; if (gdGetBuf(header, sizeof(header), ctx) < 18) { gd_error("fail to read header"); return -1; } tga->identsize = header[0]; tga->colormaptype = header[1]; tga->imagetype = header[2]; tga->colormapstart = header[3] + (header[4] << 8); tga->colormaplength = header[5] + (header[6] << 8); tga->colormapbits = header[7]; tga->xstart = header[8] + (header[9] << 8); tga->ystart = header[10] + (header[11] << 8); tga->width = header[12] + (header[13] << 8); tga->height = header[14] + (header[15] << 8); tga->bits = header[16]; tga->alphabits = header[17] & 0x0f; tga->fliph = (header[17] & 0x10) ? 1 : 0; tga->flipv = (header[17] & 0x20) ? 0 : 1; #if DEBUG printf("format bps: %i\n", tga->bits); printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv); printf("alpha: %i\n", tga->alphabits); printf("wxh: %i %i\n", tga->width, tga->height); #endif if (!((tga->bits == TGA_BPP_24 && tga->alphabits == 0) || (tga->bits == TGA_BPP_32 && tga->alphabits == 8))) { gd_error_ex(GD_WARNING, "gd-tga: %u bits per pixel with %u alpha bits not supported\n", tga->bits, tga->alphabits); return -1; } tga->ident = NULL; if (tga->identsize > 0) { tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char)); if(tga->ident == NULL) { return -1; } gdGetBuf(tga->ident, tga->identsize, ctx); } return 1; } /*! \brief Reads a TGA image data into buffer. * Reads the image data block from a binary TGA file populating the referenced TGA structure. * \param ctx Pointer to TGA binary file * \param tga Pointer to TGA structure * \return int 0 on sucess, -1 on failure */ int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; uint8_t* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int j = 0; uint8_t encoded_pixels; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < image_block_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 ); buffer_caret++; for (i = 0; i < encoded_pixels; i++) { for (j = 0; j < pixel_block_size; j++, bitmap_caret++) { tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; } } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; for (i = 0; i < encoded_pixels; i++) { for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) { tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; } buffer_caret += pixel_block_size; } } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } /*! \brief Cleans up a TGA structure. * Dereferences the bitmap referenced in a TGA structure, then the structure itself * \param tga Pointer to TGA structure */ void free_tga(oTga * tga) { if (tga) { if (tga->ident) gdFree(tga->ident); if (tga->bitmap) gdFree(tga->bitmap); gdFree(tga); } }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5201_0
crossvul-cpp_data_bad_146_0
/* radare2 - LGPL - Copyright 2009-2018 - pancake, nibble, dso */ #include <r_bin.h> // maybe too big sometimes? 2KB of stack eaten here.. #define R_STRING_SCAN_BUFFER_SIZE 2048 static void print_string(RBinString *string, RBinFile *bf) { if (!string || !bf) { return; } int mode = bf->strmode; ut64 addr , vaddr; RBin *bin = bf->rbin; const char *section_name, *type_string; RIO *io = bin->iob.io; if (!io) { return; } RBinSection *s = r_bin_get_section_at (bf->o, string->paddr, false); if (s) { string->vaddr = s->vaddr + (string->paddr - s->paddr); } section_name = s ? s->name : ""; type_string = r_bin_string_type (string->type); vaddr = addr = r_bin_get_vaddr (bin, string->paddr, string->vaddr); switch(mode) { case MODE_SIMPLE : io->cb_printf ("0x%08" PFMT64x " %s\n", addr, string->string); break; case MODE_RADARE : { char *f_name, *nstr; f_name = strdup (string->string); r_name_filter (f_name, 512); if (bin->prefix) { nstr = r_str_newf ("%s.str.%s", bin->prefix, f_name); io->cb_printf ("f %s.str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n" "Cs %"PFMT64d" @ 0x%08"PFMT64x"\n", bin->prefix, f_name, string->size, addr, string->size, addr); } else { nstr = r_str_newf ("str.%s", f_name); io->cb_printf ("f str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n" "Cs %"PFMT64d" @ 0x%08"PFMT64x"\n", f_name, string->size, addr, string->size, addr); } free (nstr); free (f_name); break; } case MODE_PRINT : io->cb_printf ("%03u 0x%08"PFMT64x" 0x%08" PFMT64x" %3u %3u " "(%s) %5s %s\n", string->ordinal, string->paddr, vaddr, string->length, string->size, section_name, type_string, string->string); break; } } static int string_scan_range(RList *list, RBinFile *bf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (from >= to) { eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to); return -1; } ut8 *buf = calloc (to - from, 1); if (!buf || !min) { return -1; } r_buf_read_at (bf->buf, from, buf, to - from); // may oobread while (needle < to) { rc = r_utf8_decode (buf + needle - from, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc - from; if ((to - needle) > 5) { bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4]; if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle - from, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle - from, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle - from, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r) && r != '\\') { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 93) { tmp[i + 0] = '\\'; tmp[i + 1] = " abtnvfr e " " " " " " \\"[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { // reduce false positives int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } RBinString *bs = R_NEW0 (RBinString); if (!bs) { break; } bs->type = str_type; bs->length = runes; bs->size = needle - str_start; bs->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start -from> 1) { const ut8 *p = buf + str_start - 2 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start -from> 3) { const ut8 *p = buf + str_start - 4 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } bs->paddr = bs->vaddr = str_start; bs->string = r_str_ndup ((const char *)tmp, i); if (list) { r_list_append (list, bs); } else { print_string (bs, bf); r_bin_string_free (bs); } } } free (buf); return count; } static char *swiftField(const char *dn, const char *cn) { char *p = strstr (dn, ".getter_"); if (!p) { p = strstr (dn, ".setter_"); if (!p) { p = strstr (dn, ".method_"); } } if (p) { char *q = strstr (dn, cn); if (q && q[strlen (cn)] == '.') { q = strdup (q + strlen (cn) + 1); char *r = strchr (q, '.'); if (r) { *r = 0; } return q; } } return NULL; } R_API RList *r_bin_classes_from_symbols (RBinFile *bf, RBinObject *o) { RBinSymbol *sym; RListIter *iter; RList *symbols = o->symbols; RList *classes = o->classes; if (!classes) { classes = r_list_newf ((RListFree)r_bin_class_free); } r_list_foreach (symbols, iter, sym) { if (sym->name[0] != '_') { continue; } const char *cn = sym->classname; if (cn) { RBinClass *c = r_bin_class_new (bf, sym->classname, NULL, 0); if (!c) { continue; } // swift specific char *dn = sym->dname; char *fn = swiftField (dn, cn); if (fn) { // eprintf ("FIELD %s %s\n", cn, fn); RBinField *f = r_bin_field_new (sym->paddr, sym->vaddr, sym->size, fn, NULL, NULL); r_list_append (c->fields, f); free (fn); } else { char *mn = strstr (dn, ".."); if (mn) { // eprintf ("META %s %s\n", sym->classname, mn); } else { char *mn = strstr (dn, cn); if (mn && mn[strlen(cn)] == '.') { mn += strlen (cn) + 1; // eprintf ("METHOD %s %s\n", sym->classname, mn); r_list_append (c->methods, sym); } } } } } if (r_list_empty (classes)) { r_list_free (classes); return NULL; } return classes; } R_API RBinFile *r_bin_file_new(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, Sdb *sdb, bool steal_ptr) { RBinFile *binfile = R_NEW0 (RBinFile); if (!binfile) { return NULL; } if (!r_id_pool_grab_id (bin->file_ids, &binfile->id)) { if (steal_ptr) { // we own the ptr, free on error free ((void*) bytes); } free (binfile); //no id means no binfile return NULL; } int res = r_bin_file_set_bytes (binfile, bytes, sz, steal_ptr); if (!res && steal_ptr) { // we own the ptr, free on error free((void*) bytes); } binfile->rbin = bin; binfile->file = file? strdup (file): NULL; binfile->rawstr = rawstr; binfile->fd = fd; binfile->curxtr = r_bin_get_xtrplugin_by_name (bin, xtrname); binfile->sdb = sdb; binfile->size = file_sz; binfile->xtr_data = r_list_newf ((RListFree)r_bin_xtrdata_free); binfile->objs = r_list_newf ((RListFree)r_bin_object_free); binfile->xtr_obj = NULL; if (!binfile->buf) { //r_bin_file_free (binfile); binfile->buf = r_buf_new (); // return NULL; } if (sdb) { binfile->sdb = sdb_ns (sdb, sdb_fmt ("fd.%d", fd), 1); sdb_set (binfile->sdb, "archs", "0:0:x86:32", 0); // x86?? /* NOTE */ /* Those refs++ are necessary because sdb_ns() doesnt rerefs all * sub-namespaces */ /* And if any namespace is referenced backwards it gets * double-freed */ binfile->sdb_addrinfo = sdb_ns (binfile->sdb, "addrinfo", 1); binfile->sdb_addrinfo->refs++; sdb_ns_set (sdb, "cur", binfile->sdb); binfile->sdb->refs++; } return binfile; } R_API bool r_bin_file_object_new_from_xtr_data(RBin *bin, RBinFile *bf, ut64 baseaddr, ut64 loadaddr, RBinXtrData *data) { RBinObject *o = NULL; RBinPlugin *plugin = NULL; ut8* bytes; ut64 offset = data? data->offset: 0; ut64 sz = data ? data->size : 0; if (!data || !bf) { return false; } // for right now the bytes used will just be the offest into the binfile // buffer // if the extraction requires some sort of transformation then this will // need to be fixed // here. bytes = data->buffer; if (!bytes) { return false; } plugin = r_bin_get_binplugin_by_bytes (bin, (const ut8*)bytes, sz); if (!plugin) { plugin = r_bin_get_binplugin_any (bin); } r_buf_free (bf->buf); bf->buf = r_buf_new_with_bytes ((const ut8*)bytes, data->size); //r_bin_object_new append the new object into binfile o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, offset, sz); // size is set here because the reported size of the object depends on // if loaded from xtr plugin or partially read if (!o) { return false; } if (o && !o->size) { o->size = sz; } bf->narch = data->file_count; if (!o->info) { o->info = R_NEW0 (RBinInfo); } free (o->info->file); free (o->info->arch); free (o->info->machine); free (o->info->type); o->info->file = strdup (bf->file); o->info->arch = strdup (data->metadata->arch); o->info->machine = strdup (data->metadata->machine); o->info->type = strdup (data->metadata->type); o->info->bits = data->metadata->bits; o->info->has_crypto = bf->o->info->has_crypto; data->loaded = true; return true; } R_API RBinFile *r_bin_file_new_from_fd(RBin *bin, int fd, RBinFileOptions *options) { int file_sz = 0; RBinPlugin *plugin = NULL; RBinFile *bf = r_bin_file_create_append (bin, "-", NULL, 0, file_sz, 0, fd, NULL, false); if (!bf) { return NULL; } int loadaddr = options? options->laddr: 0; int baseaddr = options? options->baddr: 0; // int loadaddr = options? options->laddr: 0; bool binfile_created = true; r_buf_free (bf->buf); bf->buf = r_buf_new_with_io (&bin->iob, fd); if (bin->force) { plugin = r_bin_get_binplugin_by_name (bin, bin->force); } if (!plugin) { if (options && options->plugname) { plugin = r_bin_get_binplugin_by_name (bin, options->plugname); } if (!plugin) { ut8 bytes[1024]; int sz = 1024; r_buf_read_at (bf->buf, 0, bytes, sz); plugin = r_bin_get_binplugin_by_bytes (bin, bytes, sz); if (!plugin) { plugin = r_bin_get_binplugin_any (bin); } } } RBinObject *o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, 0, r_buf_size (bf->buf)); // size is set here because the reported size of the object depends on // if loaded from xtr plugin or partially read if (o && !o->size) { o->size = file_sz; } if (!o) { if (bf && binfile_created) { r_list_delete_data (bin->binfiles, bf); } return NULL; } #if 0 /* WTF */ if (strcmp (plugin->name, "any")) { bf->narch = 1; } #endif /* free unnecessary rbuffer (???) */ return bf; } R_API RBinFile *r_bin_file_new_from_bytes(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, ut64 baseaddr, ut64 loadaddr, int fd, const char *pluginname, const char *xtrname, ut64 offset, bool steal_ptr) { ut8 binfile_created = false; RBinPlugin *plugin = NULL; RBinXtrPlugin *xtr = NULL; RBinObject *o = NULL; if (sz == UT64_MAX) { return NULL; } if (xtrname) { xtr = r_bin_get_xtrplugin_by_name (bin, xtrname); } if (xtr && xtr->check_bytes (bytes, sz)) { return r_bin_file_xtr_load_bytes (bin, xtr, file, bytes, sz, file_sz, baseaddr, loadaddr, 0, fd, rawstr); } RBinFile *bf = r_bin_file_create_append (bin, file, bytes, sz, file_sz, rawstr, fd, xtrname, steal_ptr); if (!bf) { if (!steal_ptr) { // we own the ptr, free on error free ((void*) bytes); } return NULL; } binfile_created = true; if (bin->force) { plugin = r_bin_get_binplugin_by_name (bin, bin->force); } if (!plugin) { if (pluginname) { plugin = r_bin_get_binplugin_by_name (bin, pluginname); } if (!plugin) { plugin = r_bin_get_binplugin_by_bytes (bin, bytes, sz); if (!plugin) { plugin = r_bin_get_binplugin_any (bin); } } } o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, 0, r_buf_size (bf->buf)); // size is set here because the reported size of the object depends on // if loaded from xtr plugin or partially read if (o && !o->size) { o->size = file_sz; } if (!o) { if (bf && binfile_created) { r_list_delete_data (bin->binfiles, bf); } return NULL; } #if 0 /* WTF */ if (strcmp (plugin->name, "any")) { bf->narch = 1; } #endif /* free unnecessary rbuffer (???) */ return bf; } R_API RBinFile *r_bin_file_find_by_arch_bits(RBin *bin, const char *arch, int bits, const char *name) { RListIter *iter; RBinFile *binfile = NULL; RBinXtrData *xtr_data; if (!name || !arch) { return NULL; } r_list_foreach (bin->binfiles, iter, binfile) { RListIter *iter_xtr; if (!binfile->xtr_data) { continue; } // look for sub-bins in Xtr Data and Load if we need to r_list_foreach (binfile->xtr_data, iter_xtr, xtr_data) { if (xtr_data->metadata && xtr_data->metadata->arch) { char *iter_arch = xtr_data->metadata->arch; int iter_bits = xtr_data->metadata->bits; if (bits == iter_bits && !strcmp (iter_arch, arch)) { if (!xtr_data->loaded) { if (!r_bin_file_object_new_from_xtr_data ( bin, binfile, xtr_data->baddr, xtr_data->laddr, xtr_data)) { return NULL; } return binfile; } } } } } return binfile; } R_API RBinObject *r_bin_file_object_find_by_id(RBinFile *binfile, ut32 binobj_id) { RBinObject *obj; RListIter *iter; if (binfile) { r_list_foreach (binfile->objs, iter, obj) { if (obj->id == binobj_id) { return obj; } } } return NULL; } R_API RBinFile *r_bin_file_find_by_object_id(RBin *bin, ut32 binobj_id) { RListIter *iter; RBinFile *binfile; r_list_foreach (bin->binfiles, iter, binfile) { if (r_bin_file_object_find_by_id (binfile, binobj_id)) { return binfile; } } return NULL; } R_API RBinFile *r_bin_file_find_by_id(RBin *bin, ut32 binfile_id) { RBinFile *binfile = NULL; RListIter *iter = NULL; r_list_foreach (bin->binfiles, iter, binfile) { if (binfile->id == binfile_id) { break; } binfile = NULL; } return binfile; } R_API int r_bin_file_object_add(RBinFile *binfile, RBinObject *o) { if (!o) { return false; } r_list_append (binfile->objs, o); r_bin_file_set_cur_binfile_obj (binfile->rbin, binfile, o); return true; } R_API int r_bin_file_delete_all(RBin *bin) { int counter = 0; if (bin) { counter = r_list_length (bin->binfiles); r_list_purge (bin->binfiles); bin->cur = NULL; } return counter; } R_API int r_bin_file_delete(RBin *bin, ut32 bin_fd) { RListIter *iter; RBinFile *bf; RBinFile *cur = r_bin_cur (bin); if (bin && cur) { r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->fd == bin_fd) { if (cur->fd == bin_fd) { //avoiding UaF due to dead reference bin->cur = NULL; } r_list_delete (bin->binfiles, iter); return 1; } } } return 0; } R_API RBinFile *r_bin_file_find_by_fd(RBin *bin, ut32 bin_fd) { RListIter *iter; RBinFile *bf; if (bin) { r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->fd == bin_fd) { return bf; } } } return NULL; } R_API RBinFile *r_bin_file_find_by_name(RBin *bin, const char *name) { RListIter *iter; RBinFile *bf = NULL; if (!bin || !name) { return NULL; } r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->file && !strcmp (bf->file, name)) { break; } bf = NULL; } return bf; } R_API RBinFile *r_bin_file_find_by_name_n(RBin *bin, const char *name, int idx) { RListIter *iter; RBinFile *bf = NULL; int i = 0; if (!bin) { return bf; } r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->file && !strcmp (bf->file, name)) { if (i == idx) { break; } i++; } bf = NULL; } return bf; } R_API int r_bin_file_set_cur_by_fd(RBin *bin, ut32 bin_fd) { RBinFile *bf = r_bin_file_find_by_fd (bin, bin_fd); return r_bin_file_set_cur_binfile (bin, bf); } R_API bool r_bin_file_set_cur_binfile_obj(RBin *bin, RBinFile *bf, RBinObject *obj) { RBinPlugin *plugin = NULL; if (!bin || !bf || !obj) { return false; } bin->file = bf->file; bin->cur = bf; bin->narch = bf->narch; bf->o = obj; plugin = r_bin_file_cur_plugin (bf); if (bin->minstrlen < 1) { bin->minstrlen = plugin? plugin->minstrlen: bin->minstrlen; } return true; } R_API int r_bin_file_set_cur_binfile(RBin *bin, RBinFile *bf) { RBinObject *obj = bf? bf->o: NULL; return r_bin_file_set_cur_binfile_obj (bin, bf, obj); } R_API int r_bin_file_set_cur_by_name(RBin *bin, const char *name) { RBinFile *bf = r_bin_file_find_by_name (bin, name); return r_bin_file_set_cur_binfile (bin, bf); } R_API RBinObject *r_bin_file_object_get_cur(RBinFile *binfile) { return binfile? binfile->o: NULL; } R_API int r_bin_file_cur_set_plugin(RBinFile *binfile, RBinPlugin *plugin) { if (binfile && binfile->o) { binfile->o->plugin = plugin; return true; } return false; } R_API int r_bin_file_deref_by_bind(RBinBind *binb) { RBin *bin = binb? binb->bin: NULL; RBinFile *a = r_bin_cur (bin); return r_bin_file_deref (bin, a); } R_API int r_bin_file_deref(RBin *bin, RBinFile *a) { RBinObject *o = r_bin_cur_object (bin); int res = false; if (a && !o) { //r_list_delete_data (bin->binfiles, a); res = true; } else if (a && o->referenced - 1 < 1) { //r_list_delete_data (bin->binfiles, a); res = true; // not thread safe } else if (o) { o->referenced--; } // it is possible for a file not // to be bound to RBin and RBinFiles // XXX - is this an ok assumption? if (bin) { bin->cur = NULL; } return res; } R_API int r_bin_file_ref_by_bind(RBinBind *binb) { RBin *bin = binb? binb->bin: NULL; RBinFile *a = r_bin_cur (bin); return r_bin_file_ref (bin, a); } R_API int r_bin_file_ref(RBin *bin, RBinFile *a) { RBinObject *o = r_bin_cur_object (bin); if (a && o) { o->referenced--; return true; } return false; } R_API void r_bin_file_free(void /*RBinFile*/ *bf_) { RBinFile *a = bf_; RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (!a) { return; } // Binary format objects are connected to the // RBinObject, so the plugin must destroy the // format data first if (plugin && plugin->destroy) { plugin->destroy (a); } if (a->curxtr && a->curxtr->destroy && a->xtr_obj) { a->curxtr->free_xtr ((void *)(a->xtr_obj)); } r_buf_free (a->buf); // TODO: unset related sdb namespaces if (a && a->sdb_addrinfo) { sdb_free (a->sdb_addrinfo); a->sdb_addrinfo = NULL; } R_FREE (a->file); a->o = NULL; r_list_free (a->objs); r_list_free (a->xtr_data); if (a->id != -1) { r_id_pool_kick_id (a->rbin->file_ids, a->id); } memset (a, 0, sizeof (RBinFile)); free (a); } // This is an unnecessary piece of overengineering R_API RBinFile *r_bin_file_create_append(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, bool steal_ptr) { RBinFile *bf = r_bin_file_new (bin, file, bytes, sz, file_sz, rawstr, fd, xtrname, bin->sdb, steal_ptr); if (bf) { r_list_append (bin->binfiles, bf); } return bf; } // This function populate RBinFile->xtr_data, that information is enough to // create RBinObject when needed using r_bin_file_object_new_from_xtr_data R_API RBinFile *r_bin_file_xtr_load_bytes(RBin *bin, RBinXtrPlugin *xtr, const char *filename, const ut8 *bytes, ut64 sz, ut64 file_sz, ut64 baseaddr, ut64 loadaddr, int idx, int fd, int rawstr) { if (!bin || !bytes) { return NULL; } RBinFile *bf = r_bin_file_find_by_name (bin, filename); if (!bf) { bf = r_bin_file_create_append (bin, filename, bytes, sz, file_sz, rawstr, fd, xtr->name, false); if (!bf) { return NULL; } if (!bin->cur) { bin->cur = bf; } } if (bf->xtr_data) { r_list_free (bf->xtr_data); } if (xtr && bytes) { RList *xtr_data_list = xtr->extractall_from_bytes (bin, bytes, sz); RListIter *iter; RBinXtrData *xtr; //populate xtr_data with baddr and laddr that will be used later on //r_bin_file_object_new_from_xtr_data r_list_foreach (xtr_data_list, iter, xtr) { xtr->baddr = baseaddr? baseaddr : UT64_MAX; xtr->laddr = loadaddr? loadaddr : UT64_MAX; } bf->loadaddr = loadaddr; bf->xtr_data = xtr_data_list ? xtr_data_list : NULL; } return bf; } #define LIMIT_SIZE 0 R_API int r_bin_file_set_bytes(RBinFile *binfile, const ut8 *bytes, ut64 sz, bool steal_ptr) { if (!binfile) { return false; } if (!bytes) { return false; } r_buf_free (binfile->buf); binfile->buf = r_buf_new (); #if LIMIT_SIZE if (sz > 1024 * 1024) { eprintf ("Too big\n"); // TODO: use r_buf_io instead of setbytes all the time to save memory return NULL; } #else if (steal_ptr) { r_buf_set_bytes_steal (binfile->buf, bytes, sz); } else { r_buf_set_bytes (binfile->buf, bytes, sz); } #endif return binfile->buf != NULL; } R_API RBinPlugin *r_bin_file_cur_plugin(RBinFile *binfile) { return binfile && binfile->o? binfile->o->plugin: NULL; } static int is_data_section(RBinFile *a, RBinSection *s) { if (s->has_strings || s->is_data) { return true; } if (s->is_data) { return true; } // Rust return (strstr (s->name, "_const") != NULL); } R_API RList *r_bin_file_get_strings(RBinFile *a, int min, int dump) { RListIter *iter; RBinSection *section; RBinObject *o = a? a->o: NULL; RList *ret; if (dump) { /* dump to stdout, not stored in list */ ret = NULL; } else { ret = r_list_newf (r_bin_string_free); if (!ret) { return NULL; } } if (o && o->sections && !r_list_empty (o->sections) && !a->rawstr) { r_list_foreach (o->sections, iter, section) { if (is_data_section (a, section)) { r_bin_file_get_strings_range (a, ret, min, section->paddr, section->paddr + section->size); } } r_list_foreach (o->sections, iter, section) { RBinString *s; RListIter *iter2; /* load objc/swift strings */ const int bits = (a->o && a->o->info) ? a->o->info->bits : 32; const int cfstr_size = (bits == 64) ? 32 : 16; const int cfstr_offs = (bits == 64) ? 16 : 8; if (strstr (section->name, "__cfstring")) { int i; // XXX do not walk if bin.strings == 0 ut8 *p; for (i = 0; i < section->size; i += cfstr_size) { ut8 buf[32]; if (!r_buf_read_at ( a->buf, section->paddr + i + cfstr_offs, buf, sizeof (buf))) { break; } p = buf; ut64 cfstr_vaddr = section->vaddr + i; ut64 cstr_vaddr = (bits == 64) ? r_read_le64 (p) : r_read_le32 (p); r_list_foreach (ret, iter2, s) { if (s->vaddr == cstr_vaddr) { RBinString *bs = R_NEW0 (RBinString); if (bs) { bs->type = s->type; bs->length = s->length; bs->size = s->size; bs->ordinal = s->ordinal; bs->paddr = bs->vaddr = cfstr_vaddr; bs->string = r_str_newf ("cstr.%s", s->string); r_list_append (ret, bs); } break; } } } } } } else { if (a) { r_bin_file_get_strings_range (a, ret, min, 0, a->size); } } return ret; } R_API void r_bin_file_get_strings_range(RBinFile *bf, RList *list, int min, ut64 from, ut64 to) { RBinPlugin *plugin = r_bin_file_cur_plugin (bf); RBinString *ptr; RListIter *it; if (!bf || !bf->buf) { return; } if (!bf->rawstr) { if (!plugin || !plugin->info) { return; } } if (!min) { min = plugin? plugin->minstrlen: 4; } /* Some plugins return zero, fix it up */ if (!min) { min = 4; } if (min < 0) { return; } if (!to || to > bf->buf->length) { to = r_buf_size (bf->buf); } if (!to) { eprintf ("Empty file with fd %d?\n", bf->buf->fd); return; } if (bf->rawstr != 2) { ut64 size = to - from; // in case of dump ignore here if (bf->rbin->maxstrbuf && size && size > bf->rbin->maxstrbuf) { if (bf->rbin->verbose) { eprintf ("WARNING: bin_strings buffer is too big " "(0x%08" PFMT64x ")." " Use -zzz or set bin.maxstrbuf " "(RABIN2_MAXSTRBUF) in r2 (rabin2)\n", size); } return; } } if (string_scan_range (list, bf, min, from, to, -1) < 0) { return; } r_list_foreach (list, it, ptr) { RBinSection *s = r_bin_get_section_at (bf->o, ptr->paddr, false); if (s) { ptr->vaddr = s->vaddr + (ptr->paddr - s->paddr); } } } R_API ut64 r_bin_file_get_baddr(RBinFile *binfile) { return binfile? r_bin_object_get_baddr (binfile->o): UT64_MAX; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_146_0
crossvul-cpp_data_good_5009_1
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_apps_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "openjpeg.h" #include "convert.h" typedef struct { OPJ_UINT16 bfType; /* 'BM' for Bitmap (19776) */ OPJ_UINT32 bfSize; /* Size of the file */ OPJ_UINT16 bfReserved1; /* Reserved : 0 */ OPJ_UINT16 bfReserved2; /* Reserved : 0 */ OPJ_UINT32 bfOffBits; /* Offset */ } OPJ_BITMAPFILEHEADER; typedef struct { OPJ_UINT32 biSize; /* Size of the structure in bytes */ OPJ_UINT32 biWidth; /* Width of the image in pixels */ OPJ_UINT32 biHeight; /* Heigth of the image in pixels */ OPJ_UINT16 biPlanes; /* 1 */ OPJ_UINT16 biBitCount; /* Number of color bits by pixels */ OPJ_UINT32 biCompression; /* Type of encoding 0: none 1: RLE8 2: RLE4 */ OPJ_UINT32 biSizeImage; /* Size of the image in bytes */ OPJ_UINT32 biXpelsPerMeter; /* Horizontal (X) resolution in pixels/meter */ OPJ_UINT32 biYpelsPerMeter; /* Vertical (Y) resolution in pixels/meter */ OPJ_UINT32 biClrUsed; /* Number of color used in the image (0: ALL) */ OPJ_UINT32 biClrImportant; /* Number of important color (0: ALL) */ OPJ_UINT32 biRedMask; /* Red channel bit mask */ OPJ_UINT32 biGreenMask; /* Green channel bit mask */ OPJ_UINT32 biBlueMask; /* Blue channel bit mask */ OPJ_UINT32 biAlphaMask; /* Alpha channel bit mask */ OPJ_UINT32 biColorSpaceType; /* Color space type */ OPJ_UINT8 biColorSpaceEP[36]; /* Color space end points */ OPJ_UINT32 biRedGamma; /* Red channel gamma */ OPJ_UINT32 biGreenGamma; /* Green channel gamma */ OPJ_UINT32 biBlueGamma; /* Blue channel gamma */ OPJ_UINT32 biIntent; /* Intent */ OPJ_UINT32 biIccProfileData; /* ICC profile data */ OPJ_UINT32 biIccProfileSize; /* ICC profile size */ OPJ_UINT32 biReserved; /* Reserved */ } OPJ_BITMAPINFOHEADER; static void opj_applyLUT8u_8u32s_C1R( OPJ_UINT8 const* pSrc, OPJ_INT32 srcStride, OPJ_INT32* pDst, OPJ_INT32 dstStride, OPJ_UINT8 const* pLUT, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 y; for (y = height; y != 0U; --y) { OPJ_UINT32 x; for(x = 0; x < width; x++) { pDst[x] = (OPJ_INT32)pLUT[pSrc[x]]; } pSrc += srcStride; pDst += dstStride; } } static void opj_applyLUT8u_8u32s_C1P3R( OPJ_UINT8 const* pSrc, OPJ_INT32 srcStride, OPJ_INT32* const* pDst, OPJ_INT32 const* pDstStride, OPJ_UINT8 const* const* pLUT, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 y; OPJ_INT32* pR = pDst[0]; OPJ_INT32* pG = pDst[1]; OPJ_INT32* pB = pDst[2]; OPJ_UINT8 const* pLUT_R = pLUT[0]; OPJ_UINT8 const* pLUT_G = pLUT[1]; OPJ_UINT8 const* pLUT_B = pLUT[2]; for (y = height; y != 0U; --y) { OPJ_UINT32 x; for(x = 0; x < width; x++) { OPJ_UINT8 idx = pSrc[x]; pR[x] = (OPJ_INT32)pLUT_R[idx]; pG[x] = (OPJ_INT32)pLUT_G[idx]; pB[x] = (OPJ_INT32)pLUT_B[idx]; } pSrc += srcStride; pR += pDstStride[0]; pG += pDstStride[1]; pB += pDstStride[2]; } } static void bmp24toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; width = image->comps[0].w; height = image->comps[0].h; index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { image->comps[0].data[index] = (OPJ_INT32)pSrc[3*x+2]; /* R */ image->comps[1].data[index] = (OPJ_INT32)pSrc[3*x+1]; /* G */ image->comps[2].data[index] = (OPJ_INT32)pSrc[3*x+0]; /* B */ index++; } pSrc -= stride; } } static void bmp_mask_get_shift_and_prec(OPJ_UINT32 mask, OPJ_UINT32* shift, OPJ_UINT32* prec) { OPJ_UINT32 l_shift, l_prec; l_shift = l_prec = 0U; if (mask != 0U) { while ((mask & 1U) == 0U) { mask >>= 1; l_shift++; } while (mask & 1U) { mask >>= 1; l_prec++; } } *shift = l_shift; *prec = l_prec; } static void bmpmask32toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask, OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; OPJ_BOOL hasAlpha; OPJ_UINT32 redShift, redPrec; OPJ_UINT32 greenShift, greenPrec; OPJ_UINT32 blueShift, bluePrec; OPJ_UINT32 alphaShift, alphaPrec; width = image->comps[0].w; height = image->comps[0].h; hasAlpha = image->numcomps > 3U; bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec); bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec); bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec); bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec); image->comps[0].bpp = redPrec; image->comps[0].prec = redPrec; image->comps[1].bpp = greenPrec; image->comps[1].prec = greenPrec; image->comps[2].bpp = bluePrec; image->comps[2].prec = bluePrec; if (hasAlpha) { image->comps[3].bpp = alphaPrec; image->comps[3].prec = alphaPrec; } index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { OPJ_UINT32 value = 0U; value |= ((OPJ_UINT32)pSrc[4*x+0]) << 0; value |= ((OPJ_UINT32)pSrc[4*x+1]) << 8; value |= ((OPJ_UINT32)pSrc[4*x+2]) << 16; value |= ((OPJ_UINT32)pSrc[4*x+3]) << 24; image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >> redShift); /* R */ image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >> greenShift); /* G */ image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >> blueShift); /* B */ if (hasAlpha) { image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >> alphaShift); /* A */ } index++; } pSrc -= stride; } } static void bmpmask16toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask, OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; OPJ_BOOL hasAlpha; OPJ_UINT32 redShift, redPrec; OPJ_UINT32 greenShift, greenPrec; OPJ_UINT32 blueShift, bluePrec; OPJ_UINT32 alphaShift, alphaPrec; width = image->comps[0].w; height = image->comps[0].h; hasAlpha = image->numcomps > 3U; bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec); bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec); bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec); bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec); image->comps[0].bpp = redPrec; image->comps[0].prec = redPrec; image->comps[1].bpp = greenPrec; image->comps[1].prec = greenPrec; image->comps[2].bpp = bluePrec; image->comps[2].prec = bluePrec; if (hasAlpha) { image->comps[3].bpp = alphaPrec; image->comps[3].prec = alphaPrec; } index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { OPJ_UINT32 value = 0U; value |= ((OPJ_UINT32)pSrc[2*x+0]) << 0; value |= ((OPJ_UINT32)pSrc[2*x+1]) << 8; image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >> redShift); /* R */ image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >> greenShift); /* G */ image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >> blueShift); /* B */ if (hasAlpha) { image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >> alphaShift); /* A */ } index++; } pSrc -= stride; } } static opj_image_t* bmp8toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT8 const* const* pLUT) { OPJ_UINT32 width, height; const OPJ_UINT8 *pSrc = NULL; width = image->comps[0].w; height = image->comps[0].h; pSrc = pData + (height - 1U) * stride; if (image->numcomps == 1U) { opj_applyLUT8u_8u32s_C1R(pSrc, -(OPJ_INT32)stride, image->comps[0].data, (OPJ_INT32)width, pLUT[0], width, height); } else { OPJ_INT32* pDst[3]; OPJ_INT32 pDstStride[3]; pDst[0] = image->comps[0].data; pDst[1] = image->comps[1].data; pDst[2] = image->comps[2].data; pDstStride[0] = (OPJ_INT32)width; pDstStride[1] = (OPJ_INT32)width; pDstStride[2] = (OPJ_INT32)width; opj_applyLUT8u_8u32s_C1P3R(pSrc, -(OPJ_INT32)stride, pDst, pDstStride, pLUT, width, height); } return image; } static OPJ_BOOL bmp_read_file_header(FILE* IN, OPJ_BITMAPFILEHEADER* header) { header->bfType = (OPJ_UINT16)getc(IN); header->bfType |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if (header->bfType != 19778) { fprintf(stderr,"Error, not a BMP file!\n"); return OPJ_FALSE; } /* FILE HEADER */ /* ------------- */ header->bfSize = (OPJ_UINT32)getc(IN); header->bfSize |= (OPJ_UINT32)getc(IN) << 8; header->bfSize |= (OPJ_UINT32)getc(IN) << 16; header->bfSize |= (OPJ_UINT32)getc(IN) << 24; header->bfReserved1 = (OPJ_UINT16)getc(IN); header->bfReserved1 |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->bfReserved2 = (OPJ_UINT16)getc(IN); header->bfReserved2 |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->bfOffBits = (OPJ_UINT32)getc(IN); header->bfOffBits |= (OPJ_UINT32)getc(IN) << 8; header->bfOffBits |= (OPJ_UINT32)getc(IN) << 16; header->bfOffBits |= (OPJ_UINT32)getc(IN) << 24; return OPJ_TRUE; } static OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header) { memset(header, 0, sizeof(*header)); /* INFO HEADER */ /* ------------- */ header->biSize = (OPJ_UINT32)getc(IN); header->biSize |= (OPJ_UINT32)getc(IN) << 8; header->biSize |= (OPJ_UINT32)getc(IN) << 16; header->biSize |= (OPJ_UINT32)getc(IN) << 24; switch (header->biSize) { case 12U: /* BITMAPCOREHEADER */ case 40U: /* BITMAPINFOHEADER */ case 52U: /* BITMAPV2INFOHEADER */ case 56U: /* BITMAPV3INFOHEADER */ case 108U: /* BITMAPV4HEADER */ case 124U: /* BITMAPV5HEADER */ break; default: fprintf(stderr,"Error, unknown BMP header size %d\n", header->biSize); return OPJ_FALSE; } header->biWidth = (OPJ_UINT32)getc(IN); header->biWidth |= (OPJ_UINT32)getc(IN) << 8; header->biWidth |= (OPJ_UINT32)getc(IN) << 16; header->biWidth |= (OPJ_UINT32)getc(IN) << 24; header->biHeight = (OPJ_UINT32)getc(IN); header->biHeight |= (OPJ_UINT32)getc(IN) << 8; header->biHeight |= (OPJ_UINT32)getc(IN) << 16; header->biHeight |= (OPJ_UINT32)getc(IN) << 24; header->biPlanes = (OPJ_UINT16)getc(IN); header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->biBitCount = (OPJ_UINT16)getc(IN); header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if(header->biSize >= 40U) { header->biCompression = (OPJ_UINT32)getc(IN); header->biCompression |= (OPJ_UINT32)getc(IN) << 8; header->biCompression |= (OPJ_UINT32)getc(IN) << 16; header->biCompression |= (OPJ_UINT32)getc(IN) << 24; header->biSizeImage = (OPJ_UINT32)getc(IN); header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24; header->biXpelsPerMeter = (OPJ_UINT32)getc(IN); header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biYpelsPerMeter = (OPJ_UINT32)getc(IN); header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biClrUsed = (OPJ_UINT32)getc(IN); header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24; header->biClrImportant = (OPJ_UINT32)getc(IN); header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24; } if(header->biSize >= 56U) { header->biRedMask = (OPJ_UINT32)getc(IN); header->biRedMask |= (OPJ_UINT32)getc(IN) << 8; header->biRedMask |= (OPJ_UINT32)getc(IN) << 16; header->biRedMask |= (OPJ_UINT32)getc(IN) << 24; header->biGreenMask = (OPJ_UINT32)getc(IN); header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24; header->biBlueMask = (OPJ_UINT32)getc(IN); header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24; header->biAlphaMask = (OPJ_UINT32)getc(IN); header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24; } if(header->biSize >= 108U) { header->biColorSpaceType = (OPJ_UINT32)getc(IN); header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24; if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP), IN) != sizeof(header->biColorSpaceEP)) { fprintf(stderr,"Error, can't read BMP header\n"); return OPJ_FALSE; } header->biRedGamma = (OPJ_UINT32)getc(IN); header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24; header->biGreenGamma = (OPJ_UINT32)getc(IN); header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24; header->biBlueGamma = (OPJ_UINT32)getc(IN); header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24; } if(header->biSize >= 124U) { header->biIntent = (OPJ_UINT32)getc(IN); header->biIntent |= (OPJ_UINT32)getc(IN) << 8; header->biIntent |= (OPJ_UINT32)getc(IN) << 16; header->biIntent |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileData = (OPJ_UINT32)getc(IN); header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileSize = (OPJ_UINT32)getc(IN); header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24; header->biReserved = (OPJ_UINT32)getc(IN); header->biReserved |= (OPJ_UINT32)getc(IN) << 8; header->biReserved |= (OPJ_UINT32)getc(IN) << 16; header->biReserved |= (OPJ_UINT32)getc(IN) << 24; } return OPJ_TRUE; } static OPJ_BOOL bmp_read_raw_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_ARG_NOT_USED(width); if ( fread(pData, sizeof(OPJ_UINT8), stride * height, IN) != (stride * height) ) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while (y < height) { int c = getc(IN); if (c) { int j; OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = c1; } } else { c = getc(IN); if (c == 0x00) { /* EOL */ x = 0; ++y; pix = pData + y * stride + x; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); x += (OPJ_UINT32)c; c = getc(IN); y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else /* 03 .. 255 */ { int j; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); *pix = c1; } if ((OPJ_UINT32)c & 1U) { /* skip padding byte */ getc(IN); } } } }/* while() */ return OPJ_TRUE; } static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while(y < height) { int c = getc(IN); if(c == EOF) break; if(c) {/* encoded mode */ int j; OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = (OPJ_UINT8)((j&1) ? (c1 & 0x0fU) : ((c1>>4)&0x0fU)); } } else { /* absolute mode */ c = getc(IN); if(c == EOF) break; if(c == 0x00) { /* EOL */ x = 0; y++; pix = pData + y * stride; } else if(c == 0x01) { /* EOP */ break; } else if(c == 0x02) { /* MOVE by dxdy */ c = getc(IN); x += (OPJ_UINT32)c; c = getc(IN); y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 : absolute mode */ int j; OPJ_UINT8 c1 = 0U; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { if((j&1) == 0) { c1 = (OPJ_UINT8)getc(IN); } *pix = (OPJ_UINT8)((j&1) ? (c1 & 0x0fU) : ((c1>>4)&0x0fU)); } if(((c&3) == 1) || ((c&3) == 2)) { /* skip padding byte */ getc(IN); } } } } /* while(y < height) */ return OPJ_TRUE; } opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) { opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256]; OPJ_UINT8 const* pLUT[3]; opj_image_t * image = NULL; FILE *IN; OPJ_BITMAPFILEHEADER File_h; OPJ_BITMAPINFOHEADER Info_h; OPJ_UINT32 i, palette_len, numcmpts = 1U; OPJ_BOOL l_result = OPJ_FALSE; OPJ_UINT8* pData = NULL; OPJ_UINT32 stride; pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B; IN = fopen(filename, "rb"); if (!IN) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return NULL; } if (!bmp_read_file_header(IN, &File_h)) { fclose(IN); return NULL; } if (!bmp_read_info_header(IN, &Info_h)) { fclose(IN); return NULL; } /* Load palette */ if (Info_h.biBitCount <= 8U) { memset(&lut_R[0], 0, sizeof(lut_R)); memset(&lut_G[0], 0, sizeof(lut_G)); memset(&lut_B[0], 0, sizeof(lut_B)); palette_len = Info_h.biClrUsed; if((palette_len == 0U) && (Info_h.biBitCount <= 8U)) { palette_len = (1U << Info_h.biBitCount); } if (palette_len > 256U) { palette_len = 256U; } if (palette_len > 0U) { OPJ_UINT8 has_color = 0U; for (i = 0U; i < palette_len; i++) { lut_B[i] = (OPJ_UINT8)getc(IN); lut_G[i] = (OPJ_UINT8)getc(IN); lut_R[i] = (OPJ_UINT8)getc(IN); (void)getc(IN); /* padding */ has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]); } if(has_color) { numcmpts = 3U; } } } else { numcmpts = 3U; if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) { numcmpts++; } } stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */ if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */ stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U; } pData = (OPJ_UINT8 *) calloc(1, stride * Info_h.biHeight * sizeof(OPJ_UINT8)); if (pData == NULL) { fclose(IN); return NULL; } /* Place the cursor at the beginning of the image information */ fseek(IN, 0, SEEK_SET); fseek(IN, (long)File_h.bfOffBits, SEEK_SET); switch (Info_h.biCompression) { case 0: case 3: /* read raw data */ l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 1: /* read rle8 data */ l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 2: /* read rle4 data */ l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; default: fprintf(stderr, "Unsupported BMP compression\n"); l_result = OPJ_FALSE; break; } if (!l_result) { free(pData); fclose(IN); return NULL; } /* create the image */ memset(&cmptparm[0], 0, sizeof(cmptparm)); for(i = 0; i < 4U; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy; cmptparm[i].w = Info_h.biWidth; cmptparm[i].h = Info_h.biHeight; } image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB); if(!image) { fclose(IN); free(pData); return NULL; } if (numcmpts == 4U) { image->comps[3].alpha = 1; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)parameters->subsampling_dx + 1U; image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)parameters->subsampling_dy + 1U; /* Read the data */ if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */ bmp24toimage(pData, stride, image); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/ bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */ } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */ bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U); } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */ bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */ bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */ if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) { Info_h.biRedMask = 0xF800U; Info_h.biGreenMask = 0x07E0U; Info_h.biBlueMask = 0x001FU; } bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else { opj_image_destroy(image); image = NULL; fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount); } free(pData); fclose(IN); return image; } int imagetobmp(opj_image_t * image, const char *outfile) { int w, h; int i, pad; FILE *fdest = NULL; int adjustR, adjustG, adjustB; if (image->comps[0].prec < 8) { fprintf(stderr, "Unsupported number of components: %d\n", image->comps[0].prec); return 1; } if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx && image->comps[1].dx == image->comps[2].dx && image->comps[0].dy == image->comps[1].dy && image->comps[1].dy == image->comps[2].dy && image->comps[0].prec == image->comps[1].prec && image->comps[1].prec == image->comps[2].prec) { /* -->> -->> -->> -->> 24 bits color <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (3 * h * w + 3 * h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); } else adjustR = 0; if (image->comps[1].prec > 8) { adjustG = (int)image->comps[1].prec - 8; printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec); } else adjustG = 0; if (image->comps[2].prec > 8) { adjustB = (int)image->comps[2].prec - 8; printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec); } else adjustB = 0; for (i = 0; i < w * h; i++) { OPJ_UINT8 rc, gc, bc; int r, g, b; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; rc = (OPJ_UINT8)r; g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); g = ((g >> adjustG)+((g >> (adjustG-1))%2)); if(g > 255) g = 255; else if(g < 0) g = 0; gc = (OPJ_UINT8)g; b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); b = ((b >> adjustB)+((b >> (adjustB-1))%2)); if(b > 255) b = 255; else if(b < 0) b = 0; bc = (OPJ_UINT8)b; fprintf(fdest, "%c%c%c", bc, gc, rc); if ((i + 1) % w == 0) { for (pad = ((3 * w) % 4) ? (4 - (3 * w) % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } else { /* Gray-scale */ /* -->> -->> -->> -->> 8 bits non code (Gray scale) <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + 54 + 1024 + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, ((54 + 1024) >> 16) & 0xff, ((54 + 1024) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); }else adjustR = 0; for (i = 0; i < 256; i++) { fprintf(fdest, "%c%c%c%c", i, i, i, 0); } for (i = 0; i < w * h; i++) { int r; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; fprintf(fdest, "%c", (OPJ_UINT8)r); if ((i + 1) % w == 0) { for (pad = (w % 4) ? (4 - w % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5009_1
crossvul-cpp_data_bad_3255_1
/* * NET An implementation of the SOCKET network access protocol. * * Version: @(#)socket.c 1.1.93 18/02/95 * * Authors: Orest Zborowski, <obz@Kodak.COM> * Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * * Fixes: * Anonymous : NOTSOCK/BADF cleanup. Error fix in * shutdown() * Alan Cox : verify_area() fixes * Alan Cox : Removed DDI * Jonathan Kamens : SOCK_DGRAM reconnect bug * Alan Cox : Moved a load of checks to the very * top level. * Alan Cox : Move address structures to/from user * mode above the protocol layers. * Rob Janssen : Allow 0 length sends. * Alan Cox : Asynchronous I/O support (cribbed from the * tty drivers). * Niibe Yutaka : Asynchronous I/O for writes (4.4BSD style) * Jeff Uphoff : Made max number of sockets command-line * configurable. * Matti Aarnio : Made the number of sockets dynamic, * to be allocated when needed, and mr. * Uphoff's max is used as max to be * allowed to allocate. * Linus : Argh. removed all the socket allocation * altogether: it's in the inode now. * Alan Cox : Made sock_alloc()/sock_release() public * for NetROM and future kernel nfsd type * stuff. * Alan Cox : sendmsg/recvmsg basics. * Tom Dyas : Export net symbols. * Marcin Dalecki : Fixed problems with CONFIG_NET="n". * Alan Cox : Added thread locking to sys_* calls * for sockets. May have errors at the * moment. * Kevin Buhr : Fixed the dumb errors in the above. * Andi Kleen : Some small cleanups, optimizations, * and fixed a copy_from_user() bug. * Tigran Aivazian : sys_send(args) calls sys_sendto(args, NULL, 0) * Tigran Aivazian : Made listen(2) backlog sanity checks * protocol-independent * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * * This module is effectively the top level interface to the BSD socket * paradigm. * * Based upon Swansea University Computer Society NET3.039 */ #include <linux/mm.h> #include <linux/socket.h> #include <linux/file.h> #include <linux/net.h> #include <linux/interrupt.h> #include <linux/thread_info.h> #include <linux/rcupdate.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/mutex.h> #include <linux/if_bridge.h> #include <linux/if_frad.h> #include <linux/if_vlan.h> #include <linux/ptp_classify.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/highmem.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/compat.h> #include <linux/kmod.h> #include <linux/audit.h> #include <linux/wireless.h> #include <linux/nsproxy.h> #include <linux/magic.h> #include <linux/slab.h> #include <linux/xattr.h> #include <linux/uaccess.h> #include <asm/unistd.h> #include <net/compat.h> #include <net/wext.h> #include <net/cls_cgroup.h> #include <net/sock.h> #include <linux/netfilter.h> #include <linux/if_tun.h> #include <linux/ipv6_route.h> #include <linux/route.h> #include <linux/sockios.h> #include <linux/atalk.h> #include <net/busy_poll.h> #include <linux/errqueue.h> #ifdef CONFIG_NET_RX_BUSY_POLL unsigned int sysctl_net_busy_read __read_mostly; unsigned int sysctl_net_busy_poll __read_mostly; #endif static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to); static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from); static int sock_mmap(struct file *file, struct vm_area_struct *vma); static int sock_close(struct inode *inode, struct file *file); static unsigned int sock_poll(struct file *file, struct poll_table_struct *wait); static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #ifdef CONFIG_COMPAT static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #endif static int sock_fasync(int fd, struct file *filp, int on); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more); static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags); /* * Socket files have a set of 'special' operations as well as the generic file ones. These don't appear * in the operation structures but are done directly via the socketcall() multiplexor. */ static const struct file_operations socket_file_ops = { .owner = THIS_MODULE, .llseek = no_llseek, .read_iter = sock_read_iter, .write_iter = sock_write_iter, .poll = sock_poll, .unlocked_ioctl = sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_sock_ioctl, #endif .mmap = sock_mmap, .release = sock_close, .fasync = sock_fasync, .sendpage = sock_sendpage, .splice_write = generic_splice_sendpage, .splice_read = sock_splice_read, }; /* * The protocol list. Each protocol is registered in here. */ static DEFINE_SPINLOCK(net_family_lock); static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly; /* * Statistics counters of the socket lists */ static DEFINE_PER_CPU(int, sockets_in_use); /* * Support routines. * Move socket addresses back and forth across the kernel/user * divide and look after the messy bits. */ /** * move_addr_to_kernel - copy a socket address into kernel space * @uaddr: Address in user space * @kaddr: Address in kernel space * @ulen: Length in user space * * The address is copied into kernel space. If the provided address is * too long an error code of -EINVAL is returned. If the copy gives * invalid addresses -EFAULT is returned. On a success 0 is returned. */ int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr) { if (ulen < 0 || ulen > sizeof(struct sockaddr_storage)) return -EINVAL; if (ulen == 0) return 0; if (copy_from_user(kaddr, uaddr, ulen)) return -EFAULT; return audit_sockaddr(ulen, kaddr); } /** * move_addr_to_user - copy an address to user space * @kaddr: kernel space address * @klen: length of address in kernel * @uaddr: user space address * @ulen: pointer to user length field * * The value pointed to by ulen on entry is the buffer length available. * This is overwritten with the buffer space used. -EINVAL is returned * if an overlong buffer is specified or a negative buffer size. -EFAULT * is returned if either the buffer or the length field are not * accessible. * After copying the data up to the limit the user specifies, the true * length of the data is written over the length limit the user * specified. Zero is returned for a success. */ static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen, void __user *uaddr, int __user *ulen) { int err; int len; BUG_ON(klen > sizeof(struct sockaddr_storage)); err = get_user(len, ulen); if (err) return err; if (len > klen) len = klen; if (len < 0) return -EINVAL; if (len) { if (audit_sockaddr(klen, kaddr)) return -ENOMEM; if (copy_to_user(uaddr, kaddr, len)) return -EFAULT; } /* * "fromlen shall refer to the value before truncation.." * 1003.1g */ return __put_user(klen, ulen); } static struct kmem_cache *sock_inode_cachep __read_mostly; static struct inode *sock_alloc_inode(struct super_block *sb) { struct socket_alloc *ei; struct socket_wq *wq; ei = kmem_cache_alloc(sock_inode_cachep, GFP_KERNEL); if (!ei) return NULL; wq = kmalloc(sizeof(*wq), GFP_KERNEL); if (!wq) { kmem_cache_free(sock_inode_cachep, ei); return NULL; } init_waitqueue_head(&wq->wait); wq->fasync_list = NULL; wq->flags = 0; RCU_INIT_POINTER(ei->socket.wq, wq); ei->socket.state = SS_UNCONNECTED; ei->socket.flags = 0; ei->socket.ops = NULL; ei->socket.sk = NULL; ei->socket.file = NULL; return &ei->vfs_inode; } static void sock_destroy_inode(struct inode *inode) { struct socket_alloc *ei; struct socket_wq *wq; ei = container_of(inode, struct socket_alloc, vfs_inode); wq = rcu_dereference_protected(ei->socket.wq, 1); kfree_rcu(wq, rcu); kmem_cache_free(sock_inode_cachep, ei); } static void init_once(void *foo) { struct socket_alloc *ei = (struct socket_alloc *)foo; inode_init_once(&ei->vfs_inode); } static void init_inodecache(void) { sock_inode_cachep = kmem_cache_create("sock_inode_cache", sizeof(struct socket_alloc), 0, (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT), init_once); BUG_ON(sock_inode_cachep == NULL); } static const struct super_operations sockfs_ops = { .alloc_inode = sock_alloc_inode, .destroy_inode = sock_destroy_inode, .statfs = simple_statfs, }; /* * sockfs_dname() is called from d_path(). */ static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "socket:[%lu]", d_inode(dentry)->i_ino); } static const struct dentry_operations sockfs_dentry_operations = { .d_dname = sockfs_dname, }; static int sockfs_xattr_get(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *suffix, void *value, size_t size) { if (value) { if (dentry->d_name.len + 1 > size) return -ERANGE; memcpy(value, dentry->d_name.name, dentry->d_name.len + 1); } return dentry->d_name.len + 1; } #define XATTR_SOCKPROTONAME_SUFFIX "sockprotoname" #define XATTR_NAME_SOCKPROTONAME (XATTR_SYSTEM_PREFIX XATTR_SOCKPROTONAME_SUFFIX) #define XATTR_NAME_SOCKPROTONAME_LEN (sizeof(XATTR_NAME_SOCKPROTONAME)-1) static const struct xattr_handler sockfs_xattr_handler = { .name = XATTR_NAME_SOCKPROTONAME, .get = sockfs_xattr_get, }; static int sockfs_security_xattr_set(const struct xattr_handler *handler, struct dentry *dentry, struct inode *inode, const char *suffix, const void *value, size_t size, int flags) { /* Handled by LSM. */ return -EAGAIN; } static const struct xattr_handler sockfs_security_xattr_handler = { .prefix = XATTR_SECURITY_PREFIX, .set = sockfs_security_xattr_set, }; static const struct xattr_handler *sockfs_xattr_handlers[] = { &sockfs_xattr_handler, &sockfs_security_xattr_handler, NULL }; static struct dentry *sockfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo_xattr(fs_type, "socket:", &sockfs_ops, sockfs_xattr_handlers, &sockfs_dentry_operations, SOCKFS_MAGIC); } static struct vfsmount *sock_mnt __read_mostly; static struct file_system_type sock_fs_type = { .name = "sockfs", .mount = sockfs_mount, .kill_sb = kill_anon_super, }; /* * Obtains the first available file descriptor and sets it up for use. * * These functions create file structures and maps them to fd space * of the current process. On success it returns file descriptor * and file struct implicitly stored in sock->file. * Note that another thread may close file descriptor before we return * from this function. We use the fact that now we do not refer * to socket after mapping. If one day we will need it, this * function will increment ref. count on file by 1. * * In any case returned fd MAY BE not valid! * This race condition is unavoidable * with shared fd spaces, we cannot solve it inside kernel, * but we take care of internal coherence yet. */ struct file *sock_alloc_file(struct socket *sock, int flags, const char *dname) { struct qstr name = { .name = "" }; struct path path; struct file *file; if (dname) { name.name = dname; name.len = strlen(name.name); } else if (sock->sk) { name.name = sock->sk->sk_prot_creator->name; name.len = strlen(name.name); } path.dentry = d_alloc_pseudo(sock_mnt->mnt_sb, &name); if (unlikely(!path.dentry)) return ERR_PTR(-ENOMEM); path.mnt = mntget(sock_mnt); d_instantiate(path.dentry, SOCK_INODE(sock)); file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &socket_file_ops); if (IS_ERR(file)) { /* drop dentry, keep inode */ ihold(d_inode(path.dentry)); path_put(&path); return file; } sock->file = file; file->f_flags = O_RDWR | (flags & O_NONBLOCK); file->private_data = sock; return file; } EXPORT_SYMBOL(sock_alloc_file); static int sock_map_fd(struct socket *sock, int flags) { struct file *newfile; int fd = get_unused_fd_flags(flags); if (unlikely(fd < 0)) return fd; newfile = sock_alloc_file(sock, flags, NULL); if (likely(!IS_ERR(newfile))) { fd_install(fd, newfile); return fd; } put_unused_fd(fd); return PTR_ERR(newfile); } struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; } EXPORT_SYMBOL(sock_from_file); /** * sockfd_lookup - Go from a file number to its socket slot * @fd: file handle * @err: pointer to an error code return * * The file handle passed in is locked and the socket it is bound * too is returned. If an error occurs the err pointer is overwritten * with a negative errno code and NULL is returned. The function checks * for both invalid handles and passing a handle which is not a socket. * * On a success the socket object pointer is returned. */ struct socket *sockfd_lookup(int fd, int *err) { struct file *file; struct socket *sock; file = fget(fd); if (!file) { *err = -EBADF; return NULL; } sock = sock_from_file(file, err); if (!sock) fput(file); return sock; } EXPORT_SYMBOL(sockfd_lookup); static struct socket *sockfd_lookup_light(int fd, int *err, int *fput_needed) { struct fd f = fdget(fd); struct socket *sock; *err = -EBADF; if (f.file) { sock = sock_from_file(f.file, err); if (likely(sock)) { *fput_needed = f.flags; return sock; } fdput(f); } return NULL; } static ssize_t sockfs_listxattr(struct dentry *dentry, char *buffer, size_t size) { ssize_t len; ssize_t used = 0; len = security_inode_listsecurity(d_inode(dentry), buffer, size); if (len < 0) return len; used += len; if (buffer) { if (size < used) return -ERANGE; buffer += len; } len = (XATTR_NAME_SOCKPROTONAME_LEN + 1); used += len; if (buffer) { if (size < used) return -ERANGE; memcpy(buffer, XATTR_NAME_SOCKPROTONAME, len); buffer += len; } return used; } static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr) { int err = simple_setattr(dentry, iattr); if (!err && (iattr->ia_valid & ATTR_UID)) { struct socket *sock = SOCKET_I(d_inode(dentry)); sock->sk->sk_uid = iattr->ia_uid; } return err; } static const struct inode_operations sockfs_inode_ops = { .listxattr = sockfs_listxattr, .setattr = sockfs_setattr, }; /** * sock_alloc - allocate a socket * * Allocate a new inode and socket object. The two are bound together * and initialised. The socket is then returned. If we are out of inodes * NULL is returned. */ struct socket *sock_alloc(void) { struct inode *inode; struct socket *sock; inode = new_inode_pseudo(sock_mnt->mnt_sb); if (!inode) return NULL; sock = SOCKET_I(inode); kmemcheck_annotate_bitfield(sock, type); inode->i_ino = get_next_ino(); inode->i_mode = S_IFSOCK | S_IRWXUGO; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); inode->i_op = &sockfs_inode_ops; this_cpu_add(sockets_in_use, 1); return sock; } EXPORT_SYMBOL(sock_alloc); /** * sock_release - close a socket * @sock: socket to close * * The socket is released from the protocol stack if it has a release * callback, and the inode is then released if the socket is bound to * an inode not a file. */ void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) pr_err("%s: fasync list not empty!\n", __func__); this_cpu_sub(sockets_in_use, 1); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } EXPORT_SYMBOL(sock_release); void __sock_tx_timestamp(__u16 tsflags, __u8 *tx_flags) { u8 flags = *tx_flags; if (tsflags & SOF_TIMESTAMPING_TX_HARDWARE) flags |= SKBTX_HW_TSTAMP; if (tsflags & SOF_TIMESTAMPING_TX_SOFTWARE) flags |= SKBTX_SW_TSTAMP; if (tsflags & SOF_TIMESTAMPING_TX_SCHED) flags |= SKBTX_SCHED_TSTAMP; *tx_flags = flags; } EXPORT_SYMBOL(__sock_tx_timestamp); static inline int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg) { int ret = sock->ops->sendmsg(sock, msg, msg_data_left(msg)); BUG_ON(ret == -EIOCBQUEUED); return ret; } int sock_sendmsg(struct socket *sock, struct msghdr *msg) { int err = security_socket_sendmsg(sock, msg, msg_data_left(msg)); return err ?: sock_sendmsg_nosec(sock, msg); } EXPORT_SYMBOL(sock_sendmsg); int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size) { iov_iter_kvec(&msg->msg_iter, WRITE | ITER_KVEC, vec, num, size); return sock_sendmsg(sock, msg); } EXPORT_SYMBOL(kernel_sendmsg); /* * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP) */ void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } EXPORT_SYMBOL_GPL(__sock_recv_timestamp); void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int ack; if (!sock_flag(sk, SOCK_WIFI_STATUS)) return; if (!skb->wifi_acked_valid) return; ack = skb->wifi_acked; put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack); } EXPORT_SYMBOL_GPL(__sock_recv_wifi_status); static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && SOCK_SKB_CB(skb)->dropcount) put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL, sizeof(__u32), &SOCK_SKB_CB(skb)->dropcount); } void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { sock_recv_timestamp(msg, sk, skb); sock_recv_drops(msg, sk, skb); } EXPORT_SYMBOL_GPL(__sock_recv_ts_and_drops); static inline int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg, int flags) { return sock->ops->recvmsg(sock, msg, msg_data_left(msg), flags); } int sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags) { int err = security_socket_recvmsg(sock, msg, msg_data_left(msg), flags); return err ?: sock_recvmsg_nosec(sock, msg, flags); } EXPORT_SYMBOL(sock_recvmsg); /** * kernel_recvmsg - Receive a message from a socket (kernel space) * @sock: The socket to receive the message from * @msg: Received message * @vec: Input s/g array for message data * @num: Size of input s/g array * @size: Number of bytes to read * @flags: Message flags (MSG_DONTWAIT, etc...) * * On return the msg structure contains the scatter/gather array passed in the * vec argument. The array is modified so that it consists of the unfilled * portion of the original array. * * The returned value is the total number of bytes received, or an error. */ int kernel_recvmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size, int flags) { mm_segment_t oldfs = get_fs(); int result; iov_iter_kvec(&msg->msg_iter, READ | ITER_KVEC, vec, num, size); set_fs(KERNEL_DS); result = sock_recvmsg(sock, msg, flags); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_recvmsg); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more) { struct socket *sock; int flags; sock = file->private_data; flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; /* more is a combination of MSG_MORE and MSG_SENDPAGE_NOTLAST */ flags |= more; return kernel_sendpage(sock, page, offset, size, flags); } static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct socket *sock = file->private_data; if (unlikely(!sock->ops->splice_read)) return -EINVAL; return sock->ops->splice_read(sock, ppos, pipe, len, flags); } static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *to, .msg_iocb = iocb}; ssize_t res; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (iocb->ki_pos != 0) return -ESPIPE; if (!iov_iter_count(to)) /* Match SYS5 behaviour */ return 0; res = sock_recvmsg(sock, &msg, msg.msg_flags); *to = msg.msg_iter; return res; } static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct socket *sock = file->private_data; struct msghdr msg = {.msg_iter = *from, .msg_iocb = iocb}; ssize_t res; if (iocb->ki_pos != 0) return -ESPIPE; if (file->f_flags & O_NONBLOCK) msg.msg_flags = MSG_DONTWAIT; if (sock->type == SOCK_SEQPACKET) msg.msg_flags |= MSG_EOR; res = sock_sendmsg(sock, &msg); *from = msg.msg_iter; return res; } /* * Atomic setting of ioctl hooks to avoid race * with module unload. */ static DEFINE_MUTEX(br_ioctl_mutex); static int (*br_ioctl_hook) (struct net *, unsigned int cmd, void __user *arg); void brioctl_set(int (*hook) (struct net *, unsigned int, void __user *)) { mutex_lock(&br_ioctl_mutex); br_ioctl_hook = hook; mutex_unlock(&br_ioctl_mutex); } EXPORT_SYMBOL(brioctl_set); static DEFINE_MUTEX(vlan_ioctl_mutex); static int (*vlan_ioctl_hook) (struct net *, void __user *arg); void vlan_ioctl_set(int (*hook) (struct net *, void __user *)) { mutex_lock(&vlan_ioctl_mutex); vlan_ioctl_hook = hook; mutex_unlock(&vlan_ioctl_mutex); } EXPORT_SYMBOL(vlan_ioctl_set); static DEFINE_MUTEX(dlci_ioctl_mutex); static int (*dlci_ioctl_hook) (unsigned int, void __user *); void dlci_ioctl_set(int (*hook) (unsigned int, void __user *)) { mutex_lock(&dlci_ioctl_mutex); dlci_ioctl_hook = hook; mutex_unlock(&dlci_ioctl_mutex); } EXPORT_SYMBOL(dlci_ioctl_set); static long sock_do_ioctl(struct net *net, struct socket *sock, unsigned int cmd, unsigned long arg) { int err; void __user *argp = (void __user *)arg; err = sock->ops->ioctl(sock, cmd, arg); /* * If this ioctl is unknown try to hand it down * to the NIC driver. */ if (err == -ENOIOCTLCMD) err = dev_ioctl(net, cmd, argp); return err; } /* * With an ioctl, arg may well be a user mode pointer, but we don't know * what to do with it - that's up to the protocol still. */ static struct ns_common *get_net_ns(struct ns_common *ns) { return &get_net(container_of(ns, struct net, ns))->ns; } static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) { struct socket *sock; struct sock *sk; void __user *argp = (void __user *)arg; int pid, err; struct net *net; sock = file->private_data; sk = sock->sk; net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) { err = dev_ioctl(net, cmd, argp); } else #ifdef CONFIG_WEXT_CORE if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) { err = dev_ioctl(net, cmd, argp); } else #endif switch (cmd) { case FIOSETOWN: case SIOCSPGRP: err = -EFAULT; if (get_user(pid, (int __user *)argp)) break; f_setown(sock->file, pid, 1); err = 0; break; case FIOGETOWN: case SIOCGPGRP: err = put_user(f_getown(sock->file), (int __user *)argp); break; case SIOCGIFBR: case SIOCSIFBR: case SIOCBRADDBR: case SIOCBRDELBR: err = -ENOPKG; if (!br_ioctl_hook) request_module("bridge"); mutex_lock(&br_ioctl_mutex); if (br_ioctl_hook) err = br_ioctl_hook(net, cmd, argp); mutex_unlock(&br_ioctl_mutex); break; case SIOCGIFVLAN: case SIOCSIFVLAN: err = -ENOPKG; if (!vlan_ioctl_hook) request_module("8021q"); mutex_lock(&vlan_ioctl_mutex); if (vlan_ioctl_hook) err = vlan_ioctl_hook(net, argp); mutex_unlock(&vlan_ioctl_mutex); break; case SIOCADDDLCI: case SIOCDELDLCI: err = -ENOPKG; if (!dlci_ioctl_hook) request_module("dlci"); mutex_lock(&dlci_ioctl_mutex); if (dlci_ioctl_hook) err = dlci_ioctl_hook(cmd, argp); mutex_unlock(&dlci_ioctl_mutex); break; case SIOCGSKNS: err = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) break; err = open_related_ns(&net->ns, get_net_ns); break; default: err = sock_do_ioctl(net, sock, cmd, arg); break; } return err; } int sock_create_lite(int family, int type, int protocol, struct socket **res) { int err; struct socket *sock = NULL; err = security_socket_create(family, type, protocol, 1); if (err) goto out; sock = sock_alloc(); if (!sock) { err = -ENOMEM; goto out; } sock->type = type; err = security_socket_post_create(sock, family, type, protocol, 1); if (err) goto out_release; out: *res = sock; return err; out_release: sock_release(sock); sock = NULL; goto out; } EXPORT_SYMBOL(sock_create_lite); /* No kernel lock held - perfect */ static unsigned int sock_poll(struct file *file, poll_table *wait) { unsigned int busy_flag = 0; struct socket *sock; /* * We can't return errors to poll, so it's either yes or no. */ sock = file->private_data; if (sk_can_busy_loop(sock->sk)) { /* this socket can poll_ll so tell the system call */ busy_flag = POLL_BUSY_LOOP; /* once, only if requested by syscall */ if (wait && (wait->_key & POLL_BUSY_LOOP)) sk_busy_loop(sock->sk, 1); } return busy_flag | sock->ops->poll(file, sock, wait); } static int sock_mmap(struct file *file, struct vm_area_struct *vma) { struct socket *sock = file->private_data; return sock->ops->mmap(file, sock, vma); } static int sock_close(struct inode *inode, struct file *filp) { sock_release(SOCKET_I(inode)); return 0; } /* * Update the socket async list * * Fasync_list locking strategy. * * 1. fasync_list is modified only under process context socket lock * i.e. under semaphore. * 2. fasync_list is used under read_lock(&sk->sk_callback_lock) * or under socket lock */ static int sock_fasync(int fd, struct file *filp, int on) { struct socket *sock = filp->private_data; struct sock *sk = sock->sk; struct socket_wq *wq; if (sk == NULL) return -EINVAL; lock_sock(sk); wq = rcu_dereference_protected(sock->wq, lockdep_sock_is_held(sk)); fasync_helper(fd, filp, on, &wq->fasync_list); if (!wq->fasync_list) sock_reset_flag(sk, SOCK_FASYNC); else sock_set_flag(sk, SOCK_FASYNC); release_sock(sk); return 0; } /* This function may be called only under rcu_lock */ int sock_wake_async(struct socket_wq *wq, int how, int band) { if (!wq || !wq->fasync_list) return -1; switch (how) { case SOCK_WAKE_WAITD: if (test_bit(SOCKWQ_ASYNC_WAITDATA, &wq->flags)) break; goto call_kill; case SOCK_WAKE_SPACE: if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &wq->flags)) break; /* fall through */ case SOCK_WAKE_IO: call_kill: kill_fasync(&wq->fasync_list, SIGIO, band); break; case SOCK_WAKE_URG: kill_fasync(&wq->fasync_list, SIGURG, band); } return 0; } EXPORT_SYMBOL(sock_wake_async); int __sock_create(struct net *net, int family, int type, int protocol, struct socket **res, int kern) { int err; struct socket *sock; const struct net_proto_family *pf; /* * Check protocol is in range */ if (family < 0 || family >= NPROTO) return -EAFNOSUPPORT; if (type < 0 || type >= SOCK_MAX) return -EINVAL; /* Compatibility. This uglymoron is moved from INET layer to here to avoid deadlock in module load. */ if (family == PF_INET && type == SOCK_PACKET) { pr_info_once("%s uses obsolete (PF_INET,SOCK_PACKET)\n", current->comm); family = PF_PACKET; } err = security_socket_create(family, type, protocol, kern); if (err) return err; /* * Allocate the socket and allow the family to set things up. if * the protocol is 0, the family is instructed to select an appropriate * default. */ sock = sock_alloc(); if (!sock) { net_warn_ratelimited("socket: no more sockets\n"); return -ENFILE; /* Not exactly a match, but its the closest posix thing */ } sock->type = type; #ifdef CONFIG_MODULES /* Attempt to load a protocol module if the find failed. * * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user * requested real, full-featured networking support upon configuration. * Otherwise module support will break! */ if (rcu_access_pointer(net_families[family]) == NULL) request_module("net-pf-%d", family); #endif rcu_read_lock(); pf = rcu_dereference(net_families[family]); err = -EAFNOSUPPORT; if (!pf) goto out_release; /* * We will call the ->create function, that possibly is in a loadable * module, so we have to bump that loadable module refcnt first. */ if (!try_module_get(pf->owner)) goto out_release; /* Now protected by module ref count */ rcu_read_unlock(); err = pf->create(net, sock, protocol, kern); if (err < 0) goto out_module_put; /* * Now to bump the refcnt of the [loadable] module that owns this * socket at sock_release time we decrement its refcnt. */ if (!try_module_get(sock->ops->owner)) goto out_module_busy; /* * Now that we're done with the ->create function, the [loadable] * module can have its refcnt decremented */ module_put(pf->owner); err = security_socket_post_create(sock, family, type, protocol, kern); if (err) goto out_sock_release; *res = sock; return 0; out_module_busy: err = -EAFNOSUPPORT; out_module_put: sock->ops = NULL; module_put(pf->owner); out_sock_release: sock_release(sock); return err; out_release: rcu_read_unlock(); goto out_sock_release; } EXPORT_SYMBOL(__sock_create); int sock_create(int family, int type, int protocol, struct socket **res) { return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0); } EXPORT_SYMBOL(sock_create); int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res) { return __sock_create(net, family, type, protocol, res, 1); } EXPORT_SYMBOL(sock_create_kern); SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) { int retval; struct socket *sock; int flags; /* Check the SOCK_* constants for consistency. */ BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK); flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; retval = sock_create(family, type, protocol, &sock); if (retval < 0) goto out; retval = sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK)); if (retval < 0) goto out_release; out: /* It may be already another descriptor 8) Not kernel problem. */ return retval; out_release: sock_release(sock); return retval; } /* * Create a pair of connected sockets. */ SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol, int __user *, usockvec) { struct socket *sock1, *sock2; int fd1, fd2, err; struct file *newfile1, *newfile2; int flags; flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; /* * Obtain the first socket and check if the underlying protocol * supports the socketpair call. */ err = sock_create(family, type, protocol, &sock1); if (err < 0) goto out; err = sock_create(family, type, protocol, &sock2); if (err < 0) goto out_release_1; err = sock1->ops->socketpair(sock1, sock2); if (err < 0) goto out_release_both; fd1 = get_unused_fd_flags(flags); if (unlikely(fd1 < 0)) { err = fd1; goto out_release_both; } fd2 = get_unused_fd_flags(flags); if (unlikely(fd2 < 0)) { err = fd2; goto out_put_unused_1; } newfile1 = sock_alloc_file(sock1, flags, NULL); if (IS_ERR(newfile1)) { err = PTR_ERR(newfile1); goto out_put_unused_both; } newfile2 = sock_alloc_file(sock2, flags, NULL); if (IS_ERR(newfile2)) { err = PTR_ERR(newfile2); goto out_fput_1; } err = put_user(fd1, &usockvec[0]); if (err) goto out_fput_both; err = put_user(fd2, &usockvec[1]); if (err) goto out_fput_both; audit_fd_pair(fd1, fd2); fd_install(fd1, newfile1); fd_install(fd2, newfile2); /* fd1 and fd2 may be already another descriptors. * Not kernel problem. */ return 0; out_fput_both: fput(newfile2); fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); goto out; out_fput_1: fput(newfile1); put_unused_fd(fd2); put_unused_fd(fd1); sock_release(sock2); goto out; out_put_unused_both: put_unused_fd(fd2); out_put_unused_1: put_unused_fd(fd1); out_release_both: sock_release(sock2); out_release_1: sock_release(sock1); out: return err; } /* * Bind a name to a socket. Nothing much to do here since it's * the protocol's responsibility to handle the local address. * * We move the socket address to kernel space before we call * the protocol layer (having also checked the address is ok). */ SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { err = move_addr_to_kernel(umyaddr, addrlen, &address); if (err >= 0) { err = security_socket_bind(sock, (struct sockaddr *)&address, addrlen); if (!err) err = sock->ops->bind(sock, (struct sockaddr *) &address, addrlen); } fput_light(sock->file, fput_needed); } return err; } /* * Perform a listen. Basically, we allow the protocol to do anything * necessary for a listen, and if that works, we mark the socket as * ready for listening. */ SYSCALL_DEFINE2(listen, int, fd, int, backlog) { struct socket *sock; int err, fput_needed; int somaxconn; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn; if ((unsigned int)backlog > somaxconn) backlog = somaxconn; err = security_socket_listen(sock, backlog); if (!err) err = sock->ops->listen(sock, backlog); fput_light(sock->file, fput_needed); } return err; } /* * For accept, we attempt to create a new socket, set up the link * with the client, wake up the client, then return the new * connected fd. We collect the address of the connector in kernel * space and move it to user at the very end. This is unclean because * we open the socket then return an error. * * 1003.1g adds the ability to recvmsg() to query connection pending * status to recvmsg. We need to add that support in a way thats * clean when we restucture accept also. */ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen, int, flags) { struct socket *sock, *newsock; struct file *newfile; int err, len, newfd, fput_needed; struct sockaddr_storage address; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = -ENFILE; newsock = sock_alloc(); if (!newsock) goto out_put; newsock->type = sock->type; newsock->ops = sock->ops; /* * We don't need try_module_get here, as the listening socket (sock) * has the protocol module (sock->ops->owner) held. */ __module_get(newsock->ops->owner); newfd = get_unused_fd_flags(flags); if (unlikely(newfd < 0)) { err = newfd; sock_release(newsock); goto out_put; } newfile = sock_alloc_file(newsock, flags, sock->sk->sk_prot_creator->name); if (IS_ERR(newfile)) { err = PTR_ERR(newfile); put_unused_fd(newfd); sock_release(newsock); goto out_put; } err = security_socket_accept(sock, newsock); if (err) goto out_fd; err = sock->ops->accept(sock, newsock, sock->file->f_flags, false); if (err < 0) goto out_fd; if (upeer_sockaddr) { if (newsock->ops->getname(newsock, (struct sockaddr *)&address, &len, 2) < 0) { err = -ECONNABORTED; goto out_fd; } err = move_addr_to_user(&address, len, upeer_sockaddr, upeer_addrlen); if (err < 0) goto out_fd; } /* File flags are not inherited via accept() unlike another OSes. */ fd_install(newfd, newfile); err = newfd; out_put: fput_light(sock->file, fput_needed); out: return err; out_fd: fput(newfile); put_unused_fd(newfd); goto out_put; } SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen) { return sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0); } /* * Attempt to connect to a socket with the server address. The address * is in user space so we verify it is OK and move it to kernel space. * * For 1003.1g we need to add clean support for a bind to AF_UNSPEC to * break bindings * * NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and * other SEQPACKET protocols that take time to connect() as it doesn't * include the -EINPROGRESS status for such sockets. */ SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = move_addr_to_kernel(uservaddr, addrlen, &address); if (err < 0) goto out_put; err = security_socket_connect(sock, (struct sockaddr *)&address, addrlen); if (err) goto out_put; err = sock->ops->connect(sock, (struct sockaddr *)&address, addrlen, sock->file->f_flags); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the local address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = security_socket_getsockname(sock); if (err) goto out_put; err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 0); if (err) goto out_put; err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the remote address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getpeername(sock); if (err) { fput_light(sock->file, fput_needed); return err; } err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 1); if (!err) err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); fput_light(sock->file, fput_needed); } return err; } /* * Send a datagram to a given address. We move the address into kernel * space and check the user space data area is readable before invoking * the protocol. */ SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; err = import_single_range(WRITE, buff, len, &iov, &msg.msg_iter); if (unlikely(err)) return err; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_name = NULL; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Send a datagram down a socket. */ SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len, unsigned int, flags) { return sys_sendto(fd, buff, len, flags, NULL, 0); } /* * Receive a frame from the socket and optionally record the address of the * sender. We verify the buffers are writable and if needed move the * sender address from kernel to user space. */ SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; err = import_single_range(READ, ubuf, size, &iov, &msg.msg_iter); if (unlikely(err)) return err; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; msg.msg_iocb = NULL; msg.msg_flags = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } /* * Receive a datagram from a socket. */ SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags) { return sys_recvfrom(fd, ubuf, size, flags, NULL, NULL); } /* * Set a socket option. Because we don't know the option lengths we have * to pass the user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname, char __user *, optval, int, optlen) { int err, fput_needed; struct socket *sock; if (optlen < 0) return -EINVAL; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_setsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, optval, optlen); else err = sock->ops->setsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Get a socket option. Because we don't know the option lengths we have * to pass a user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname, char __user *, optval, int __user *, optlen) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, optval, optlen); else err = sock->ops->getsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Shutdown a socket. */ SYSCALL_DEFINE2(shutdown, int, fd, int, how) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_shutdown(sock, how); if (!err) err = sock->ops->shutdown(sock, how); fput_light(sock->file, fput_needed); } return err; } /* A couple of helpful macros for getting the address of the 32/64 bit * fields which are the same type (int / unsigned) on our platforms. */ #define COMPAT_MSG(msg, member) ((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member) #define COMPAT_NAMELEN(msg) COMPAT_MSG(msg, msg_namelen) #define COMPAT_FLAGS(msg) COMPAT_MSG(msg, msg_flags) struct used_address { struct sockaddr_storage name; unsigned int name_len; }; static int copy_msghdr_from_user(struct msghdr *kmsg, struct user_msghdr __user *umsg, struct sockaddr __user **save_addr, struct iovec **iov) { struct sockaddr __user *uaddr; struct iovec __user *uiov; size_t nr_segs; ssize_t err; if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) || __get_user(uaddr, &umsg->msg_name) || __get_user(kmsg->msg_namelen, &umsg->msg_namelen) || __get_user(uiov, &umsg->msg_iov) || __get_user(nr_segs, &umsg->msg_iovlen) || __get_user(kmsg->msg_control, &umsg->msg_control) || __get_user(kmsg->msg_controllen, &umsg->msg_controllen) || __get_user(kmsg->msg_flags, &umsg->msg_flags)) return -EFAULT; if (!uaddr) kmsg->msg_namelen = 0; if (kmsg->msg_namelen < 0) return -EINVAL; if (kmsg->msg_namelen > sizeof(struct sockaddr_storage)) kmsg->msg_namelen = sizeof(struct sockaddr_storage); if (save_addr) *save_addr = uaddr; if (uaddr && kmsg->msg_namelen) { if (!save_addr) { err = move_addr_to_kernel(uaddr, kmsg->msg_namelen, kmsg->msg_name); if (err < 0) return err; } } else { kmsg->msg_name = NULL; kmsg->msg_namelen = 0; } if (nr_segs > UIO_MAXIOV) return -EMSGSIZE; kmsg->msg_iocb = NULL; return import_iovec(save_addr ? READ : WRITE, uiov, nr_segs, UIO_FASTIOV, iov, &kmsg->msg_iter); } static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, struct used_address *used_address, unsigned int allowed_msghdr_flags) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __aligned(sizeof(__kernel_size_t)); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int ctl_len; ssize_t err; msg_sys->msg_name = &address; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, NULL, &iov); else err = copy_msghdr_from_user(msg_sys, msg, NULL, &iov); if (err < 0) return err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; flags |= (msg_sys->msg_flags & allowed_msghdr_flags); ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { BUILD_BUG_ON(sizeof(struct cmsghdr) != CMSG_ALIGN(sizeof(struct cmsghdr))); if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && msg_sys->msg_name && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg_sys->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys); goto out_freectl; } err = sock_sendmsg(sock, msg_sys); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; if (msg_sys->msg_name) memcpy(&used_address->name, msg_sys->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: kfree(iov); return err; } /* * BSD sendmsg interface */ long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL, 0); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmsg(fd, msg, flags); } /* * Linux sendmmsg interface */ int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct used_address used_address; unsigned int oflags = flags; if (vlen > UIO_MAXIOV) vlen = UIO_MAXIOV; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; used_address.name_len = UINT_MAX; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; err = 0; flags |= MSG_BATCH; while (datagrams < vlen) { if (datagrams == vlen - 1) flags = oflags; if (MSG_CMSG_COMPAT & flags) { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags, &used_address, MSG_EOR); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags, &used_address, MSG_EOR); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; if (msg_data_left(&msg_sys)) break; cond_resched(); } fput_light(sock->file, fput_needed); /* We only return an error if no datagrams were able to be sent */ if (datagrams != 0) return datagrams; return err; } SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmmsg(fd, mmsg, vlen, flags); } static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, int nosec) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; unsigned long cmsg_ptr; int len; ssize_t err; /* kernel mode address */ struct sockaddr_storage addr; /* user mode address pointers */ struct sockaddr __user *uaddr; int __user *uaddr_len = COMPAT_NAMELEN(msg); msg_sys->msg_name = &addr; if (MSG_CMSG_COMPAT & flags) err = get_compat_msghdr(msg_sys, msg_compat, &uaddr, &iov); else err = copy_msghdr_from_user(msg_sys, msg, &uaddr, &iov); if (err < 0) return err; cmsg_ptr = (unsigned long)msg_sys->msg_control; msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); /* We assume all kernel code knows the size of sockaddr_storage */ msg_sys->msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, flags); if (err < 0) goto out_freeiov; len = err; if (uaddr != NULL) { err = move_addr_to_user(&addr, msg_sys->msg_namelen, uaddr, uaddr_len); if (err < 0) goto out_freeiov; } err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT), COMPAT_FLAGS(msg)); if (err) goto out_freeiov; if (MSG_CMSG_COMPAT & flags) err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg_compat->msg_controllen); else err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg->msg_controllen); if (err) goto out_freeiov; err = len; out_freeiov: kfree(iov); return err; } /* * BSD recvmsg interface */ long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = ___sys_recvmsg(sock, msg, &msg_sys, flags, 0); fput_light(sock->file, fput_needed); out: return err; } SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_recvmsg(fd, msg, flags); } /* * Linux recvmmsg interface */ int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct timespec64 end_time; struct timespec64 timeout64; if (timeout && poll_select_set_timeout(&end_time, timeout->tv_sec, timeout->tv_nsec)) return -EINVAL; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; err = sock_error(sock->sk); if (err) { datagrams = err; goto out_put; } entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; while (datagrams < vlen) { /* * No need to ask LSM for more than the first datagram. */ if (MSG_CMSG_COMPAT & flags) { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */ if (flags & MSG_WAITFORONE) flags |= MSG_DONTWAIT; if (timeout) { ktime_get_ts64(&timeout64); *timeout = timespec64_to_timespec( timespec64_sub(end_time, timeout64)); if (timeout->tv_sec < 0) { timeout->tv_sec = timeout->tv_nsec = 0; break; } /* Timeout, return less than vlen datagrams */ if (timeout->tv_nsec == 0 && timeout->tv_sec == 0) break; } /* Out of band data, return right away */ if (msg_sys.msg_flags & MSG_OOB) break; cond_resched(); } if (err == 0) goto out_put; if (datagrams == 0) { datagrams = err; goto out_put; } /* * We may return less entries than requested (vlen) if the * sock is non block and there aren't enough datagrams... */ if (err != -EAGAIN) { /* * ... or if recvmsg returns an error after we * received some datagrams, where we record the * error to return on the next call or if the * app asks about it using getsockopt(SO_ERROR). */ sock->sk->sk_err = -err; } out_put: fput_light(sock->file, fput_needed); return datagrams; } SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags, struct timespec __user *, timeout) { int datagrams; struct timespec timeout_sys; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (!timeout) return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL); if (copy_from_user(&timeout_sys, timeout, sizeof(timeout_sys))) return -EFAULT; datagrams = __sys_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys); if (datagrams > 0 && copy_to_user(timeout, &timeout_sys, sizeof(timeout_sys))) datagrams = -EFAULT; return datagrams; } #ifdef __ARCH_WANT_SYS_SOCKETCALL /* Argument list sizes for sys_socketcall */ #define AL(x) ((x) * sizeof(unsigned long)) static const unsigned char nargs[21] = { AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4) }; #undef AL /* * System call vectors. * * Argument checking cleaned up. Saved 20% in size. * This function doesn't need to set the kernel lock because * it is set by the callees. */ SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) { unsigned long a[AUDITSC_ARGS]; unsigned long a0, a1; int err; unsigned int len; if (call < 1 || call > SYS_SENDMMSG) return -EINVAL; len = nargs[call]; if (len > sizeof(a)) return -EINVAL; /* copy_from_user should be SMP safe. */ if (copy_from_user(a, args, len)) return -EFAULT; err = audit_socketcall(nargs[call] / sizeof(unsigned long), a); if (err) return err; a0 = a[0]; a1 = a[1]; switch (call) { case SYS_SOCKET: err = sys_socket(a0, a1, a[2]); break; case SYS_BIND: err = sys_bind(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_CONNECT: err = sys_connect(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_LISTEN: err = sys_listen(a0, a1); break; case SYS_ACCEPT: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], 0); break; case SYS_GETSOCKNAME: err = sys_getsockname(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_GETPEERNAME: err = sys_getpeername(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_SOCKETPAIR: err = sys_socketpair(a0, a1, a[2], (int __user *)a[3]); break; case SYS_SEND: err = sys_send(a0, (void __user *)a1, a[2], a[3]); break; case SYS_SENDTO: err = sys_sendto(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], a[5]); break; case SYS_RECV: err = sys_recv(a0, (void __user *)a1, a[2], a[3]); break; case SYS_RECVFROM: err = sys_recvfrom(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], (int __user *)a[5]); break; case SYS_SHUTDOWN: err = sys_shutdown(a0, a1); break; case SYS_SETSOCKOPT: err = sys_setsockopt(a0, a1, a[2], (char __user *)a[3], a[4]); break; case SYS_GETSOCKOPT: err = sys_getsockopt(a0, a1, a[2], (char __user *)a[3], (int __user *)a[4]); break; case SYS_SENDMSG: err = sys_sendmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_SENDMMSG: err = sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3]); break; case SYS_RECVMSG: err = sys_recvmsg(a0, (struct user_msghdr __user *)a1, a[2]); break; case SYS_RECVMMSG: err = sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3], (struct timespec __user *)a[4]); break; case SYS_ACCEPT4: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], a[3]); break; default: err = -EINVAL; break; } return err; } #endif /* __ARCH_WANT_SYS_SOCKETCALL */ /** * sock_register - add a socket protocol handler * @ops: description of protocol * * This function is called by a protocol handler that wants to * advertise its address family, and have it linked into the * socket interface. The value ops->family corresponds to the * socket system call protocol family. */ int sock_register(const struct net_proto_family *ops) { int err; if (ops->family >= NPROTO) { pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO); return -ENOBUFS; } spin_lock(&net_family_lock); if (rcu_dereference_protected(net_families[ops->family], lockdep_is_held(&net_family_lock))) err = -EEXIST; else { rcu_assign_pointer(net_families[ops->family], ops); err = 0; } spin_unlock(&net_family_lock); pr_info("NET: Registered protocol family %d\n", ops->family); return err; } EXPORT_SYMBOL(sock_register); /** * sock_unregister - remove a protocol handler * @family: protocol family to remove * * This function is called by a protocol handler that wants to * remove its address family, and have it unlinked from the * new socket creation. * * If protocol handler is a module, then it can use module reference * counts to protect against new references. If protocol handler is not * a module then it needs to provide its own protection in * the ops->create routine. */ void sock_unregister(int family) { BUG_ON(family < 0 || family >= NPROTO); spin_lock(&net_family_lock); RCU_INIT_POINTER(net_families[family], NULL); spin_unlock(&net_family_lock); synchronize_rcu(); pr_info("NET: Unregistered protocol family %d\n", family); } EXPORT_SYMBOL(sock_unregister); static int __init sock_init(void) { int err; /* * Initialize the network sysctl infrastructure. */ err = net_sysctl_init(); if (err) goto out; /* * Initialize skbuff SLAB cache */ skb_init(); /* * Initialize the protocols module. */ init_inodecache(); err = register_filesystem(&sock_fs_type); if (err) goto out_fs; sock_mnt = kern_mount(&sock_fs_type); if (IS_ERR(sock_mnt)) { err = PTR_ERR(sock_mnt); goto out_mount; } /* The real protocol initialization is performed in later initcalls. */ #ifdef CONFIG_NETFILTER err = netfilter_init(); if (err) goto out; #endif ptp_classifier_init(); out: return err; out_mount: unregister_filesystem(&sock_fs_type); out_fs: goto out; } core_initcall(sock_init); /* early initcall */ #ifdef CONFIG_PROC_FS void socket_seq_show(struct seq_file *seq) { int cpu; int counter = 0; for_each_possible_cpu(cpu) counter += per_cpu(sockets_in_use, cpu); /* It can be negative, by the way. 8) */ if (counter < 0) counter = 0; seq_printf(seq, "sockets: used %d\n", counter); } #endif /* CONFIG_PROC_FS */ #ifdef CONFIG_COMPAT static int do_siocgstamp(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timeval ktv; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv); set_fs(old_fs); if (!err) err = compat_put_timeval(&ktv, up); return err; } static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(&kts, up); return err; } static int dev_ifname32(struct net *net, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(struct ifreq)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; err = dev_ioctl(net, SIOCGIFNAME, uifr); if (err) return err; if (copy_in_user(uifr32, uifr, sizeof(struct compat_ifreq))) return -EFAULT; return 0; } static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; memset(&ifc, 0, sizeof(ifc)); if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; } static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) { struct compat_ethtool_rxnfc __user *compat_rxnfc; bool convert_in = false, convert_out = false; size_t buf_size = ALIGN(sizeof(struct ifreq), 8); struct ethtool_rxnfc __user *rxnfc; struct ifreq __user *ifr; u32 rule_cnt = 0, actual_rule_cnt; u32 ethcmd; u32 data; int ret; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; compat_rxnfc = compat_ptr(data); if (get_user(ethcmd, &compat_rxnfc->cmd)) return -EFAULT; /* Most ethtool structures are defined without padding. * Unfortunately struct ethtool_rxnfc is an exception. */ switch (ethcmd) { default: break; case ETHTOOL_GRXCLSRLALL: /* Buffer size is variable */ if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) return -EFAULT; if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) return -ENOMEM; buf_size += rule_cnt * sizeof(u32); /* fall through */ case ETHTOOL_GRXRINGS: case ETHTOOL_GRXCLSRLCNT: case ETHTOOL_GRXCLSRULE: case ETHTOOL_SRXCLSRLINS: convert_out = true; /* fall through */ case ETHTOOL_SRXCLSRLDEL: buf_size += sizeof(struct ethtool_rxnfc); convert_in = true; break; } ifr = compat_alloc_user_space(buf_size); rxnfc = (void __user *)ifr + ALIGN(sizeof(struct ifreq), 8); if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (put_user(convert_in ? rxnfc : compat_ptr(data), &ifr->ifr_ifru.ifru_data)) return -EFAULT; if (convert_in) { /* We expect there to be holes between fs.m_ext and * fs.ring_cookie and at the end of fs, but nowhere else. */ BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + sizeof(compat_rxnfc->fs.m_ext) != offsetof(struct ethtool_rxnfc, fs.m_ext) + sizeof(rxnfc->fs.m_ext)); BUILD_BUG_ON( offsetof(struct compat_ethtool_rxnfc, fs.location) - offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != offsetof(struct ethtool_rxnfc, fs.location) - offsetof(struct ethtool_rxnfc, fs.ring_cookie)); if (copy_in_user(rxnfc, compat_rxnfc, (void __user *)(&rxnfc->fs.m_ext + 1) - (void __user *)rxnfc) || copy_in_user(&rxnfc->fs.ring_cookie, &compat_rxnfc->fs.ring_cookie, (void __user *)(&rxnfc->fs.location + 1) - (void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; } ret = dev_ioctl(net, SIOCETHTOOL, ifr); if (ret) return ret; if (convert_out) { if (copy_in_user(compat_rxnfc, rxnfc, (const void __user *)(&rxnfc->fs.m_ext + 1) - (const void __user *)rxnfc) || copy_in_user(&compat_rxnfc->fs.ring_cookie, &rxnfc->fs.ring_cookie, (const void __user *)(&rxnfc->fs.location + 1) - (const void __user *)&rxnfc->fs.ring_cookie) || copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; if (ethcmd == ETHTOOL_GRXCLSRLALL) { /* As an optimisation, we only copy the actual * number of rules that the underlying * function returned. Since Mallory might * change the rule count in user memory, we * check that it is less than the rule count * originally given (as the user buffer size), * which has been range-checked. */ if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) return -EFAULT; if (actual_rule_cnt < rule_cnt) rule_cnt = actual_rule_cnt; if (copy_in_user(&compat_rxnfc->rule_locs[0], &rxnfc->rule_locs[0], rule_cnt * sizeof(u32))) return -EFAULT; } } return 0; } static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_settings.ifs_ifsu.raw_hdlc)) return -EFAULT; return dev_ioctl(net, SIOCWANDEV, uifr); } static int bond_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *ifr32) { struct ifreq kifr; mm_segment_t old_fs; int err; switch (cmd) { case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (struct ifreq __user __force *) &kifr); set_fs(old_fs); return err; default: return -ENOIOCTLCMD; } } /* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */ static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *u_ifreq32) { struct ifreq __user *u_ifreq64; char tmp_buf[IFNAMSIZ]; void __user *data64; u32 data32; if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]), IFNAMSIZ)) return -EFAULT; if (get_user(data32, &u_ifreq32->ifr_ifru.ifru_data)) return -EFAULT; data64 = compat_ptr(data32); u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64)); if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0], IFNAMSIZ)) return -EFAULT; if (put_user(data64, &u_ifreq64->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, u_ifreq64); } static int dev_ifsioc(struct net *net, struct socket *sock, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(*uifr32))) return -EFAULT; err = sock_do_ioctl(net, sock, cmd, (unsigned long)uifr); if (!err) { switch (cmd) { case SIOCGIFFLAGS: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFMEM: case SIOCGIFHWADDR: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFDSTADDR: case SIOCGIFNETMASK: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCGMIIPHY: case SIOCGMIIREG: if (copy_in_user(uifr32, uifr, sizeof(*uifr32))) err = -EFAULT; break; } } return err; } static int compat_sioc_ifmap(struct net *net, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq ifr; struct compat_ifmap __user *uifmap32; mm_segment_t old_fs; int err; uifmap32 = &uifr32->ifr_ifru.ifru_map; err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name)); err |= get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= get_user(ifr.ifr_map.irq, &uifmap32->irq); err |= get_user(ifr.ifr_map.dma, &uifmap32->dma); err |= get_user(ifr.ifr_map.port, &uifmap32->port); if (err) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (void __user __force *)&ifr); set_fs(old_fs); if (cmd == SIOCGIFMAP && !err) { err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name)); err |= put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= put_user(ifr.ifr_map.irq, &uifmap32->irq); err |= put_user(ifr.ifr_map.dma, &uifmap32->dma); err |= put_user(ifr.ifr_map.port, &uifmap32->port); if (err) err = -EFAULT; } return err; } struct rtentry32 { u32 rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; u32 rt_pad3; unsigned char rt_tos; unsigned char rt_class; short rt_pad4; short rt_metric; /* +1 for binary compatibility! */ /* char * */ u32 rt_dev; /* forcing the device at add */ u32 rt_mtu; /* per route MTU/Window */ u32 rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; struct in6_rtmsg32 { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; u32 rtmsg_type; u16 rtmsg_dst_len; u16 rtmsg_src_len; u32 rtmsg_metric; u32 rtmsg_info; u32 rtmsg_flags; s32 rtmsg_ifindex; }; static int routing_ioctl(struct net *net, struct socket *sock, unsigned int cmd, void __user *argp) { int ret; void *r = NULL; struct in6_rtmsg r6; struct rtentry r4; char devname[16]; u32 rtdev; mm_segment_t old_fs = get_fs(); if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */ struct in6_rtmsg32 __user *ur6 = argp; ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst), 3 * sizeof(struct in6_addr)); ret |= get_user(r6.rtmsg_type, &(ur6->rtmsg_type)); ret |= get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len)); ret |= get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len)); ret |= get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric)); ret |= get_user(r6.rtmsg_info, &(ur6->rtmsg_info)); ret |= get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags)); ret |= get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex)); r = (void *) &r6; } else { /* ipv4 */ struct rtentry32 __user *ur4 = argp; ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst), 3 * sizeof(struct sockaddr)); ret |= get_user(r4.rt_flags, &(ur4->rt_flags)); ret |= get_user(r4.rt_metric, &(ur4->rt_metric)); ret |= get_user(r4.rt_mtu, &(ur4->rt_mtu)); ret |= get_user(r4.rt_window, &(ur4->rt_window)); ret |= get_user(r4.rt_irtt, &(ur4->rt_irtt)); ret |= get_user(rtdev, &(ur4->rt_dev)); if (rtdev) { ret |= copy_from_user(devname, compat_ptr(rtdev), 15); r4.rt_dev = (char __user __force *)devname; devname[15] = 0; } else r4.rt_dev = NULL; r = (void *) &r4; } if (ret) { ret = -EFAULT; goto out; } set_fs(KERNEL_DS); ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r); set_fs(old_fs); out: return ret; } /* Since old style bridge ioctl's endup using SIOCDEVPRIVATE * for some operations; this forces use of the newer bridge-utils that * use compatible ioctls */ static int old_bridge_ioctl(compat_ulong_t __user *argp) { compat_ulong_t tmp; if (get_user(tmp, argp)) return -EFAULT; if (tmp == BRCTL_GET_VERSION) return BRCTL_VERSION + 1; return -EINVAL; } static int compat_sock_ioctl_trans(struct file *file, struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); struct sock *sk = sock->sk; struct net *net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) return compat_ifr_data_ioctl(net, cmd, argp); switch (cmd) { case SIOCSIFBR: case SIOCGIFBR: return old_bridge_ioctl(argp); case SIOCGIFNAME: return dev_ifname32(net, argp); case SIOCGIFCONF: return dev_ifconf(net, argp); case SIOCETHTOOL: return ethtool_ioctl(net, argp); case SIOCWANDEV: return compat_siocwandev(net, argp); case SIOCGIFMAP: case SIOCSIFMAP: return compat_sioc_ifmap(net, cmd, argp); case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: return bond_ioctl(net, cmd, argp); case SIOCADDRT: case SIOCDELRT: return routing_ioctl(net, sock, cmd, argp); case SIOCGSTAMP: return do_siocgstamp(net, sock, cmd, argp); case SIOCGSTAMPNS: return do_siocgstampns(net, sock, cmd, argp); case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: case SIOCSHWTSTAMP: case SIOCGHWTSTAMP: return compat_ifr_data_ioctl(net, cmd, argp); case FIOSETOWN: case SIOCSPGRP: case FIOGETOWN: case SIOCGPGRP: case SIOCBRADDBR: case SIOCBRDELBR: case SIOCGIFVLAN: case SIOCSIFVLAN: case SIOCADDDLCI: case SIOCDELDLCI: case SIOCGSKNS: return sock_ioctl(file, cmd, arg); case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFMETRIC: case SIOCSIFMETRIC: case SIOCGIFMTU: case SIOCSIFMTU: case SIOCGIFMEM: case SIOCSIFMEM: case SIOCGIFHWADDR: case SIOCSIFHWADDR: case SIOCADDMULTI: case SIOCDELMULTI: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCSIFHWBROADCAST: case SIOCDIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCSIFTXQLEN: case SIOCBRADDIF: case SIOCBRDELIF: case SIOCSIFNAME: case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return dev_ifsioc(net, sock, cmd, argp); case SIOCSARP: case SIOCGARP: case SIOCDARP: case SIOCATMARK: return sock_do_ioctl(net, sock, cmd, arg); } return -ENOIOCTLCMD; } static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct socket *sock = file->private_data; int ret = -ENOIOCTLCMD; struct sock *sk; struct net *net; sk = sock->sk; net = sock_net(sk); if (sock->ops->compat_ioctl) ret = sock->ops->compat_ioctl(sock, cmd, arg); if (ret == -ENOIOCTLCMD && (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)) ret = compat_wext_handle_ioctl(net, cmd, arg); if (ret == -ENOIOCTLCMD) ret = compat_sock_ioctl_trans(file, sock, cmd, arg); return ret; } #endif int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen) { return sock->ops->bind(sock, addr, addrlen); } EXPORT_SYMBOL(kernel_bind); int kernel_listen(struct socket *sock, int backlog) { return sock->ops->listen(sock, backlog); } EXPORT_SYMBOL(kernel_listen); int kernel_accept(struct socket *sock, struct socket **newsock, int flags) { struct sock *sk = sock->sk; int err; err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol, newsock); if (err < 0) goto done; err = sock->ops->accept(sock, *newsock, flags, true); if (err < 0) { sock_release(*newsock); *newsock = NULL; goto done; } (*newsock)->ops = sock->ops; __module_get((*newsock)->ops->owner); done: return err; } EXPORT_SYMBOL(kernel_accept); int kernel_connect(struct socket *sock, struct sockaddr *addr, int addrlen, int flags) { return sock->ops->connect(sock, addr, addrlen, flags); } EXPORT_SYMBOL(kernel_connect); int kernel_getsockname(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 0); } EXPORT_SYMBOL(kernel_getsockname); int kernel_getpeername(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 1); } EXPORT_SYMBOL(kernel_getpeername); int kernel_getsockopt(struct socket *sock, int level, int optname, char *optval, int *optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int __user *uoptlen; int err; uoptval = (char __user __force *) optval; uoptlen = (int __user __force *) optlen; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, uoptval, uoptlen); else err = sock->ops->getsockopt(sock, level, optname, uoptval, uoptlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_getsockopt); int kernel_setsockopt(struct socket *sock, int level, int optname, char *optval, unsigned int optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int err; uoptval = (char __user __force *) optval; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, uoptval, optlen); else err = sock->ops->setsockopt(sock, level, optname, uoptval, optlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_setsockopt); int kernel_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { if (sock->ops->sendpage) return sock->ops->sendpage(sock, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } EXPORT_SYMBOL(kernel_sendpage); int kernel_sock_ioctl(struct socket *sock, int cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); int err; set_fs(KERNEL_DS); err = sock->ops->ioctl(sock, cmd, arg); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_sock_ioctl); int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how) { return sock->ops->shutdown(sock, how); } EXPORT_SYMBOL(kernel_sock_shutdown);
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3255_1
crossvul-cpp_data_good_486_2
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Protocol services - Clipboard functions Copyright 2003 Erik Forsberg <forsberg@cendio.se> for Cendio AB Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 2003-2008 Copyright 2017 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #define CLIPRDR_CONNECT 1 #define CLIPRDR_FORMAT_ANNOUNCE 2 #define CLIPRDR_FORMAT_ACK 3 #define CLIPRDR_DATA_REQUEST 4 #define CLIPRDR_DATA_RESPONSE 5 #define CLIPRDR_REQUEST 0 #define CLIPRDR_RESPONSE 1 #define CLIPRDR_ERROR 2 static VCHANNEL *cliprdr_channel; static uint8 *last_formats = NULL; static uint32 last_formats_length = 0; static void cliprdr_send_packet(uint16 type, uint16 status, uint8 * data, uint32 length) { STREAM s; logger(Clipboard, Debug, "cliprdr_send_packet(), type=%d, status=%d, length=%d", type, status, length); s = channel_init(cliprdr_channel, length + 12); out_uint16_le(s, type); out_uint16_le(s, status); out_uint32_le(s, length); out_uint8p(s, data, length); out_uint32(s, 0); /* pad? */ s_mark_end(s); channel_send(s, cliprdr_channel); } /* Helper which announces our readiness to supply clipboard data in a single format (such as CF_TEXT) to the RDP side. To announce more than one format at a time, use cliprdr_send_native_format_announce. */ void cliprdr_send_simple_native_format_announce(uint32 format) { uint8 buffer[36]; logger(Clipboard, Debug, "cliprdr_send_simple_native_format_announce() format 0x%x", format); buf_out_uint32(buffer, format); memset(buffer + 4, 0, sizeof(buffer) - 4); /* description */ cliprdr_send_native_format_announce(buffer, sizeof(buffer)); } /* Announces our readiness to supply clipboard data in multiple formats, each denoted by a 36-byte format descriptor of [ uint32 format + 32-byte description ]. */ void cliprdr_send_native_format_announce(uint8 * formats_data, uint32 formats_data_length) { logger(Clipboard, Debug, "cliprdr_send_native_format_announce()"); cliprdr_send_packet(CLIPRDR_FORMAT_ANNOUNCE, CLIPRDR_REQUEST, formats_data, formats_data_length); if (formats_data != last_formats) { if (last_formats) xfree(last_formats); last_formats = xmalloc(formats_data_length); memcpy(last_formats, formats_data, formats_data_length); last_formats_length = formats_data_length; } } void cliprdr_send_data_request(uint32 format) { uint8 buffer[4]; logger(Clipboard, Debug, "cliprdr_send_data_request(), format 0x%x", format); buf_out_uint32(buffer, format); cliprdr_send_packet(CLIPRDR_DATA_REQUEST, CLIPRDR_REQUEST, buffer, sizeof(buffer)); } void cliprdr_send_data(uint8 * data, uint32 length) { logger(Clipboard, Debug, "cliprdr_send_data(), length %d bytes", length); cliprdr_send_packet(CLIPRDR_DATA_RESPONSE, CLIPRDR_RESPONSE, data, length); } static void cliprdr_process(STREAM s) { uint16 type, status; uint32 length, format; uint8 *data; struct stream packet = *s; in_uint16_le(s, type); in_uint16_le(s, status); in_uint32_le(s, length); data = s->p; logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status, length); if (!s_check_rem(s, length)) { rdp_protocol_error("cliprdr_process(), consume of packet from stream would overrun", &packet); } if (status == CLIPRDR_ERROR) { switch (type) { case CLIPRDR_FORMAT_ACK: /* FIXME: We seem to get this when we send an announce while the server is still processing a paste. Try sending another announce. */ cliprdr_send_native_format_announce(last_formats, last_formats_length); break; case CLIPRDR_DATA_RESPONSE: ui_clip_request_failed(); break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled error (type=%d)", type); } return; } switch (type) { case CLIPRDR_CONNECT: ui_clip_sync(); break; case CLIPRDR_FORMAT_ANNOUNCE: ui_clip_format_announce(data, length); cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0); return; case CLIPRDR_FORMAT_ACK: break; case CLIPRDR_DATA_REQUEST: in_uint32_le(s, format); ui_clip_request_data(format); break; case CLIPRDR_DATA_RESPONSE: ui_clip_handle_data(data, length); break; case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */ break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d", type); } } void cliprdr_set_mode(const char *optarg) { ui_clip_set_mode(optarg); } RD_BOOL cliprdr_init(void) { cliprdr_channel = channel_register("cliprdr", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP | CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL, cliprdr_process); return (cliprdr_channel != NULL); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_486_2
crossvul-cpp_data_good_5515_1
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <andrei@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_WDDX #include "ext/xml/expat_compat.h" #include "php_wddx.h" #include "php_wddx_api.h" #define PHP_XML_INTERNAL #include "ext/xml/php_xml.h" #include "ext/standard/php_incomplete_class.h" #include "ext/standard/base64.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/html.h" #include "ext/standard/php_string.h" #include "ext/date/php_date.h" #include "zend_globals.h" #define WDDX_BUF_LEN 256 #define PHP_CLASS_NAME_VAR "php_class_name" #define EL_ARRAY "array" #define EL_BINARY "binary" #define EL_BOOLEAN "boolean" #define EL_CHAR "char" #define EL_CHAR_CODE "code" #define EL_NULL "null" #define EL_NUMBER "number" #define EL_PACKET "wddxPacket" #define EL_STRING "string" #define EL_STRUCT "struct" #define EL_VALUE "value" #define EL_VAR "var" #define EL_NAME "name" #define EL_VERSION "version" #define EL_RECORDSET "recordset" #define EL_FIELD "field" #define EL_DATETIME "dateTime" #define php_wddx_deserialize(a,b) \ php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b)) #define SET_STACK_VARNAME \ if (stack->varname) { \ ent.varname = estrdup(stack->varname); \ efree(stack->varname); \ stack->varname = NULL; \ } else \ ent.varname = NULL; \ static int le_wddx; typedef struct { zval *data; enum { ST_ARRAY, ST_BOOLEAN, ST_NULL, ST_NUMBER, ST_STRING, ST_BINARY, ST_STRUCT, ST_RECORDSET, ST_FIELD, ST_DATETIME } type; char *varname; } st_entry; typedef struct { int top, max; char *varname; zend_bool done; void **elements; } wddx_stack; static void php_wddx_process_data(void *user_data, const XML_Char *s, int len); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1) ZEND_ARG_INFO(0, packet_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2) ZEND_ARG_INFO(0, packet_id) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1) ZEND_ARG_INFO(0, packet) ZEND_END_ARG_INFO() /* }}} */ /* {{{ wddx_functions[] */ const zend_function_entry wddx_functions[] = { PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value) PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars) PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start) PHP_FE(wddx_packet_end, arginfo_wddx_packet_end) PHP_FE(wddx_add_vars, arginfo_wddx_add_vars) PHP_FE(wddx_deserialize, arginfo_wddx_deserialize) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(wddx); PHP_MINFO_FUNCTION(wddx); /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_WDDX ZEND_GET_MODULE(wddx) #endif /* COMPILE_DL_WDDX */ /* }}} */ /* {{{ wddx_module_entry */ zend_module_entry wddx_module_entry = { STANDARD_MODULE_HEADER, "wddx", wddx_functions, PHP_MINIT(wddx), NULL, NULL, NULL, PHP_MINFO(wddx), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* }}} */ /* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; } /* }}} */ /* {{{ wddx_stack_push */ static int wddx_stack_push(wddx_stack *stack, void *element, int size) { if (stack->top >= stack->max) { /* we need to allocate more memory */ stack->elements = (void **) erealloc(stack->elements, (sizeof(void **) * (stack->max += STACK_BLOCK_SIZE))); } stack->elements[stack->top] = (void *) emalloc(size); memcpy(stack->elements[stack->top], element, size); return stack->top++; } /* }}} */ /* {{{ wddx_stack_top */ static int wddx_stack_top(wddx_stack *stack, void **element) { if (stack->top > 0) { *element = stack->elements[stack->top - 1]; return SUCCESS; } else { *element = NULL; return FAILURE; } } /* }}} */ /* {{{ wddx_stack_is_empty */ static int wddx_stack_is_empty(wddx_stack *stack) { if (stack->top == 0) { return 1; } else { return 0; } } /* }}} */ /* {{{ wddx_stack_destroy */ static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data && ((st_entry *)stack->elements[i])->type != ST_FIELD) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } /* }}} */ /* {{{ release_wddx_packet_rsrc */ static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } /* }}} */ #include "ext/session/php_session.h" #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) /* {{{ PS_SERIALIZER_ENCODE_FUNC */ PS_SERIALIZER_ENCODE_FUNC(wddx) { wddx_packet *packet; PS_ENCODE_VARS; packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); PS_ENCODE_LOOP( php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); *newstr = php_wddx_gather(packet); php_wddx_destructor(packet); if (newlen) { *newlen = strlen(*newstr); } return SUCCESS; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval *retval; zval **ent; char *key; uint key_length; char tmp[128]; ulong idx; int hash_type; int ret; if (vallen == 0) { return SUCCESS; } MAKE_STD_ZVAL(retval); if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) { if (Z_TYPE_P(retval) != IS_ARRAY) { zval_ptr_dtor(&retval); return FAILURE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval)); zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(retval))) { hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL); switch (hash_type) { case HASH_KEY_IS_LONG: key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC); PS_ADD_VAR(key); } } } zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(wddx) { le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_session_register_serializer("wddx", PS_SERIALIZER_ENCODE_NAME(wddx), PS_SERIALIZER_DECODE_NAME(wddx)); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(wddx) { php_info_print_table_start(); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_info_print_table_header(2, "WDDX Support", "enabled" ); php_info_print_table_row(2, "WDDX Session Serializer", "enabled" ); #else php_info_print_table_row(2, "WDDX Support", "enabled" ); #endif php_info_print_table_end(); } /* }}} */ /* {{{ php_wddx_packet_start */ void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { char *escaped; size_t escaped_len; TSRMLS_FETCH(); escaped = php_escape_html_entities( comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, escaped, escaped_len); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); str_efree(escaped); } else { php_wddx_add_chunk_static(packet, WDDX_HEADER); } php_wddx_add_chunk_static(packet, WDDX_DATA_S); } /* }}} */ /* {{{ php_wddx_packet_end */ void php_wddx_packet_end(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_DATA_E); php_wddx_add_chunk_static(packet, WDDX_PACKET_E); } /* }}} */ #define FLUSH_BUF() \ if (l > 0) { \ php_wddx_add_chunk_ex(packet, buf, l); \ l = 0; \ } /* {{{ php_wddx_serialize_string */ static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { char *buf; size_t buf_len; buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_ex(packet, buf, buf_len); str_efree(buf); } php_wddx_add_chunk_static(packet, WDDX_STRING_E); } /* }}} */ /* {{{ php_wddx_serialize_number */ static void php_wddx_serialize_number(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; zval tmp; tmp = *var; zval_copy_ctor(&tmp); convert_to_string(&tmp); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp)); zval_dtor(&tmp); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ /* {{{ php_wddx_serialize_boolean */ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE); } /* }}} */ /* {{{ php_wddx_serialize_unset */ static void php_wddx_serialize_unset(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_NULL); } /* }}} */ /* {{{ php_wddx_serialize_object */ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; zend_class_entry *ce; PHP_CLASS_ATTRIBUTES; TSRMLS_FETCH(); PHP_SET_CLASS_ATTRIBUTES(obj); ce = Z_OBJCE_P(obj); if (!ce || ce->serialize || ce->unserialize) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be serialized", class_name); PHP_CLEANUP_CLASS_ATTRIBUTES(); return; } MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } PHP_CLEANUP_CLASS_ATTRIBUTES(); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval **ent; char *key; uint key_len; int is_struct = 0, ent_type; ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; ulong ind = 0; int type; TSRMLS_FETCH(); target_hash = HASH_OF(arr); for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { type = zend_hash_get_current_key(target_hash, &key, &idx, 0); if (type == HASH_KEY_IS_STRING) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { if (*ent == arr) { continue; } if (is_struct) { ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL); if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else { php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC); } } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } else { php_wddx_add_chunk_static(packet, WDDX_ARRAY_E); } } /* }}} */ /* {{{ php_wddx_serialize_var */ void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); str_efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } } /* }}} */ /* {{{ php_wddx_add_var */ static void php_wddx_add_var(wddx_packet *packet, zval *name_var) { zval **val; HashTable *target_hash; TSRMLS_FETCH(); if (Z_TYPE_P(name_var) == IS_STRING) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var), Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) { php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC); } } else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) { int is_array = Z_TYPE_P(name_var) == IS_ARRAY; target_hash = HASH_OF(name_var); if (is_array && target_hash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } zend_hash_internal_pointer_reset(target_hash); while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) { if (is_array) { target_hash->nApplyCount++; } php_wddx_add_var(packet, *val); if (is_array) { target_hash->nApplyCount--; } zend_hash_move_forward(target_hash); } } } /* }}} */ /* {{{ php_wddx_push_element */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } else { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_FALSE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } /* }}} */ /* {{{ php_wddx_pop_element */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } if (pce != &PHP_IC_ENTRY && ((*pce)->serialize || (*pce)->unserialize)) { zval_ptr_dtor(&ent2->data); ent2->data = NULL; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be unserialized", Z_STRVAL_P(ent1->data)); } else { /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } /* }}} */ /* {{{ php_wddx_process_data */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; if (Z_TYPE_P(ent->data) == IS_STRING) { tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1); memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data)); memcpy(tmp + Z_STRLEN_P(ent->data), s, len); len += Z_STRLEN_P(ent->data); efree(Z_STRVAL_P(ent->data)); Z_TYPE_P(ent->data) = IS_LONG; } else { tmp = emalloc(len + 1); memcpy(tmp, s, len); } tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { ZVAL_STRINGL(ent->data, tmp, len, 0); } else { efree(tmp); } } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); if(ent->data == NULL) { retval = FAILURE; } else { *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } /* }}} */ /* {{{ proto string wddx_serialize_value(mixed var [, string comment]) Creates a new packet and serializes the given value */ PHP_FUNCTION(wddx_serialize_value) { zval *var; char *comment = NULL; int comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...]) Creates a new packet and serializes given variables into a struct */ PHP_FUNCTION(wddx_serialize_vars) { int num_args, i; wddx_packet *packet; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, *args[i]); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); efree(args); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = (smart_str *)emalloc(sizeof(smart_str)); packet->c = NULL; return packet; } /* }}} */ /* {{{ php_wddx_destructor */ void php_wddx_destructor(wddx_packet *packet) { smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto resource wddx_packet_start([string comment]) Starts a WDDX packet with optional comment and returns the packet id */ PHP_FUNCTION(wddx_packet_start) { char *comment = NULL; int comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx); } /* }}} */ /* {{{ proto string wddx_packet_end(resource packet_id) Ends specified WDDX packet and returns the string containing the packet */ PHP_FUNCTION(wddx_packet_end) { zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); zend_list_delete(Z_LVAL_P(packet_id)); } /* }}} */ /* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...]) Serializes given variables and adds them to packet given by packet_id */ PHP_FUNCTION(wddx_add_vars) { int num_args, i; zval ***args = NULL; zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) { efree(args); RETURN_FALSE; } if (!packet) { efree(args); RETURN_FALSE; } for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, (*args[i])); } efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; char *payload; int payload_len; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STRVAL_P(packet); payload_len = Z_STRLEN_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, &packet); if (stream) { payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload_len == 0) { return; } php_wddx_deserialize_ex(payload, payload_len, return_value); if (stream) { pefree(payload, 0); } } /* }}} */ #endif /* HAVE_LIBEXPAT */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-125/c/good_5515_1
crossvul-cpp_data_bad_2900_0
/* radare - LGPL - Copyright 2009-2017 - pancake, nibble, dso */ // TODO: dlopen library and show address #include <r_bin.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_io.h> #include <config.h> R_LIB_VERSION (r_bin); #define bprintf if(binfile->rbin->verbose)eprintf #define DB a->sdb; #define RBINLISTFREE(x)\ if (x) { \ r_list_free (x);\ x = NULL;\ } #define REBASE_PADDR(o, l, type_t)\ do { \ RListIter *_it;\ type_t *_el;\ r_list_foreach ((l), _it, _el) { \ _el->paddr += (o)->loadaddr;\ }\ } while (0) #define ARCHS_KEY "archs" #if !defined(R_BIN_STATIC_PLUGINS) #define R_BIN_STATIC_PLUGINS 0 #endif #if !defined(R_BIN_XTR_STATIC_PLUGINS) #define R_BIN_XTR_STATIC_PLUGINS 0 #endif static RBinPlugin *bin_static_plugins[] = { R_BIN_STATIC_PLUGINS, NULL }; static RBinXtrPlugin *bin_xtr_static_plugins[] = { R_BIN_XTR_STATIC_PLUGINS, NULL }; static int is_data_section(RBinFile *a, RBinSection *s); static RList *get_strings(RBinFile *a, int min, int dump); static void r_bin_object_delete_items(RBinObject *o); static void r_bin_object_free(void /*RBinObject*/ *o_); // static int r_bin_object_set_items(RBinFile *binfile, RBinObject *o); static int r_bin_file_set_bytes(RBinFile *binfile, const ut8 *bytes, ut64 sz, bool steal_ptr); //static int remove_bin_file_by_binfile (RBin *bin, RBinFile * binfile); //static void r_bin_free_bin_files (RBin *bin); static void r_bin_file_free(void /*RBinFile*/ *bf_); static RBinFile *r_bin_file_create_append(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, bool steal_ptr); static RBinFile *r_bin_file_xtr_load_bytes(RBin *bin, RBinXtrPlugin *xtr, const char *filename, const ut8 *bytes, ut64 sz, ut64 file_sz, ut64 baseaddr, ut64 loadaddr, int idx, int fd, int rawstr); int r_bin_load_io_at_offset_as_sz(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx, ut64 offset, const char *name, ut64 sz); static RBinPlugin *r_bin_get_binplugin_by_name(RBin *bin, const char *name); static RBinXtrPlugin *r_bin_get_xtrplugin_by_name(RBin *bin, const char *name); static RBinPlugin *r_bin_get_binplugin_any(RBin *bin); static RBinObject *r_bin_object_new(RBinFile *binfile, RBinPlugin *plugin, ut64 baseaddr, ut64 loadaddr, ut64 offset, ut64 sz); static RBinFile *r_bin_file_new(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, Sdb *sdb, bool steal_ptr); static RBinFile *r_bin_file_new_from_bytes(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, ut64 baseaddr, ut64 loadaddr, int fd, const char *pluginname, const char *xtrname, ut64 offset, bool steal_ptr); static int getoffset(RBin *bin, int type, int idx) { RBinFile *a = r_bin_cur (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (plugin && plugin->get_offset) { return plugin->get_offset (a, type, idx); } return -1; } static const char *getname(RBin *bin, int type, int idx) { RBinFile *a = r_bin_cur (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (plugin && plugin->get_name) { return plugin->get_name (a, type, idx); } return NULL; } static int r_bin_file_object_add(RBinFile *binfile, RBinObject *o) { if (!o) { return false; } r_list_append (binfile->objs, o); r_bin_file_set_cur_binfile_obj (binfile->rbin, binfile, o); return true; } static void binobj_set_baddr(RBinObject *o, ut64 baddr) { if (!o || baddr == UT64_MAX) { return; } o->baddr_shift = baddr - o->baddr; } static ut64 binobj_a2b(RBinObject *o, ut64 addr) { return addr + (o? o->baddr_shift: 0); } static void filterStrings (RBin *bin, RList *strings) { RBinString *ptr; RListIter *iter; r_list_foreach (strings, iter, ptr) { char *dec = (char *)r_base64_decode_dyn (ptr->string, -1); if (dec) { char *s = ptr->string; do { char *dec2 = (char *)r_base64_decode_dyn (s, -1); if (!dec2) { break; } if (!r_str_is_printable (dec2)) { free (dec2); break; } free (dec); s = dec = dec2; } while (true); if (r_str_is_printable (dec) && strlen (dec) > 3) { free (ptr->string); ptr->string = dec; ptr->type = R_STRING_TYPE_BASE64; } else { free (dec); } } } } R_API void r_bin_iobind(RBin *bin, RIO *io) { r_io_bind (io, &bin->iob); } // TODO: move these two function do a different file R_API RBinXtrData *r_bin_xtrdata_new(RBuffer *buf, ut64 offset, ut64 size, ut32 file_count, RBinXtrMetadata *metadata) { RBinXtrData *data = R_NEW0 (RBinXtrData); if (!data) { return NULL; } data->offset = offset; data->size = size; data->file_count = file_count; data->metadata = metadata; data->loaded = 0; data->buffer = malloc (size + 1); // data->laddr = 0; /// XXX if (!data->buffer) { free (data); return NULL; } memcpy (data->buffer, r_buf_buffer (buf), size); data->buffer[size] = 0; return data; } R_API const char *r_bin_string_type (int type) { switch (type) { case 'a': return "ascii"; case 'u': return "utf8"; case 'w': return "utf16le"; case 'W': return "utf32le"; case 'b': return "base64"; } return "ascii"; // XXX } R_API void r_bin_xtrdata_free(void /*RBinXtrData*/ *data_) { RBinXtrData *data = data_; if (data) { if (data->metadata) { free (data->metadata->libname); free (data->metadata->arch); free (data->metadata->machine); free (data->metadata); } free (data->file); free (data->buffer); free (data); } } R_API RBinObject *r_bin_file_object_get_cur(RBinFile *binfile) { return binfile? binfile->o: NULL; } R_API RBinObject *r_bin_object_get_cur(RBin *bin) { return bin ? r_bin_file_object_get_cur (r_bin_cur (bin)) : NULL; } R_API RBinPlugin *r_bin_file_cur_plugin(RBinFile *binfile) { return binfile && binfile->o? binfile->o->plugin: NULL; } R_API int r_bin_file_cur_set_plugin(RBinFile *binfile, RBinPlugin *plugin) { if (binfile && binfile->o) { binfile->o->plugin = plugin; return true; } return false; } // maybe too big sometimes? 2KB of stack eaten here.. #define R_STRING_SCAN_BUFFER_SIZE 2048 static int string_scan_range(RList *list, const ut8 *buf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (!buf || !min) { return -1; } while (needle < to) { rc = r_utf8_decode (buf + needle, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc; if ((to - needle) > 4) { bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4]; if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r)) { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\e", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 28) { tmp[i + 0] = '\\'; tmp[i + 1] = " abtnvfr e"[r]; } else { // string too long break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { // reduce false positives int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } if (list) { RBinString *new = R_NEW0 (RBinString); if (!new) { break; } new->type = str_type; new->length = runes; new->size = needle - str_start; new->ordinal = count++; // TODO: move into adjust_offset switch (str_type) { case R_STRING_TYPE_WIDE: { const ut8 *p = buf + str_start - 2; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: { const ut8 *p = buf + str_start - 4; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } new->paddr = new->vaddr = str_start; new->string = r_str_ndup ((const char *)tmp, i); r_list_append (list, new); } else { // DUMP TO STDOUT. raw dumping for rabin2 -zzz printf ("0x%08" PFMT64x " %s\n", str_start, tmp); } } } return count; } static void get_strings_range(RBinFile *arch, RList *list, int min, ut64 from, ut64 to) { RBinPlugin *plugin = r_bin_file_cur_plugin (arch); RBinString *ptr; RListIter *it; if (!arch || !arch->buf || !arch->buf->buf) { return; } if (!arch->rawstr) { if (!plugin || !plugin->info) { return; } } if (!min) { min = plugin? plugin->minstrlen: 4; } /* Some plugins return zero, fix it up */ if (!min) { min = 4; } if (min < 0) { return; } if (!to || to > arch->buf->length) { to = arch->buf->length; } if (arch->rawstr != 2) { ut64 size = to - from; // in case of dump ignore here if (arch->rbin->maxstrbuf && size && size > arch->rbin->maxstrbuf) { if (arch->rbin->verbose) { eprintf ("WARNING: bin_strings buffer is too big " "(0x%08" PFMT64x ")." " Use -zzz or set bin.maxstrbuf " "(RABIN2_MAXSTRBUF) in r2 (rabin2)\n", size); } return; } } if (string_scan_range (list, arch->buf->buf, min, from, to, -1) < 0) { return; } r_list_foreach (list, it, ptr) { RBinSection *s = r_bin_get_section_at (arch->o, ptr->paddr, false); if (s) { ptr->vaddr = s->vaddr + (ptr->paddr - s->paddr); } } } static int is_data_section(RBinFile *a, RBinSection *s) { if (s->has_strings || s->is_data) { return true; } if (s->is_data) { return true; } // Rust return (strstr (s->name, "_const") != NULL); } static RList *get_strings(RBinFile *a, int min, int dump) { RListIter *iter; RBinSection *section; RBinObject *o = a? a->o: NULL; RList *ret; if (!o) { return NULL; } if (dump) { /* dump to stdout, not stored in list */ ret = NULL; } else { ret = r_list_newf (r_bin_string_free); if (!ret) { return NULL; } } if (o->sections && !r_list_empty (o->sections) && !a->rawstr) { r_list_foreach (o->sections, iter, section) { if (is_data_section (a, section)) { get_strings_range (a, ret, min, section->paddr, section->paddr + section->size); } } r_list_foreach (o->sections, iter, section) { RBinString *s; RListIter *iter2; /* load objc/swift strings */ const int bits = (a->o && a->o->info) ? a->o->info->bits : 32; const int cfstr_size = (bits == 64) ? 32 : 16; const int cfstr_offs = (bits == 64) ? 16 : 8; if (strstr (section->name, "__cfstring")) { int i; // XXX do not walk if bin.strings == 0 ut8 *p; for (i = 0; i < section->size; i += cfstr_size) { ut8 buf[32]; if (!r_buf_read_at ( a->buf, section->paddr + i + cfstr_offs, buf, sizeof (buf))) { break; } p = buf; ut64 cfstr_vaddr = section->vaddr + i; ut64 cstr_vaddr = (bits == 64) ? r_read_le64 (p) : r_read_le32 (p); r_list_foreach (ret, iter2, s) { if (s->vaddr == cstr_vaddr) { RBinString *new = R_NEW0 (RBinString); new->type = s->type; new->length = s->length; new->size = s->size; new->ordinal = s->ordinal; new->paddr = new->vaddr = cfstr_vaddr; new->string = r_str_newf ("cstr.%s", s->string); r_list_append (ret, new); break; } } } } } } else { get_strings_range (a, ret, min, 0, a->size); } return ret; } R_API RList* r_bin_raw_strings(RBinFile *a, int min) { RList *l = NULL; if (a) { int tmp = a->rawstr; a->rawstr = 2; l = get_strings (a, min, 0); a->rawstr = tmp; } return l; } R_API int r_bin_dump_strings(RBinFile *a, int min) { get_strings (a, min, 1); return 0; } /* This is very slow if there are lot of symbols */ R_API int r_bin_load_languages(RBinFile *binfile) { if (r_bin_lang_rust (binfile)) { return R_BIN_NM_RUST; } if (r_bin_lang_swift (binfile)) { return R_BIN_NM_SWIFT; } if (r_bin_lang_objc (binfile)) { return R_BIN_NM_OBJC; } if (r_bin_lang_cxx (binfile)) { return R_BIN_NM_CXX; } if (r_bin_lang_dlang (binfile)) { return R_BIN_NM_DLANG; } if (r_bin_lang_msvc (binfile)) { return R_BIN_NM_MSVC; } return R_BIN_NM_NONE; } static void mem_free(void *data) { RBinMem *mem = (RBinMem *)data; if (mem && mem->mirrors) { mem->mirrors->free = mem_free; r_list_free (mem->mirrors); mem->mirrors = NULL; } free (mem); } static void r_bin_object_delete_items(RBinObject *o) { ut32 i = 0; if (!o) { return; } r_list_free (o->entries); r_list_free (o->fields); r_list_free (o->imports); r_list_free (o->libs); r_list_free (o->relocs); r_list_free (o->sections); r_list_free (o->strings); r_list_free (o->symbols); r_list_free (o->classes); r_list_free (o->lines); sdb_free (o->kv); if (o->mem) { o->mem->free = mem_free; } r_list_free (o->mem); o->mem = NULL; o->entries = NULL; o->fields = NULL; o->imports = NULL; o->libs = NULL; o->relocs = NULL; o->sections = NULL; o->strings = NULL; o->symbols = NULL; o->classes = NULL; o->lines = NULL; o->info = NULL; o->kv = NULL; for (i = 0; i < R_BIN_SYM_LAST; i++) { free (o->binsym[i]); o->binsym[i] = NULL; } } R_API void r_bin_info_free(RBinInfo *rb) { if (!rb) { return; } free (rb->intrp); free (rb->file); free (rb->type); free (rb->bclass); free (rb->rclass); free (rb->arch); free (rb->cpu); free (rb->machine); free (rb->os); free (rb->subsystem); free (rb->rpath); free (rb->guid); free (rb->debug_file_name); free (rb); } R_API void r_bin_import_free(void *_imp) { RBinImport *imp = (RBinImport *)_imp; if (imp) { R_FREE (imp->name); R_FREE (imp->classname); R_FREE (imp->descriptor); free (imp); } } R_API void r_bin_symbol_free(void *_sym) { RBinSymbol *sym = (RBinSymbol *)_sym; free (sym->name); free (sym->classname); free (sym); } R_API void r_bin_string_free(void *_str) { RBinString *str = (RBinString *)_str; free (str->string); free (str); } static void r_bin_object_free(void /*RBinObject*/ *o_) { RBinObject *o = o_; if (!o) { return; } r_bin_info_free (o->info); r_bin_object_delete_items (o); R_FREE (o); } static char *swiftField(const char *dn, const char *cn) { char *p = strstr (dn, ".getter_"); if (!p) { p = strstr (dn, ".setter_"); if (!p) { p = strstr (dn, ".method_"); } } if (p) { char *q = strstr (dn, cn); if (q && q[strlen (cn)] == '.') { q = strdup (q + strlen (cn) + 1); char *r = strchr (q, '.'); if (r) { *r = 0; } return q; } } return NULL; } R_API RList *r_bin_classes_from_symbols (RBinFile *bf, RBinObject *o) { RBinSymbol *sym; RListIter *iter; RList *symbols = o->symbols; RList *classes = o->classes; if (!classes) { classes = r_list_newf ((RListFree)r_bin_class_free); } r_list_foreach (symbols, iter, sym) { if (sym->name[0] != '_') { continue; } const char *cn = sym->classname; if (cn) { RBinClass *c = r_bin_class_new (bf, sym->classname, NULL, 0); if (!c) { continue; } // swift specific char *dn = sym->dname; char *fn = swiftField (dn, cn); if (fn) { // eprintf ("FIELD %s %s\n", cn, fn); RBinField *f = r_bin_field_new (sym->paddr, sym->vaddr, sym->size, fn, NULL, NULL); r_list_append (c->fields, f); free (fn); } else { char *mn = strstr (dn, ".."); if (mn) { // eprintf ("META %s %s\n", sym->classname, mn); } else { char *mn = strstr (dn, cn); if (mn && mn[strlen(cn)] == '.') { mn += strlen (cn) + 1; // eprintf ("METHOD %s %s\n", sym->classname, mn); r_list_append (c->methods, sym); } } } } } if (r_list_empty (classes)) { r_list_free (classes); return NULL; } return classes; } // XXX - change this to RBinObject instead of RBinFile // makes no sense to pass in a binfile and set the RBinObject // kinda a clunky functions R_API int r_bin_object_set_items(RBinFile *binfile, RBinObject *o) { RBinObject *old_o; RBinPlugin *cp; int i, minlen; RBin *bin; if (!binfile || !o || !o->plugin) { return false; } bin = binfile->rbin; old_o = binfile->o; cp = o->plugin; if (binfile->rbin->minstrlen > 0) { minlen = binfile->rbin->minstrlen; } else { minlen = cp->minstrlen; } binfile->o = o; if (cp->baddr) { ut64 old_baddr = o->baddr; o->baddr = cp->baddr (binfile); binobj_set_baddr (o, old_baddr); } if (cp->boffset) { o->boffset = cp->boffset (binfile); } // XXX: no way to get info from xtr pluginz? // Note, object size can not be set from here due to potential // inconsistencies if (cp->size) { o->size = cp->size (binfile); } if (cp->binsym) { for (i = 0; i < R_BIN_SYM_LAST; i++) { o->binsym[i] = cp->binsym (binfile, i); if (o->binsym[i]) { o->binsym[i]->paddr += o->loadaddr; } } } if (cp->entries) { o->entries = cp->entries (binfile); REBASE_PADDR (o, o->entries, RBinAddr); } if (cp->fields) { o->fields = cp->fields (binfile); if (o->fields) { o->fields->free = r_bin_field_free; REBASE_PADDR (o, o->fields, RBinField); } } if (cp->imports) { r_list_free (o->imports); o->imports = cp->imports (binfile); if (o->imports) { o->imports->free = r_bin_import_free; } } //if (bin->filter_rules & (R_BIN_REQ_SYMBOLS | R_BIN_REQ_IMPORTS)) { if (true) { if (cp->symbols) { o->symbols = cp->symbols (binfile); if (o->symbols) { o->symbols->free = r_bin_symbol_free; REBASE_PADDR (o, o->symbols, RBinSymbol); if (bin->filter) { r_bin_filter_symbols (o->symbols); } } } } //} o->info = cp->info? cp->info (binfile): NULL; if (cp->libs) { o->libs = cp->libs (binfile); } if (cp->sections) { // XXX sections are populated by call to size if (!o->sections) { o->sections = cp->sections (binfile); } REBASE_PADDR (o, o->sections, RBinSection); if (bin->filter) { r_bin_filter_sections (o->sections); } } if (bin->filter_rules & (R_BIN_REQ_RELOCS | R_BIN_REQ_IMPORTS)) { if (cp->relocs) { o->relocs = cp->relocs (binfile); REBASE_PADDR (o, o->relocs, RBinReloc); } } if (bin->filter_rules & R_BIN_REQ_STRINGS) { if (cp->strings) { o->strings = cp->strings (binfile); } else { o->strings = get_strings (binfile, minlen, 0); } if (bin->debase64) { filterStrings (bin, o->strings); } REBASE_PADDR (o, o->strings, RBinString); } if (bin->filter_rules & R_BIN_REQ_CLASSES) { if (cp->classes) { o->classes = cp->classes (binfile); if (r_bin_lang_swift (binfile)) { o->classes = r_bin_classes_from_symbols (binfile, o); } } else { o->classes = r_bin_classes_from_symbols (binfile, o); } if (bin->filter) { r_bin_filter_classes (o->classes); } } if (cp->lines) { o->lines = cp->lines (binfile); } if (cp->get_sdb) { Sdb* new_kv = cp->get_sdb (binfile); if (new_kv != o->kv) { sdb_free (o->kv); } o->kv = new_kv; } if (cp->mem) { o->mem = cp->mem (binfile); } if (bin->filter_rules & (R_BIN_REQ_SYMBOLS | R_BIN_REQ_IMPORTS)) { o->lang = r_bin_load_languages (binfile); } binfile->o = old_o; return true; } // XXX - this is a rather hacky way to do things, there may need to be a better // way. R_API int r_bin_load(RBin *bin, const char *file, ut64 baseaddr, ut64 loadaddr, int xtr_idx, int fd, int rawstr) { if (!bin) { return false; } // ALIAS? return r_bin_load_as (bin, file, baseaddr, loadaddr, // xtr_idx, fd, rawstr, 0, file); RIOBind *iob = &(bin->iob); if (!iob) { return false; } if (!iob->io) { iob->io = r_io_new (); //wtf if (!iob->io) { return false; } bin->io_owned = true; r_io_bind (iob->io, &bin->iob); //memleak? iob = &bin->iob; } if (!iob->desc_get (iob->io, fd)) { fd = iob->fd_open (iob->io, file, R_IO_READ, 0644); } bin->rawstr = rawstr; // Use the current RIODesc otherwise r_io_map_select can swap them later on if (fd < 0) { r_io_free (iob->io); memset (&bin->iob, 0, sizeof (bin->iob)); bin->io_owned = false; return false; } //Use the current RIODesc otherwise r_io_map_select can swap them later on return r_bin_load_io (bin, fd, baseaddr, loadaddr, xtr_idx); } R_API int r_bin_load_as(RBin *bin, const char *file, ut64 baseaddr, ut64 loadaddr, int xtr_idx, int fd, int rawstr, int fileoffset, const char *name) { RIOBind *iob = &(bin->iob); if (!iob || !iob->io) { return false; } if (fd < 0) { fd = iob->fd_open (iob->io, file, R_IO_READ, 0644); } if (fd < 0) { return false; } return r_bin_load_io_at_offset_as (bin, fd, baseaddr, loadaddr, xtr_idx, fileoffset, name); } R_API int r_bin_reload(RBin *bin, int fd, ut64 baseaddr) { RIOBind *iob = &(bin->iob); RList *the_obj_list = NULL; int res = false; RBinFile *bf = NULL; ut8 *buf_bytes = NULL; ut64 sz = UT64_MAX; if (!iob || !iob->io) { res = false; goto error; } const char *name = iob->fd_get_name (iob->io, fd); bf = r_bin_file_find_by_name (bin, name); if (!bf) { res = false; goto error; } the_obj_list = bf->objs; bf->objs = r_list_newf ((RListFree)r_bin_object_free); // invalidate current object reference bf->o = NULL; sz = iob->fd_size (iob->io, fd); if (sz == UT64_MAX || sz > (64 * 1024 * 1024)) { // too big, probably wrong eprintf ("Too big\n"); res = false; goto error; } if (sz == UT64_MAX && iob->fd_is_dbg (iob->io, fd)) { // attempt a local open and read // This happens when a plugin like debugger does not have a // fixed size. // if there is no fixed size or its MAXED, there is no way to // definitively // load the bin-properly. Many of the plugins require all // content and are not // stream based loaders int tfd = iob->fd_open (iob->io, name, R_IO_READ, 0); if (tfd < 0) { res = false; goto error; } sz = iob->fd_size (iob->io, tfd); if (sz == UT64_MAX) { iob->fd_close (iob->io, tfd); res = false; goto error; } buf_bytes = calloc (1, sz + 1); if (!buf_bytes) { iob->fd_close (iob->io, tfd); res = false; goto error; } if (!iob->read_at (iob->io, 0LL, buf_bytes, sz)) { free (buf_bytes); iob->fd_close (iob->io, tfd); res = false; goto error; } iob->fd_close (iob->io, tfd); } else { buf_bytes = calloc (1, sz + 1); if (!buf_bytes) { res = false; goto error; } if (!iob->fd_read_at (iob->io, fd, 0LL, buf_bytes, sz)) { free (buf_bytes); res = false; goto error; } } bool yes_plz_steal_ptr = true; r_bin_file_set_bytes (bf, buf_bytes, sz, yes_plz_steal_ptr); if (r_list_length (the_obj_list) == 1) { RBinObject *old_o = (RBinObject *)r_list_get_n (the_obj_list, 0); res = r_bin_load_io_at_offset_as (bin, fd, baseaddr, old_o->loadaddr, 0, old_o->boffset, NULL); } else { RListIter *iter = NULL; RBinObject *old_o; r_list_foreach (the_obj_list, iter, old_o) { // XXX - naive. do we need a way to prevent multiple "anys" from being opened? res = r_bin_load_io_at_offset_as (bin, fd, baseaddr, old_o->loadaddr, 0, old_o->boffset, old_o->plugin->name); } } bf->o = r_list_get_n (bf->objs, 0); error: r_list_free (the_obj_list); return res; } R_API int r_bin_load_io(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx) { return r_bin_load_io_at_offset_as (bin, fd, baseaddr, loadaddr, xtr_idx, 0, NULL); } R_API int r_bin_load_io_at_offset_as_sz(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx, ut64 offset, const char *name, ut64 sz) { RIOBind *iob = &(bin->iob); RIO *io = iob? iob->io: NULL; RListIter *it; ut8 *buf_bytes = NULL; RBinXtrPlugin *xtr; ut64 file_sz = UT64_MAX; RBinFile *binfile = NULL; int tfd = -1; if (!io || (fd < 0) || (st64)sz < 0) { return false; } bool is_debugger = iob->fd_is_dbg (io, fd); const char *fname = iob->fd_get_name (io, fd); if (loadaddr == UT64_MAX) { loadaddr = 0; } file_sz = iob->fd_size (io, fd); // file_sz = UT64_MAX happens when attaching to frida:// and other non-debugger io plugins which results in double opening if (is_debugger && file_sz == UT64_MAX) { tfd = iob->fd_open (io, fname, R_IO_READ, 0644); if (tfd >= 1) { file_sz = iob->fd_size (io, tfd); } } if (!sz) { sz = file_sz; } bin->file = fname; sz = R_MIN (file_sz, sz); if (!r_list_length (bin->binfiles)) { if (is_debugger) { //use the temporal RIODesc to read the content of the file instead //from the memory if (tfd >= 0) { buf_bytes = calloc (1, sz + 1); iob->fd_read_at (io, tfd, 0, buf_bytes, sz); // iob->fd_close (io, tfd); } } } if (!buf_bytes) { buf_bytes = calloc (1, sz + 1); if (!buf_bytes) { return false; } ut64 seekaddr = is_debugger? baseaddr: loadaddr; if (!iob->fd_read_at (io, fd, seekaddr, buf_bytes, sz)) { sz = 0LL; } } if (!name && (st64)sz > 0) { // XXX - for the time being this is fine, but we may want to // change the name to something like // <xtr_name>:<bin_type_name> r_list_foreach (bin->binxtrs, it, xtr) { if (xtr && xtr->check_bytes (buf_bytes, sz)) { if (xtr && (xtr->extract_from_bytes || xtr->extractall_from_bytes)) { if (is_debugger && sz != file_sz) { R_FREE (buf_bytes); if (tfd < 0) { tfd = iob->fd_open (io, fname, R_IO_READ, 0); } sz = iob->fd_size (io, tfd); if (sz != UT64_MAX) { buf_bytes = calloc (1, sz + 1); if (buf_bytes) { (void) iob->fd_read_at (io, tfd, 0, buf_bytes, sz); } } //DOUBLECLOSE UAF : iob->fd_close (io, tfd); tfd = -1; // marking it closed } else if (sz != file_sz) { (void) iob->read_at (io, 0LL, buf_bytes, sz); } binfile = r_bin_file_xtr_load_bytes (bin, xtr, fname, buf_bytes, sz, file_sz, baseaddr, loadaddr, xtr_idx, fd, bin->rawstr); } xtr = NULL; } } } if (!binfile) { bool steal_ptr = true; // transfer buf_bytes ownership to binfile binfile = r_bin_file_new_from_bytes ( bin, fname, buf_bytes, sz, file_sz, bin->rawstr, baseaddr, loadaddr, fd, name, NULL, offset, steal_ptr); } return binfile? r_bin_file_set_cur_binfile (bin, binfile): false; } R_API bool r_bin_load_io_at_offset_as(RBin *bin, int fd, ut64 baseaddr, ut64 loadaddr, int xtr_idx, ut64 offset, const char *name) { // adding file_sz to help reduce the performance impact on the system // in this case the number of bytes read will be limited to 2MB // (MIN_LOAD_SIZE) // if it fails, the whole file is loaded. const ut64 MAX_LOAD_SIZE = 0; // 0xfffff; //128 * (1 << 10 << 10); int res = r_bin_load_io_at_offset_as_sz (bin, fd, baseaddr, loadaddr, xtr_idx, offset, name, MAX_LOAD_SIZE); if (!res) { res = r_bin_load_io_at_offset_as_sz (bin, fd, baseaddr, loadaddr, xtr_idx, offset, name, UT64_MAX); } return res; } R_API int r_bin_file_deref_by_bind(RBinBind *binb) { RBin *bin = binb? binb->bin: NULL; RBinFile *a = r_bin_cur (bin); return r_bin_file_deref (bin, a); } R_API int r_bin_file_deref(RBin *bin, RBinFile *a) { RBinObject *o = r_bin_cur_object (bin); int res = false; if (a && !o) { //r_list_delete_data (bin->binfiles, a); res = true; } else if (a && o->referenced - 1 < 1) { //r_list_delete_data (bin->binfiles, a); res = true; // not thread safe } else if (o) { o->referenced--; } // it is possible for a file not // to be bound to RBin and RBinFiles // XXX - is this an ok assumption? if (bin) bin->cur = NULL; return res; } R_API int r_bin_file_ref_by_bind(RBinBind *binb) { RBin *bin = binb? binb->bin: NULL; RBinFile *a = r_bin_cur (bin); return r_bin_file_ref (bin, a); } R_API int r_bin_file_ref(RBin *bin, RBinFile *a) { RBinObject *o = r_bin_cur_object (bin); if (a && o) { o->referenced--; return true; } return false; } static void r_bin_file_free(void /*RBinFile*/ *bf_) { RBinFile *a = bf_; RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (!a) { return; } // Binary format objects are connected to the // RBinObject, so the plugin must destroy the // format data first if (plugin && plugin->destroy) { plugin->destroy (a); } if (a->curxtr && a->curxtr->destroy && a->xtr_obj) { a->curxtr->free_xtr ((void *)(a->xtr_obj)); } r_buf_free (a->buf); // TODO: unset related sdb namespaces if (a && a->sdb_addrinfo) { sdb_free (a->sdb_addrinfo); a->sdb_addrinfo = NULL; } free (a->file); a->o = NULL; r_list_free (a->objs); r_list_free (a->xtr_data); r_id_pool_kick_id (a->rbin->file_ids, a->id); memset (a, 0, sizeof (RBinFile)); free (a); } static RBinFile *r_bin_file_create_append(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, bool steal_ptr) { RBinFile *bf = r_bin_file_new (bin, file, bytes, sz, file_sz, rawstr, fd, xtrname, bin->sdb, steal_ptr); if (bf) { r_list_append (bin->binfiles, bf); } return bf; } // This function populate RBinFile->xtr_data, that information is enough to // create RBinObject when needed using r_bin_file_object_new_from_xtr_data static RBinFile *r_bin_file_xtr_load_bytes(RBin *bin, RBinXtrPlugin *xtr, const char *filename, const ut8 *bytes, ut64 sz, ut64 file_sz, ut64 baseaddr, ut64 loadaddr, int idx, int fd, int rawstr) { if (!bin || !bytes) { return NULL; } RBinFile *bf = r_bin_file_find_by_name (bin, filename); if (!bf) { bf = r_bin_file_create_append (bin, filename, bytes, sz, file_sz, rawstr, fd, xtr->name, false); if (!bf) { return NULL; } if (!bin->cur) { bin->cur = bf; } } if (bf->xtr_data) { r_list_free (bf->xtr_data); } if (xtr && bytes) { RList *xtr_data_list = xtr->extractall_from_bytes (bin, bytes, sz); RListIter *iter; RBinXtrData *xtr; //populate xtr_data with baddr and laddr that will be used later on //r_bin_file_object_new_from_xtr_data r_list_foreach (xtr_data_list, iter, xtr) { xtr->baddr = baseaddr? baseaddr : UT64_MAX; xtr->laddr = loadaddr? loadaddr : UT64_MAX; } bf->loadaddr = loadaddr; bf->xtr_data = xtr_data_list ? xtr_data_list : NULL; } return bf; } static RBinPlugin *r_bin_get_binplugin_by_name(RBin *bin, const char *name) { RBinPlugin *plugin; RListIter *it; if (bin && name) { r_list_foreach (bin->plugins, it, plugin) { if (!strcmp (plugin->name, name)) { return plugin; } } } return NULL; } R_API RBinPlugin *r_bin_get_binplugin_by_bytes(RBin *bin, const ut8 *bytes, ut64 sz) { RBinPlugin *plugin; RListIter *it; if (!bin || !bytes) { return NULL; } r_list_foreach (bin->plugins, it, plugin) { if (plugin->check_bytes && plugin->check_bytes (bytes, sz)) { return plugin; } } return NULL; } static RBinXtrPlugin *r_bin_get_xtrplugin_by_name(RBin *bin, const char *name) { RBinXtrPlugin *xtr; RListIter *it; if (!bin || !name) return NULL; r_list_foreach (bin->binxtrs, it, xtr) { if (!strcmp (xtr->name, name)) { return xtr; } // must be set to null xtr = NULL; } return NULL; } static RBinPlugin *r_bin_get_binplugin_any(RBin *bin) { return r_bin_get_binplugin_by_name (bin, "any"); } static RBinObject *r_bin_object_new(RBinFile *binfile, RBinPlugin *plugin, ut64 baseaddr, ut64 loadaddr, ut64 offset, ut64 sz) { const ut8 *bytes = binfile? r_buf_buffer (binfile->buf): NULL; ut64 bytes_sz = binfile? r_buf_size (binfile->buf): 0; Sdb *sdb = binfile? binfile->sdb: NULL; RBinObject *o = R_NEW0 (RBinObject); if (!o) { return NULL; } o->obj_size = bytes && (bytes_sz >= sz + offset)? sz: 0; o->boffset = offset; o->id = r_num_rand (0xfffff000); o->kv = sdb_new0 (); o->baddr = baseaddr; o->baddr_shift = 0; o->plugin = plugin; o->loadaddr = loadaddr != UT64_MAX ? loadaddr : 0; // XXX more checking will be needed here // only use LoadBytes if buffer offset != 0 // if (offset != 0 && bytes && plugin && plugin->load_bytes && (bytes_sz // >= sz + offset) ) { if (bytes && plugin && plugin->load_bytes && (bytes_sz >= sz + offset)) { ut64 bsz = bytes_sz - offset; if (sz < bsz) { bsz = sz; } o->bin_obj = plugin->load_bytes (binfile, bytes + offset, sz, loadaddr, sdb); if (!o->bin_obj) { bprintf ( "Error in r_bin_object_new: load_bytes failed " "for %s plugin\n", plugin->name); sdb_free (o->kv); free (o); return NULL; } } else if (binfile && plugin && plugin->load) { // XXX - haha, this is a hack. // switching out the current object for the new // one to be processed RBinObject *old_o = binfile->o; binfile->o = o; if (plugin->load (binfile)) { binfile->sdb_info = o->kv; // mark as do not walk sdb_ns_set (binfile->sdb, "info", o->kv); } else { binfile->o = old_o; } o->obj_size = sz; } else { sdb_free (o->kv); free (o); return NULL; } // XXX - binfile could be null here meaning an improper load // XXX - object size cant be set here and needs to be set where // where the object is created from. The reason for this is to prevent // mis-reporting when the file is loaded from impartial bytes or is // extracted // from a set of bytes in the file r_bin_object_set_items (binfile, o); r_bin_file_object_add (binfile, o); // XXX this is a very hacky alternative to rewriting the // RIO stuff, as discussed here: return o; } #define LIMIT_SIZE 0 static int r_bin_file_set_bytes(RBinFile *binfile, const ut8 *bytes, ut64 sz, bool steal_ptr) { if (!bytes) { return false; } r_buf_free (binfile->buf); binfile->buf = r_buf_new (); #if LIMIT_SIZE if (sz > 1024 * 1024) { eprintf ("Too big\n"); // TODO: use r_buf_io instead of setbytes all the time to save memory return NULL; } #else if (steal_ptr) { r_buf_set_bytes_steal (binfile->buf, bytes, sz); } else { r_buf_set_bytes (binfile->buf, bytes, sz); } #endif return binfile->buf != NULL; } static RBinFile *r_bin_file_new(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, int fd, const char *xtrname, Sdb *sdb, bool steal_ptr) { RBinFile *binfile = R_NEW0 (RBinFile); if (!binfile) { return NULL; } if (!r_id_pool_grab_id (bin->file_ids, &binfile->id)) { if (steal_ptr) { // we own the ptr, free on error free ((void*) bytes); } free (binfile); //no id means no binfile return NULL; } int res = r_bin_file_set_bytes (binfile, bytes, sz, steal_ptr); if (!res && steal_ptr) { // we own the ptr, free on error free((void*) bytes); } binfile->rbin = bin; binfile->file = file? strdup (file): NULL; binfile->rawstr = rawstr; binfile->fd = fd; binfile->curxtr = r_bin_get_xtrplugin_by_name (bin, xtrname); binfile->sdb = sdb; binfile->size = file_sz; binfile->xtr_data = r_list_newf ((RListFree)r_bin_xtrdata_free); binfile->objs = r_list_newf ((RListFree)r_bin_object_free); binfile->xtr_obj = NULL; if (!binfile->buf) { //r_bin_file_free (binfile); binfile->buf = r_buf_new (); // return NULL; } if (sdb) { binfile->sdb = sdb_ns (sdb, sdb_fmt (0, "fd.%d", fd), 1); sdb_set (binfile->sdb, "archs", "0:0:x86:32", 0); // x86?? /* NOTE */ /* Those refs++ are necessary because sdb_ns() doesnt rerefs all * sub-namespaces */ /* And if any namespace is referenced backwards it gets * double-freed */ binfile->sdb_addrinfo = sdb_ns (binfile->sdb, "addrinfo", 1); binfile->sdb_addrinfo->refs++; sdb_ns_set (sdb, "cur", binfile->sdb); binfile->sdb->refs++; } return binfile; } R_API bool r_bin_file_object_new_from_xtr_data(RBin *bin, RBinFile *bf, ut64 baseaddr, ut64 loadaddr, RBinXtrData *data) { RBinObject *o = NULL; RBinPlugin *plugin = NULL; ut8* bytes; ut64 offset = data? data->offset: 0; ut64 sz = data ? data->size : 0; if (!data || !bf) { return false; } // for right now the bytes used will just be the offest into the binfile // buffer // if the extraction requires some sort of transformation then this will // need to be fixed // here. bytes = data->buffer; if (!bytes) { return false; } plugin = r_bin_get_binplugin_by_bytes (bin, (const ut8*)bytes, sz); if (!plugin) { plugin = r_bin_get_binplugin_any (bin); } r_buf_free (bf->buf); bf->buf = r_buf_new_with_bytes ((const ut8*)bytes, data->size); //r_bin_object_new append the new object into binfile o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, offset, sz); // size is set here because the reported size of the object depends on // if loaded from xtr plugin or partially read if (!o) { return false; } if (o && !o->size) { o->size = sz; } bf->narch = data->file_count; if (!o->info) { o->info = R_NEW0 (RBinInfo); } free (o->info->file); free (o->info->arch); free (o->info->machine); free (o->info->type); o->info->file = strdup (bf->file); o->info->arch = strdup (data->metadata->arch); o->info->machine = strdup (data->metadata->machine); o->info->type = strdup (data->metadata->type); o->info->bits = data->metadata->bits; o->info->has_crypto = bf->o->info->has_crypto; data->loaded = true; return true; } static RBinFile *r_bin_file_new_from_bytes(RBin *bin, const char *file, const ut8 *bytes, ut64 sz, ut64 file_sz, int rawstr, ut64 baseaddr, ut64 loadaddr, int fd, const char *pluginname, const char *xtrname, ut64 offset, bool steal_ptr) { ut8 binfile_created = false; RBinPlugin *plugin = NULL; RBinXtrPlugin *xtr = NULL; RBinObject *o = NULL; RBinFile *bf = NULL; if (sz == UT64_MAX) { return NULL; } if (xtrname) { xtr = r_bin_get_xtrplugin_by_name (bin, xtrname); } if (xtr && xtr->check_bytes (bytes, sz)) { return r_bin_file_xtr_load_bytes (bin, xtr, file, bytes, sz, file_sz, baseaddr, loadaddr, 0, fd, rawstr); } if (!bf) { bf = r_bin_file_create_append (bin, file, bytes, sz, file_sz, rawstr, fd, xtrname, steal_ptr); if (!bf) { if (!steal_ptr) { // we own the ptr, free on error free ((void*) bytes); } return NULL; } binfile_created = true; } if (bin->force) { plugin = r_bin_get_binplugin_by_name (bin, bin->force); } if (!plugin) { if (pluginname) { plugin = r_bin_get_binplugin_by_name (bin, pluginname); } if (!plugin) { plugin = r_bin_get_binplugin_by_bytes (bin, bytes, sz); if (!plugin) { plugin = r_bin_get_binplugin_any (bin); } } } o = r_bin_object_new (bf, plugin, baseaddr, loadaddr, 0, r_buf_size (bf->buf)); // size is set here because the reported size of the object depends on // if loaded from xtr plugin or partially read if (o && !o->size) { o->size = file_sz; } if (!o) { if (bf && binfile_created) { r_list_delete_data (bin->binfiles, bf); } return NULL; } /* WTF */ if (strcmp (plugin->name, "any")) { bf->narch = 1; } /* free unnecessary rbuffer (???) */ return bf; } static void plugin_free(RBinPlugin *p) { if (p && p->fini) { p->fini (NULL); } R_FREE (p); } // rename to r_bin_plugin_add like the rest R_API int r_bin_add(RBin *bin, RBinPlugin *foo) { RListIter *it; RBinPlugin *plugin; if (foo->init) { foo->init (bin->user); } r_list_foreach (bin->plugins, it, plugin) { if (!strcmp (plugin->name, foo->name)) { return false; } } plugin = R_NEW0 (RBinPlugin); memcpy (plugin, foo, sizeof (RBinPlugin)); r_list_append (bin->plugins, plugin); return true; } R_API int r_bin_xtr_add(RBin *bin, RBinXtrPlugin *foo) { RListIter *it; RBinXtrPlugin *xtr; if (foo->init) { foo->init (bin->user); } // avoid duplicates r_list_foreach (bin->binxtrs, it, xtr) { if (!strcmp (xtr->name, foo->name)) { return false; } } r_list_append (bin->binxtrs, foo); return true; } R_API void *r_bin_free(RBin *bin) { if (!bin) { return NULL; } if (bin->io_owned) { r_io_free (bin->iob.io); } bin->file = NULL; free (bin->force); free (bin->srcdir); //r_bin_free_bin_files (bin); r_list_free (bin->binfiles); r_list_free (bin->binxtrs); r_list_free (bin->plugins); sdb_free (bin->sdb); r_id_pool_free (bin->file_ids); memset (bin, 0, sizeof (RBin)); free (bin); return NULL; } static int r_bin_print_plugin_details(RBin *bin, RBinPlugin *bp, int json) { if (json == 'q') { bin->cb_printf ("%s\n", bp->name); } else if (json) { bin->cb_printf ( "{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}\n", bp->name, bp->desc, bp->license? bp->license: "???"); } else { bin->cb_printf ("Name: %s\n", bp->name); bin->cb_printf ("Description: %s\n", bp->desc); if (bp->license) { bin->cb_printf ("License: %s\n", bp->license); } if (bp->version) { bin->cb_printf ("Version: %s\n", bp->version); } if (bp->author) { bin->cb_printf ("Author: %s\n", bp->author); } } return true; } static int r_bin_print_xtrplugin_details(RBin *bin, RBinXtrPlugin *bx, int json) { if (json == 'q') { bin->cb_printf ("%s\n", bx->name); } else if (json) { bin->cb_printf ( "{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}\n", bx->name, bx->desc, bx->license? bx->license: "???"); } else { bin->cb_printf ("Name: %s\n", bx->name); bin->cb_printf ("Description: %s\n", bx->desc); if (bx->license) { bin->cb_printf ("License: %s\n", bx->license); } } return true; } R_API int r_bin_list(RBin *bin, int json) { RListIter *it; RBinPlugin *bp; RBinXtrPlugin *bx; if (json == 'q') { r_list_foreach (bin->plugins, it, bp) { bin->cb_printf ("%s\n", bp->name); } r_list_foreach (bin->binxtrs, it, bx) { bin->cb_printf ("%s\n", bx->name); } } else if (json) { int i; i = 0; bin->cb_printf ("{\"bin\":["); r_list_foreach (bin->plugins, it, bp) { bin->cb_printf ( "%s{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}", i? ",": "", bp->name, bp->desc, bp->license? bp->license: "???"); i++; } i = 0; bin->cb_printf ("],\"xtr\":["); r_list_foreach (bin->binxtrs, it, bx) { bin->cb_printf ( "%s{\"name\":\"%s\",\"description\":\"%s\"," "\"license\":\"%s\"}", i? ",": "", bx->name, bx->desc, bx->license? bx->license: "???"); i++; } bin->cb_printf ("]}\n"); } else { r_list_foreach (bin->plugins, it, bp) { bin->cb_printf ("bin %-11s %s (%s) %s %s\n", bp->name, bp->desc, bp->license? bp->license: "???", bp->version? bp->version: "", bp->author? bp->author: ""); } r_list_foreach (bin->binxtrs, it, bx) { bin->cb_printf ("xtr %-11s %s (%s)\n", bx->name, bx->desc, bx->license? bx->license: "???"); } } return false; } R_API int r_bin_list_plugin(RBin *bin, const char* name, int json) { RListIter *it; RBinPlugin *bp; RBinXtrPlugin *bx; r_list_foreach (bin->plugins, it, bp) { if (!r_str_cmp (name, bp->name, strlen (name))) { continue; } return r_bin_print_plugin_details (bin, bp, json); } r_list_foreach (bin->binxtrs, it, bx) { if (!r_str_cmp (name, bx->name, strlen (name))) { continue; } return r_bin_print_xtrplugin_details (bin, bx, json); } eprintf ("cannot find plugin %s\n", name); return false; } static ut64 binobj_get_baddr(RBinObject *o) { return o? o->baddr + o->baddr_shift: UT64_MAX; } R_API ut64 r_binfile_get_baddr(RBinFile *binfile) { return binfile? binobj_get_baddr (binfile->o): UT64_MAX; } /* returns the base address of bin or UT64_MAX in case of errors */ R_API ut64 r_bin_get_baddr(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return binobj_get_baddr (o); } /* returns the load address of bin or UT64_MAX in case of errors */ R_API ut64 r_bin_get_laddr(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->loadaddr: UT64_MAX; } R_API void r_bin_set_baddr(RBin *bin, ut64 baddr) { RBinObject *o = r_bin_cur_object (bin); binobj_set_baddr (o, baddr); // XXX - update all the infos? } R_API ut64 r_bin_get_boffset(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->boffset: UT64_MAX; } R_API RBinAddr *r_bin_get_sym(RBin *bin, int sym) { RBinObject *o = r_bin_cur_object (bin); if (sym < 0 || sym >= R_BIN_SYM_LAST) { return NULL; } return o? o->binsym[sym]: NULL; } // XXX: those accessors are redundant R_API RList *r_bin_get_entries(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->entries: NULL; } R_API RList *r_bin_get_fields(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->fields: NULL; } R_API RList *r_bin_get_imports(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->imports: NULL; } R_API RBinInfo *r_bin_get_info(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->info: NULL; } R_API RList *r_bin_get_libs(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->libs: NULL; } R_API RList * r_bin_patch_relocs(RBin *bin) { static bool first = true; RBinObject *o = r_bin_cur_object (bin); if (!o) { return NULL; } // r_bin_object_set_items set o->relocs but there we don't have access // to io // so we need to be run from bin_relocs, free the previous reloc and get // the patched ones if (first && o->plugin && o->plugin->patch_relocs) { RList *tmp = o->plugin->patch_relocs (bin); first = false; if (!tmp) { return o->relocs; } r_list_free (o->relocs); o->relocs = tmp; REBASE_PADDR (o, o->relocs, RBinReloc); first = false; return o->relocs; } return o->relocs; } R_API RList *r_bin_get_relocs(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->relocs: NULL; } R_API RList *r_bin_get_sections(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->sections: NULL; } // TODO: Move into section.c and rename it to r_io_section_get_at () R_API RBinSection *r_bin_get_section_at(RBinObject *o, ut64 off, int va) { RBinSection *section; RListIter *iter; ut64 from, to; if (o) { // TODO: must be O(1) .. use sdb here r_list_foreach (o->sections, iter, section) { from = va? binobj_a2b (o, section->vaddr): section->paddr; to = va? (binobj_a2b (o, section->vaddr) + section->vsize) : (section->paddr + section->size); if (off >= from && off < to) { return section; } } } return NULL; } R_API RList *r_bin_reset_strings(RBin *bin) { RBinFile *a = r_bin_cur (bin); RBinObject *o = r_bin_cur_object (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (!a || !o) { return NULL; } if (o->strings) { r_list_free (o->strings); o->strings = NULL; } if (bin->minstrlen <= 0) { return NULL; } a->rawstr = bin->rawstr; if (plugin && plugin->strings) { o->strings = plugin->strings (a); } else { o->strings = get_strings (a, bin->minstrlen, 0); } if (bin->debase64) { filterStrings (bin, o->strings); } return o->strings; } R_API RList *r_bin_get_strings(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->strings: NULL; } R_API int r_bin_is_string(RBin *bin, ut64 va) { RBinString *string; RListIter *iter; RList *list; if (!(list = r_bin_get_strings (bin))) { return false; } r_list_foreach (list, iter, string) { if (string->vaddr == va) { return true; } if (string->vaddr > va) { return false; } } return false; } //callee must not free the symbol R_API RBinSymbol *r_bin_get_symbol_at_vaddr(RBin *bin, ut64 addr) { //use skiplist here RList *symbols = r_bin_get_symbols (bin); RListIter *iter; RBinSymbol *symbol; r_list_foreach (symbols, iter, symbol) { if (symbol->vaddr == addr) { return symbol; } } return NULL; } //callee must not free the symbol R_API RBinSymbol *r_bin_get_symbol_at_paddr(RBin *bin, ut64 addr) { //use skiplist here RList *symbols = r_bin_get_symbols (bin); RListIter *iter; RBinSymbol *symbol; r_list_foreach (symbols, iter, symbol) { if (symbol->paddr == addr) { return symbol; } } return NULL; } R_API RList *r_bin_get_symbols(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->symbols: NULL; } R_API RList *r_bin_get_mem(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->mem: NULL; } R_API int r_bin_is_big_endian(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return (o && o->info)? o->info->big_endian: -1; } R_API int r_bin_is_stripped(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_STRIPPED & o->info->dbg_info): 1; } R_API int r_bin_is_static(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); if (o && r_list_length (o->libs) > 0) return R_BIN_DBG_STATIC & o->info->dbg_info; return true; } // TODO: Integrate with r_bin_dbg */ R_API int r_bin_has_dbg_linenums(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_LINENUMS & o->info->dbg_info): false; } R_API int r_bin_has_dbg_syms(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_SYMS & o->info->dbg_info): false; } R_API int r_bin_has_dbg_relocs(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? (R_BIN_DBG_RELOCS & o->info->dbg_info): false; } R_API RBin *r_bin_new() { int i; RBinXtrPlugin *static_xtr_plugin; RBin *bin = R_NEW0 (RBin); if (!bin) { return NULL; } bin->force = NULL; bin->filter_rules = UT64_MAX; bin->sdb = sdb_new0 (); bin->cb_printf = (PrintfCallback)printf; bin->plugins = r_list_newf ((RListFree)plugin_free); bin->minstrlen = 0; bin->want_dbginfo = true; bin->cur = NULL; bin->io_owned = false; bin->binfiles = r_list_newf ((RListFree)r_bin_file_free); for (i = 0; bin_static_plugins[i]; i++) { r_bin_add (bin, bin_static_plugins[i]); } bin->binxtrs = r_list_new (); bin->binxtrs->free = free; for (i = 0; bin_xtr_static_plugins[i]; i++) { static_xtr_plugin = R_NEW0 (RBinXtrPlugin); if (!static_xtr_plugin) { free (bin); return NULL; } *static_xtr_plugin = *bin_xtr_static_plugins[i]; r_bin_xtr_add (bin, static_xtr_plugin); } bin->file_ids = r_id_pool_new (0, 0xffffffff); return bin; } R_API int r_bin_use_arch(RBin *bin, const char *arch, int bits, const char *name) { RBinFile *binfile = r_bin_file_find_by_arch_bits (bin, arch, bits, name); RBinObject *obj = NULL; if (binfile) { obj = r_bin_object_find_by_arch_bits (binfile, arch, bits, name); if (!obj) { if (binfile->xtr_data) { RBinXtrData *xtr_data = r_list_get_n (binfile->xtr_data, 0); if (!r_bin_file_object_new_from_xtr_data (bin, binfile, UT64_MAX, r_bin_get_laddr (bin), xtr_data)) { return false; } obj = r_list_get_n (binfile->objs, 0); } } } else { void *plugin = r_bin_get_binplugin_by_name (bin, name); if (plugin) { if (bin->cur) { bin->cur->curplugin = plugin; } binfile = r_bin_file_new (bin, "-", NULL, 0, 0, 0, 999, NULL, NULL, false); // create object and set arch/bits obj = r_bin_object_new (binfile, plugin, 0, 0, 0, 1024); binfile->o = obj; obj->info = R_NEW0 (RBinInfo); obj->info->arch = strdup (arch); obj->info->bits = bits; } } return (binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj)); } R_API RBinObject *r_bin_object_find_by_arch_bits(RBinFile *binfile, const char *arch, int bits, const char *name) { RBinObject *obj = NULL; RListIter *iter = NULL; RBinInfo *info = NULL; r_list_foreach (binfile->objs, iter, obj) { info = obj->info; if (info && info->arch && info->file && (bits == info->bits) && !strcmp (info->arch, arch) && !strcmp (info->file, name)) { break; } obj = NULL; } return obj; } R_API RBinFile *r_bin_file_find_by_arch_bits(RBin *bin, const char *arch, int bits, const char *name) { RListIter *iter; RBinFile *binfile = NULL; RBinXtrData *xtr_data; if (!name || !arch) { return NULL; } r_list_foreach (bin->binfiles, iter, binfile) { RListIter *iter_xtr; if (!binfile->xtr_data) { continue; } // look for sub-bins in Xtr Data and Load if we need to r_list_foreach (binfile->xtr_data, iter_xtr, xtr_data) { if (xtr_data->metadata && xtr_data->metadata->arch) { char *iter_arch = xtr_data->metadata->arch; int iter_bits = xtr_data->metadata->bits; if (bits == iter_bits && !strcmp (iter_arch, arch)) { if (!xtr_data->loaded) { if (!r_bin_file_object_new_from_xtr_data ( bin, binfile, xtr_data->baddr, xtr_data->laddr, xtr_data)) { return NULL; } return binfile; } } } } } return binfile; } R_API int r_bin_select(RBin *bin, const char *arch, int bits, const char *name) { RBinFile *cur = r_bin_cur (bin), *binfile = NULL; RBinObject *obj = NULL; name = !name && cur? cur->file: name; binfile = r_bin_file_find_by_arch_bits (bin, arch, bits, name); if (binfile && name) { obj = r_bin_object_find_by_arch_bits (binfile, arch, bits, name); } return binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj); } R_API int r_bin_select_object(RBinFile *binfile, const char *arch, int bits, const char *name) { RBinObject *obj = binfile ? r_bin_object_find_by_arch_bits ( binfile, arch, bits, name) : NULL; return obj && r_bin_file_set_cur_binfile_obj (binfile->rbin, binfile, obj); } static RBinObject *r_bin_file_object_find_by_id(RBinFile *binfile, ut32 binobj_id) { RBinObject *obj; RListIter *iter; if (binfile) { r_list_foreach (binfile->objs, iter, obj) { if (obj->id == binobj_id) { return obj; } } } return NULL; } static RBinFile *r_bin_file_find_by_object_id(RBin *bin, ut32 binobj_id) { RListIter *iter; RBinFile *binfile; r_list_foreach (bin->binfiles, iter, binfile) { if (r_bin_file_object_find_by_id (binfile, binobj_id)) { return binfile; } } return NULL; } static RBinFile *r_bin_file_find_by_id(RBin *bin, ut32 binfile_id) { RBinFile *binfile = NULL; RListIter *iter = NULL; r_list_foreach (bin->binfiles, iter, binfile) { if (binfile->id == binfile_id) { break; } binfile = NULL; } return binfile; } R_API int r_bin_object_delete(RBin *bin, ut32 binfile_id, ut32 binobj_id) { RBinFile *binfile = NULL; //, *cbinfile = r_bin_cur (bin); RBinObject *obj = NULL; int res = false; #if 0 if (binfile_id == UT32_MAX && binobj_id == UT32_MAX) { return false; } #endif if (binfile_id == -1) { binfile = r_bin_file_find_by_object_id (bin, binobj_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } else if (binobj_id == -1) { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? binfile->o: NULL; } else { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } // lazy way out, always leaving at least 1 bin object loaded if (binfile && (r_list_length (binfile->objs) > 1)) { binfile->o = NULL; r_list_delete_data (binfile->objs, obj); obj = (RBinObject *)r_list_get_n (binfile->objs, 0); res = obj && binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj); } return res; } R_API int r_bin_select_by_ids(RBin *bin, ut32 binfile_id, ut32 binobj_id) { RBinFile *binfile = NULL; RBinObject *obj = NULL; if (binfile_id == UT32_MAX && binobj_id == UT32_MAX) { return false; } if (binfile_id == -1) { binfile = r_bin_file_find_by_object_id (bin, binobj_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } else if (binobj_id == -1) { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? binfile->o: NULL; } else { binfile = r_bin_file_find_by_id (bin, binfile_id); obj = binfile? r_bin_file_object_find_by_id (binfile, binobj_id): NULL; } if (!binfile || !obj) { return false; } return obj && binfile && r_bin_file_set_cur_binfile_obj (bin, binfile, obj); } R_API int r_bin_select_idx(RBin *bin, const char *name, int idx) { RBinFile *nbinfile = NULL, *binfile = r_bin_cur (bin); RBinObject *obj = NULL; const char *tname = !name && binfile? binfile->file: name; int res = false; if (!tname || !bin) { return res; } nbinfile = r_bin_file_find_by_name_n (bin, tname, idx); obj = nbinfile? r_list_get_n (nbinfile->objs, idx): NULL; return obj && nbinfile && r_bin_file_set_cur_binfile_obj (bin, nbinfile, obj); } static void list_xtr_archs(RBin *bin, int mode) { RBinFile *binfile = r_bin_cur (bin); if (binfile->xtr_data) { RListIter *iter_xtr; RBinXtrData *xtr_data; int bits, i = 0; char *arch, *machine; r_list_foreach (binfile->xtr_data, iter_xtr, xtr_data) { if (!xtr_data || !xtr_data->metadata || !xtr_data->metadata->arch) { continue; } arch = xtr_data->metadata->arch; machine = xtr_data->metadata->machine; bits = xtr_data->metadata->bits; switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ( "%s{\"arch\":\"%s\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":\"%" PFMT64d ",\"machine\":\"%s\"}", i++ ? "," : "", arch, bits, xtr_data->offset, xtr_data->size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %" PFMT64d " %s_%i %s\n", i++, xtr_data->offset, xtr_data->size, arch, bits, machine); break; } } } } R_API void r_bin_list_archs(RBin *bin, int mode) { RListIter *iter; int i = 0; char unk[128]; char archline[128]; RBinFile *binfile = r_bin_cur (bin); RBinObject *obj = NULL; const char *name = binfile? binfile->file: NULL; int narch = binfile? binfile->narch: 0; //are we with xtr format? if (binfile && binfile->curxtr) { list_xtr_archs (bin, mode); return; } Sdb *binfile_sdb = binfile? binfile->sdb: NULL; if (!binfile_sdb) { eprintf ("Cannot find SDB!\n"); return; } else if (!binfile) { eprintf ("Binary format not currently loaded!\n"); return; } sdb_unset (binfile_sdb, ARCHS_KEY, 0); if (mode == 'j') { bin->cb_printf ("\"bins\":["); } RBinFile *nbinfile = r_bin_file_find_by_name_n (bin, name, i); if (!nbinfile) { return; } i = -1; r_list_foreach (nbinfile->objs, iter, obj) { RBinInfo *info = obj->info; char bits = info? info->bits: 0; ut64 boffset = obj->boffset; ut32 obj_size = obj->obj_size; const char *arch = info? info->arch: NULL; const char *machine = info? info->machine: "unknown_machine"; i++; if (!arch) { snprintf (unk, sizeof (unk), "unk_%d", i); arch = unk; } if (info && narch > 1) { switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ("%s{\"arch\":\"%s\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":%d," "\"machine\":\"%s\"}", i? ",": "", arch, bits, boffset, obj_size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %d %s_%i %s\n", i, boffset, obj_size, arch, bits, machine); } snprintf (archline, sizeof (archline) - 1, "0x%08" PFMT64x ":%d:%s:%d:%s", boffset, obj_size, arch, bits, machine); /// xxx machine not exported? //sdb_array_push (binfile_sdb, ARCHS_KEY, archline, 0); } else { if (info) { switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ("%s{\"arch\":\"%s\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":%d," "\"machine\":\"%s\"}", i? ",": "", arch, bits, boffset, obj_size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %d %s_%d\n", i, boffset, obj_size, arch, bits); } snprintf (archline, sizeof (archline), "0x%08" PFMT64x ":%d:%s:%d", boffset, obj_size, arch, bits); } else if (nbinfile && mode) { switch (mode) { case 'q': bin->cb_printf ("%s\n", arch); break; case 'j': bin->cb_printf ("%s{\"arch\":\"unk_%d\",\"bits\":%d," "\"offset\":%" PFMT64d ",\"size\":%d," "\"machine\":\"%s\"}", i? ",": "", i, bits, boffset, obj_size, machine); break; default: bin->cb_printf ("%03i 0x%08" PFMT64x " %d unk_0\n", i, boffset, obj_size); } snprintf (archline, sizeof (archline), "0x%08" PFMT64x ":%d:%s:%d", boffset, obj_size, "unk", 0); } else { eprintf ("Error: Invalid RBinFile.\n"); } //sdb_array_push (binfile_sdb, ARCHS_KEY, archline, 0); } } if (mode == 'j') { bin->cb_printf ("]"); } } R_API void r_bin_set_user_ptr(RBin *bin, void *user) { bin->user = user; } static RBinSection* _get_vsection_at(RBin *bin, ut64 vaddr) { RBinObject *cur = r_bin_object_get_cur (bin); return r_bin_get_section_at (cur, vaddr, true); } R_API void r_bin_bind(RBin *bin, RBinBind *b) { if (b) { b->bin = bin; b->get_offset = getoffset; b->get_name = getname; b->get_sections = r_bin_get_sections; b->get_vsect_at = _get_vsection_at; } } R_API RBuffer *r_bin_create(RBin *bin, const ut8 *code, int codelen, const ut8 *data, int datalen) { RBinFile *a = r_bin_cur (bin); RBinPlugin *plugin = r_bin_file_cur_plugin (a); if (codelen < 0) { codelen = 0; } if (datalen < 0) { datalen = 0; } if (plugin && plugin->create) { return plugin->create (bin, code, codelen, data, datalen); } return NULL; } R_API RBuffer *r_bin_package(RBin *bin, const char *type, const char *file, RList *files) { if (!strcmp (type, "zip")) { #if 0 int zep = 0; struct zip * z = zip_open (file, 8 | 1, &zep); if (z) { RListIter *iter; const char *f; eprintf ("zip file created\n"); r_list_foreach (files, iter, f) { struct zip_source *zs = NULL; zs = zip_source_file (z, f, 0, 1024); if (zs) { eprintf ("ADD %s\n", f); zip_add (z, f, zs); zip_source_free (zs); } else { eprintf ("Cannot find file %s\n", f); } eprintf ("zS %p\n", zs); } zip_close (z); } else { eprintf ("Cannot create zip file\n"); } #endif } else if (!strcmp (type, "fat")) { const char *f; RListIter *iter; ut32 num; ut8 *num8 = (ut8*)&num; RBuffer *buf = r_buf_new_file (file, true); r_buf_write_at (buf, 0, (const ut8*)"\xca\xfe\xba\xbe", 4); int count = r_list_length (files); num = r_read_be32 (&count); ut64 from = 0x1000; r_buf_write_at (buf, 4, num8, 4); int off = 12; int item = 0; r_list_foreach (files, iter, f) { int f_len = 0; ut8 *f_buf = (ut8 *)r_file_slurp (f, &f_len); if (f_buf && f_len >= 0) { eprintf ("ADD %s %d\n", f, f_len); } else { eprintf ("Cannot open %s\n", f); free (f_buf); continue; } item++; /* CPU */ num8[0] = f_buf[7]; num8[1] = f_buf[6]; num8[2] = f_buf[5]; num8[3] = f_buf[4]; r_buf_write_at (buf, off - 4, num8, 4); /* SUBTYPE */ num8[0] = f_buf[11]; num8[1] = f_buf[10]; num8[2] = f_buf[9]; num8[3] = f_buf[8]; r_buf_write_at (buf, off, num8, 4); ut32 from32 = from; /* FROM */ num = r_read_be32 (&from32); r_buf_write_at (buf, off + 4, num8, 4); r_buf_write_at (buf, from, f_buf, f_len); /* SIZE */ num = r_read_be32 (&f_len); r_buf_write_at (buf, off + 8, num8, 4); off += 20; from += f_len + (f_len % 0x1000); free (f_buf); } r_buf_free (buf); return NULL; } else { eprintf ("Usage: rabin2 -X [fat|zip] [filename] [files ...]\n"); } return NULL; } R_API RBinObject *r_bin_get_object(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); if (o) { o->referenced++; } return o; } R_API RList * /*<RBinClass>*/ r_bin_get_classes(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o? o->classes: NULL; } R_API void r_bin_class_free(RBinClass *c) { free (c->name); free (c->super); r_list_free (c->methods); r_list_free (c->fields); free (c); } R_API RBinClass *r_bin_class_new(RBinFile *binfile, const char *name, const char *super, int view) { RBinObject *o = binfile? binfile->o: NULL; RList *list = NULL; RBinClass *c; if (!o) { return NULL; } list = o->classes; if (!name) { return NULL; } c = r_bin_class_get (binfile, name); if (c) { if (super) { free (c->super); c->super = strdup (super); } return c; } c = R_NEW0 (RBinClass); if (!c) { return NULL; } c->name = strdup (name); c->super = super? strdup (super): NULL; c->index = r_list_length (list); c->methods = r_list_new (); c->fields = r_list_new (); c->visibility = view; if (!list) { list = o->classes = r_list_new (); } r_list_append (list, c); return c; } R_API RBinClass *r_bin_class_get(RBinFile *binfile, const char *name) { if (!binfile || !binfile->o || !name) { return NULL; } RBinClass *c; RListIter *iter; RList *list = binfile->o->classes; r_list_foreach (list, iter, c) { if (!strcmp (c->name, name)) { return c; } } return NULL; } R_API RBinSymbol *r_bin_class_add_method(RBinFile *binfile, const char *classname, const char *name, int nargs) { RBinClass *c = r_bin_class_get (binfile, classname); if (!c) { c = r_bin_class_new (binfile, classname, NULL, 0); if (!c) { eprintf ("Cannot allocate class %s\n", classname); return NULL; } } RBinSymbol *m; RListIter *iter; r_list_foreach (c->methods, iter, m) { if (!strcmp (m->name, name)) { return NULL; } } RBinSymbol *sym = R_NEW0 (RBinSymbol); if (!sym) { return NULL; } sym->name = strdup (name); r_list_append (c->methods, sym); return sym; } R_API void r_bin_class_add_field(RBinFile *binfile, const char *classname, const char *name) { //TODO: add_field into class //eprintf ("TODO add field: %s \n", name); } /* returns vaddr, rebased with the baseaddr of binfile, if va is enabled for * bin, paddr otherwise */ R_API ut64 r_binfile_get_vaddr(RBinFile *binfile, ut64 paddr, ut64 vaddr) { int use_va = 0; if (binfile && binfile->o && binfile->o->info) { use_va = binfile->o->info->has_va; } return use_va? binobj_a2b (binfile->o, vaddr): paddr; } /* returns vaddr, rebased with the baseaddr of bin, if va is enabled for bin, * paddr otherwise */ R_API ut64 r_bin_get_vaddr(RBin *bin, ut64 paddr, ut64 vaddr) { if (!bin || !bin->cur) { return UT64_MAX; } if (paddr == UT64_MAX) { return UT64_MAX; } /* hack to realign thumb symbols */ if (bin->cur->o && bin->cur->o->info && bin->cur->o->info->arch) { if (bin->cur->o->info->bits == 16) { RBinSection *s = r_bin_get_section_at (bin->cur->o, paddr, false); // autodetect thumb if (s && s->srwx & 1 && strstr (s->name, "text")) { if (!strcmp (bin->cur->o->info->arch, "arm") && (vaddr & 1)) { vaddr = (vaddr >> 1) << 1; } } } } return r_binfile_get_vaddr (bin->cur, paddr, vaddr); } R_API ut64 r_bin_a2b(RBin *bin, ut64 addr) { RBinObject *o = r_bin_cur_object (bin); return o? o->baddr_shift + addr: addr; } R_API ut64 r_bin_get_size(RBin *bin) { RBinObject *o = r_bin_cur_object (bin); return o ? o->size : 0; } R_API int r_bin_file_delete_all(RBin *bin) { int counter = 0; if (bin) { counter = r_list_length (bin->binfiles); r_list_purge (bin->binfiles); bin->cur = NULL; } return counter; } R_API int r_bin_file_delete(RBin *bin, ut32 bin_fd) { RListIter *iter; RBinFile *bf; RBinFile *cur = r_bin_cur (bin); if (bin && cur) { r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->fd == bin_fd) { if (cur->fd == bin_fd) { //avoiding UaF due to dead reference bin->cur = NULL; } r_list_delete (bin->binfiles, iter); return 1; } } } return 0; } R_API RBinFile *r_bin_file_find_by_fd(RBin *bin, ut32 bin_fd) { RListIter *iter; RBinFile *bf; if (bin) { r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->fd == bin_fd) { return bf; } } } return NULL; } R_API RBinFile *r_bin_file_find_by_name(RBin *bin, const char *name) { RListIter *iter; RBinFile *bf = NULL; if (!bin || !name) { return NULL; } r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->file && !strcmp (bf->file, name)) { break; } bf = NULL; } return bf; } R_API RBinFile *r_bin_file_find_by_name_n(RBin *bin, const char *name, int idx) { RListIter *iter; RBinFile *bf = NULL; int i = 0; if (!bin) { return bf; } r_list_foreach (bin->binfiles, iter, bf) { if (bf && bf->file && !strcmp (bf->file, name)) { if (i == idx) { break; } i++; } bf = NULL; } return bf; } R_API int r_bin_file_set_cur_by_fd(RBin *bin, ut32 bin_fd) { RBinFile *bf = r_bin_file_find_by_fd (bin, bin_fd); return r_bin_file_set_cur_binfile (bin, bf); } R_API int r_bin_file_set_cur_binfile_obj(RBin *bin, RBinFile *bf, RBinObject *obj) { RBinPlugin *plugin = NULL; if (!bin || !bf || !obj) { return false; } bin->file = bf->file; bin->cur = bf; bin->narch = bf->narch; bf->o = obj; plugin = r_bin_file_cur_plugin (bf); if (bin->minstrlen < 1) { bin->minstrlen = plugin? plugin->minstrlen: bin->minstrlen; } return true; } R_API int r_bin_file_set_cur_binfile(RBin *bin, RBinFile *bf) { RBinObject *obj = bf? bf->o: NULL; return obj? r_bin_file_set_cur_binfile_obj (bin, bf, obj): false; } R_API int r_bin_file_set_cur_by_name(RBin *bin, const char *name) { RBinFile *bf = r_bin_file_find_by_name (bin, name); return r_bin_file_set_cur_binfile (bin, bf); } R_API RBinFile *r_bin_cur(RBin *bin) { return bin? bin->cur: NULL; } R_API RBinObject *r_bin_cur_object(RBin *bin) { RBinFile *binfile = r_bin_cur (bin); return binfile? binfile->o: NULL; } R_API void r_bin_force_plugin(RBin *bin, const char *name) { free (bin->force); bin->force = (name && *name)? strdup (name): NULL; } R_API int r_bin_read_at(RBin *bin, ut64 addr, ut8 *buf, int size) { RIOBind *iob; if (!bin || !(iob = &(bin->iob))) { return false; } return iob->read_at (iob->io, addr, buf, size); } R_API int r_bin_write_at(RBin *bin, ut64 addr, const ut8 *buf, int size) { RIOBind *iob; if (!bin || !(iob = &(bin->iob))) { return false; } return iob->write_at (iob->io, addr, buf, size); } R_API const char *r_bin_entry_type_string(int etype) { switch (etype) { case R_BIN_ENTRY_TYPE_PROGRAM: return "program"; case R_BIN_ENTRY_TYPE_MAIN: return "main"; case R_BIN_ENTRY_TYPE_INIT: return "init"; case R_BIN_ENTRY_TYPE_FINI: return "fini"; case R_BIN_ENTRY_TYPE_TLS: return "tls"; } return NULL; } R_API void r_bin_load_filter(RBin *bin, ut64 rules) { bin->filter_rules = rules; } /* RBinField */ R_API RBinField *r_bin_field_new(ut64 paddr, ut64 vaddr, int size, const char *name, const char *comment, const char *format) { RBinField *ptr; if (!(ptr = R_NEW0 (RBinField))) { return NULL; } ptr->name = strdup (name); ptr->comment = (comment && *comment)? strdup (comment): NULL; ptr->format = (format && *format)? strdup (format): NULL; ptr->paddr = paddr; ptr->size = size; // ptr->visibility = ??? ptr->vaddr = vaddr; return ptr; } // use void* to honor the RListFree signature R_API void r_bin_field_free(void *_field) { RBinField *field = (RBinField*) _field; free (field->name); free (field->comment); free (field->format); free (field); } R_API const char *r_bin_get_meth_flag_string(ut64 flag, bool compact) { switch (flag) { case R_BIN_METH_CLASS: return compact ? "c" : "class"; case R_BIN_METH_STATIC: return compact ? "s" : "static"; case R_BIN_METH_PUBLIC: return compact ? "p" : "public"; case R_BIN_METH_PRIVATE: return compact ? "P" : "private"; case R_BIN_METH_PROTECTED: return compact ? "r" : "protected"; case R_BIN_METH_INTERNAL: return compact ? "i" : "internal"; case R_BIN_METH_OPEN: return compact ? "o" : "open"; case R_BIN_METH_FILEPRIVATE: return compact ? "e" : "fileprivate"; case R_BIN_METH_FINAL: return compact ? "f" : "final"; case R_BIN_METH_VIRTUAL: return compact ? "v" : "virtual"; case R_BIN_METH_CONST: return compact ? "k" : "const"; case R_BIN_METH_MUTATING: return compact ? "m" : "mutating"; case R_BIN_METH_ABSTRACT: return compact ? "a" : "abstract"; case R_BIN_METH_SYNCHRONIZED: return compact ? "y" : "synchronized"; case R_BIN_METH_NATIVE: return compact ? "n" : "native"; case R_BIN_METH_BRIDGE: return compact ? "b" : "bridge"; case R_BIN_METH_VARARGS: return compact ? "g" : "varargs"; case R_BIN_METH_SYNTHETIC: return compact ? "h" : "synthetic"; case R_BIN_METH_STRICT: return compact ? "t" : "strict"; case R_BIN_METH_MIRANDA: return compact ? "A" : "miranda"; case R_BIN_METH_CONSTRUCTOR: return compact ? "C" : "constructor"; case R_BIN_METH_DECLARED_SYNCHRONIZED: return compact ? "Y" : "declared_synchronized"; default: return NULL; } }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2900_0
crossvul-cpp_data_bad_5316_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP DDDD BBBB % % P P D D B B % % PPPP D D BBBB % % P D D B B % % P DDDD BBBB % % % % % % Read/Write Palm Database ImageViewer Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % 20071202 TS * rewrote RLE decoder - old version could cause buffer overflows % * failure of RLE decoding now thows error RLEDecoderError % * fixed bug in RLE decoding - now all rows are decoded, not just % the first one % * fixed bug in reader - record offsets now handled correctly % * fixed bug in reader - only bits 0..2 indicate compression type % * in writer: now using image color count instead of depth */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colormap-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* Typedef declarations. */ typedef struct _PDBInfo { char name[32]; short int attributes, version; size_t create_time, modify_time, archive_time, modify_number, application_info, sort_info; char type[4], /* database type identifier "vIMG" */ id[4]; /* database creator identifier "View" */ size_t seed, next_record; short int number_records; } PDBInfo; typedef struct _PDBImage { char name[32], version; size_t reserved_1, note; short int x_last, y_last; size_t reserved_2; short int width, height; unsigned char type; unsigned short x_anchor, y_anchor; } PDBImage; /* Forward declarations. */ static MagickBooleanType WritePDBImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded % pixel packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image,unsigned char *pixels, % const size_t length) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o pixels: The address of a byte (8 bits) array of pixel data created by % the decoding process. % % o length: Number of bytes to read into buffer 'pixels'. % */ static MagickBooleanType DecodeImage(Image *image, unsigned char *pixels, const size_t length) { #define RLE_MODE_NONE -1 #define RLE_MODE_COPY 0 #define RLE_MODE_RUN 1 int data = 0, count = 0; unsigned char *p; int mode = RLE_MODE_NONE; for (p = pixels; p < pixels + length; p++) { if (0 == count) { data = ReadBlobByte( image ); if (-1 == data) return MagickFalse; if (data > 128) { mode = RLE_MODE_RUN; count = data - 128 + 1; data = ReadBlobByte( image ); if (-1 == data) return MagickFalse; } else { mode = RLE_MODE_COPY; count = data + 1; } } if (RLE_MODE_COPY == mode) { data = ReadBlobByte( image ); if (-1 == data) return MagickFalse; } *p = (unsigned char)data; --count; } return MagickTrue; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P D B % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPDB() returns MagickTrue if the image format type, identified by the % magick string, is PDB. % % The format of the ReadPDBImage method is: % % MagickBooleanType IsPDB(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPDB(const unsigned char *magick,const size_t length) { if (length < 68) return(MagickFalse); if (memcmp(magick+60,"vIMGView",8) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPDBImage() reads an Pilot image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPDBImage method is: % % Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception) { unsigned char attributes, tag[3]; Image *image; IndexPacket index; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register unsigned char *p; size_t bits_per_pixel, num_pad_bytes, one, packets; ssize_t count, img_offset, comment_offset = 0, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PDB image file. */ count=ReadBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); if (count != sizeof(pdb_info.name)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pdb_info.attributes=(short) ReadBlobMSBShort(image); pdb_info.version=(short) ReadBlobMSBShort(image); pdb_info.create_time=ReadBlobMSBLong(image); pdb_info.modify_time=ReadBlobMSBLong(image); pdb_info.archive_time=ReadBlobMSBLong(image); pdb_info.modify_number=ReadBlobMSBLong(image); pdb_info.application_info=ReadBlobMSBLong(image); pdb_info.sort_info=ReadBlobMSBLong(image); (void) ReadBlob(image,4,(unsigned char *) pdb_info.type); (void) ReadBlob(image,4,(unsigned char *) pdb_info.id); pdb_info.seed=ReadBlobMSBLong(image); pdb_info.next_record=ReadBlobMSBLong(image); pdb_info.number_records=(short) ReadBlobMSBShort(image); if ((memcmp(pdb_info.type,"vIMG",4) != 0) || (memcmp(pdb_info.id,"View",4) != 0)) if (pdb_info.next_record != 0) ThrowReaderException(CoderError,"MultipleRecordListNotSupported"); /* Read record header. */ img_offset=(ssize_t) ((int) ReadBlobMSBLong(image)); attributes=(unsigned char) ((int) ReadBlobByte(image)); (void) attributes; count=ReadBlob(image,3,(unsigned char *) tag); if (count != 3 || memcmp(tag,"\x6f\x80\x00",3) != 0) ThrowReaderException(CorruptImageError,"CorruptImage"); if (pdb_info.number_records > 1) { comment_offset=(ssize_t) ((int) ReadBlobMSBLong(image)); attributes=(unsigned char) ((int) ReadBlobByte(image)); count=ReadBlob(image,3,(unsigned char *) tag); if (count != 3 || memcmp(tag,"\x6f\x80\x01",3) != 0) ThrowReaderException(CorruptImageError,"CorruptImage"); } num_pad_bytes = (size_t) (img_offset - TellBlob( image )); while (num_pad_bytes-- != 0) { int c; c=ReadBlobByte(image); if (c == EOF) break; } /* Read image header. */ count=ReadBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); if (count != sizeof(pdb_image.name)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); pdb_image.version=ReadBlobByte(image); pdb_image.type=(unsigned char) ReadBlobByte(image); pdb_image.reserved_1=ReadBlobMSBLong(image); pdb_image.note=ReadBlobMSBLong(image); pdb_image.x_last=(short) ReadBlobMSBShort(image); pdb_image.y_last=(short) ReadBlobMSBShort(image); pdb_image.reserved_2=ReadBlobMSBLong(image); pdb_image.x_anchor=ReadBlobMSBShort(image); pdb_image.y_anchor=ReadBlobMSBShort(image); pdb_image.width=(short) ReadBlobMSBShort(image); pdb_image.height=(short) ReadBlobMSBShort(image); /* Initialize image structure. */ image->columns=(size_t) pdb_image.width; image->rows=(size_t) pdb_image.height; image->depth=8; image->storage_class=PseudoClass; bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL; one=1; if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } packets=(bits_per_pixel*image->columns+7)/8; pixels=(unsigned char *) AcquireQuantumMemory(packets+256UL,image->rows* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); switch (pdb_image.version & 0x07) { case 0: { image->compression=NoCompression; count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels); break; } case 1: { image->compression=RLECompression; if (!DecodeImage(image, pixels, packets * image -> rows)) ThrowReaderException( CorruptImageError, "RLEDecoderError" ); break; } default: ThrowReaderException(CorruptImageError, "UnrecognizedImageCompressionType" ); } p=pixels; switch (bits_per_pixel) { case 1: { int bit; /* Read 1-bit PDB image. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); break; } case 2: { /* Read 2-bit PDB image. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns-3; x+=4) { index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03)); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03)); SetPixelIndex(indexes+x+1,index); index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03)); SetPixelIndex(indexes+x+2,index); index=ConstrainColormapIndex(image,3UL-((*p) & 0x03)); SetPixelIndex(indexes+x+3,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); break; } case 4: { /* Read 4-bit PDB image. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns-1; x+=2) { index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f)); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f)); SetPixelIndex(indexes+x+1,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); if (pdb_info.number_records > 1) { char *comment; int c; register char *p; size_t length; num_pad_bytes = (size_t) (comment_offset - TellBlob( image )); while (num_pad_bytes--) ReadBlobByte( image ); /* Read comment. */ c=ReadBlobByte(image); length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; c != EOF; p++) { if ((size_t) (p-comment+MaxTextExtent) >= length) { *p='\0'; length<<=1; length+=MaxTextExtent; comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent, sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=c; c=ReadBlobByte(image); } *p='\0'; if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPDBImage() adds properties for the PDB image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPDBImage method is: % % size_t RegisterPDBImage(void) % */ ModuleExport size_t RegisterPDBImage(void) { MagickInfo *entry; entry=SetMagickInfo("PDB"); entry->decoder=(DecodeImageHandler *) ReadPDBImage; entry->encoder=(EncodeImageHandler *) WritePDBImage; entry->magick=(IsImageFormatHandler *) IsPDB; entry->description=ConstantString("Palm Database ImageViewer Format"); entry->module=ConstantString("PDB"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPDBImage() removes format registrations made by the % PDB module from the list of supported formats. % % The format of the UnregisterPDBImage method is: % % UnregisterPDBImage(void) % */ ModuleExport void UnregisterPDBImage(void) { (void) UnregisterMagickInfo("PDB"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P D B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePDBImage() writes an image % % The format of the WritePDBImage method is: % % MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % */ static unsigned char *EncodeRLE(unsigned char *destination, unsigned char *source,size_t literal,size_t repeat) { if (literal > 0) *destination++=(unsigned char) (literal-1); (void) CopyMagickMemory(destination,source,literal); destination+=literal; if (repeat > 0) { *destination++=(unsigned char) (0x80 | (repeat-1)); *destination++=source[literal]; } return(destination); } static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image) { const char *comment; int bits; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, literal, packets, packet_size, repeat; ssize_t y; unsigned char *buffer, *runlength, *scanline; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); if ((image -> colors <= 2 ) || (GetImageType(image,&image->exception ) == BilevelType)) { bits_per_pixel=1; } else if (image->colors <= 4) { bits_per_pixel=2; } else if (image->colors <= 8) { bits_per_pixel=3; } else { bits_per_pixel=4; } (void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info)); (void) CopyMagickString(pdb_info.name,image_info->filename, sizeof(pdb_info.name)); pdb_info.attributes=0; pdb_info.version=0; pdb_info.create_time=time(NULL); pdb_info.modify_time=pdb_info.create_time; pdb_info.archive_time=0; pdb_info.modify_number=0; pdb_info.application_info=0; pdb_info.sort_info=0; (void) CopyMagickMemory(pdb_info.type,"vIMG",4); (void) CopyMagickMemory(pdb_info.id,"View",4); pdb_info.seed=0; pdb_info.next_record=0; comment=GetImageProperty(image,"comment"); pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2); (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info); (void) WriteBlob(image,4,(unsigned char *) pdb_info.type); (void) WriteBlob(image,4,(unsigned char *) pdb_info.id); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records); (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name)); pdb_image.version=1; /* RLE Compressed */ switch (bits_per_pixel) { case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */ case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */ default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */ } pdb_image.reserved_1=0; pdb_image.note=0; pdb_image.x_last=0; pdb_image.y_last=0; pdb_image.reserved_2=0; pdb_image.x_anchor=(unsigned short) 0xffff; pdb_image.y_anchor=(unsigned short) 0xffff; pdb_image.width=(short) image->columns; if (image->columns % 16) pdb_image.width=(short) (16*(image->columns/16+1)); pdb_image.height=(short) image->rows; packets=((bits_per_pixel*image->columns+7)/8); runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets, image->rows*sizeof(*runlength)); if (runlength == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); buffer=(unsigned char *) AcquireQuantumMemory(256,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=(size_t) (image->depth > 8 ? 2: 1); scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Convert to GRAY raster scanline. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); bits=8/(int) bits_per_pixel-1; /* start at most significant bits */ literal=0; repeat=0; q=runlength; buffer[0]=0x00; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,scanline,&image->exception); for (x=0; x < (ssize_t) pdb_image.width; x++) { if (x < (ssize_t) image->columns) buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >> (8-bits_per_pixel) << bits*bits_per_pixel; bits--; if (bits < 0) { if (((literal+repeat) > 0) && (buffer[literal+repeat] == buffer[literal+repeat-1])) { if (repeat == 0) { literal--; repeat++; } repeat++; if (0x7f < repeat) { q=EncodeRLE(q,buffer,literal,repeat); literal=0; repeat=0; } } else { if (repeat >= 2) literal+=repeat; else { q=EncodeRLE(q,buffer,literal,repeat); buffer[0]=buffer[literal+repeat]; literal=0; } literal++; repeat=0; if (0x7f < literal) { q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0); (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80); literal-=0x80; } } bits=8/(int) bits_per_pixel-1; buffer[literal+repeat]=0x00; } } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } q=EncodeRLE(q,buffer,literal,repeat); scanline=(unsigned char *) RelinquishMagickMemory(scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); quantum_info=DestroyQuantumInfo(quantum_info); /* Write the Image record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8* pdb_info.number_records)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,0); if (pdb_info.number_records > 1) { /* Write the comment record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q- runlength)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,1); } /* Write the Image data. */ (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); (void) WriteBlobByte(image,(unsigned char) pdb_image.version); (void) WriteBlobByte(image,pdb_image.type); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2); (void) WriteBlobMSBShort(image,pdb_image.x_anchor); (void) WriteBlobMSBShort(image,pdb_image.y_anchor); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height); (void) WriteBlob(image,(size_t) (q-runlength),runlength); runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (pdb_info.number_records > 1) (void) WriteBlobString(image,comment); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5316_0
crossvul-cpp_data_good_458_0
/* Copyright (C) 2008-2018 - pancake, unlogic, emvivre */ #include <r_flag.h> #include <r_core.h> #include <r_asm.h> #include <r_lib.h> #include <r_types.h> #include <stdio.h> #include <string.h> static ut64 getnum(RAsm *a, const char *s); #define ENCODING_SHIFT 0 #define OPTYPE_SHIFT 6 #define REGMASK_SHIFT 16 #define OPSIZE_SHIFT 24 // How to encode the operand? #define OT_REGMEM (1 << (ENCODING_SHIFT + 0)) #define OT_SPECIAL (1 << (ENCODING_SHIFT + 1)) #define OT_IMMEDIATE (1 << (ENCODING_SHIFT + 2)) #define OT_JMPADDRESS (1 << (ENCODING_SHIFT + 3)) // Register indices - by default, we allow all registers #define OT_REGALL (0xff << REGMASK_SHIFT) // Memory or register operands: how is the operand written in assembly code? #define OT_MEMORY (1 << (OPTYPE_SHIFT + 0)) #define OT_CONSTANT (1 << (OPTYPE_SHIFT + 1)) #define OT_GPREG ((1 << (OPTYPE_SHIFT + 2)) | OT_REGALL) #define OT_SEGMENTREG ((1 << (OPTYPE_SHIFT + 3)) | OT_REGALL) #define OT_FPUREG ((1 << (OPTYPE_SHIFT + 4)) | OT_REGALL) #define OT_MMXREG ((1 << (OPTYPE_SHIFT + 5)) | OT_REGALL) #define OT_XMMREG ((1 << (OPTYPE_SHIFT + 6)) | OT_REGALL) #define OT_CONTROLREG ((1 << (OPTYPE_SHIFT + 7)) | OT_REGALL) #define OT_DEBUGREG ((1 << (OPTYPE_SHIFT + 8)) | OT_REGALL) #define OT_SREG ((1 << (OPTYPE_SHIFT + 9)) | OT_REGALL) // more? #define OT_REGTYPE ((OT_GPREG | OT_SEGMENTREG | OT_FPUREG | OT_MMXREG | OT_XMMREG | OT_CONTROLREG | OT_DEBUGREG) & ~OT_REGALL) // Register mask #define OT_REG(num) ((1 << (REGMASK_SHIFT + (num))) | OT_REGTYPE) #define OT_UNKNOWN (0 << OPSIZE_SHIFT) #define OT_BYTE (1 << OPSIZE_SHIFT) #define OT_WORD (2 << OPSIZE_SHIFT) #define OT_DWORD (4 << OPSIZE_SHIFT) #define OT_QWORD (8 << OPSIZE_SHIFT) #define OT_OWORD (16 << OPSIZE_SHIFT) #define OT_TBYTE (32 << OPSIZE_SHIFT) #define ALL_SIZE (OT_BYTE | OT_WORD | OT_DWORD | OT_QWORD | OT_OWORD) // For register operands, we mostl don't care about the size. // So let's just set all relevant flags. #define OT_FPUSIZE (OT_DWORD | OT_QWORD | OT_TBYTE) #define OT_XMMSIZE (OT_DWORD | OT_QWORD | OT_OWORD) // Macros for encoding #define OT_REGMEMOP(type) (OT_##type##REG | OT_MEMORY | OT_REGMEM) #define OT_REGONLYOP(type) (OT_##type##REG | OT_REGMEM) #define OT_MEMONLYOP (OT_MEMORY | OT_REGMEM) #define OT_MEMIMMOP (OT_MEMORY | OT_IMMEDIATE) #define OT_REGSPECOP(type) (OT_##type##REG | OT_SPECIAL) #define OT_IMMOP (OT_CONSTANT | OT_IMMEDIATE) #define OT_MEMADDROP (OT_MEMORY | OT_IMMEDIATE) // Some operations are encoded via opcode + spec field #define SPECIAL_SPEC 0x00010000 #define SPECIAL_MASK 0x00000007 #define MAX_OPERANDS 3 #define MAX_REPOP_LENGTH 20 const ut8 SEG_REG_PREFIXES[] = {0x26, 0x2e, 0x36, 0x3e, 0x64, 0x65}; typedef enum tokentype_t { TT_EOF, TT_WORD, TT_NUMBER, TT_SPECIAL } x86newTokenType; typedef enum register_t { X86R_UNDEFINED = -1, X86R_EAX = 0, X86R_ECX, X86R_EDX, X86R_EBX, X86R_ESP, X86R_EBP, X86R_ESI, X86R_EDI, X86R_EIP, X86R_AX = 0, X86R_CX, X86R_DX, X86R_BX, X86R_SP, X86R_BP, X86R_SI, X86R_DI, X86R_AL = 0, X86R_CL, X86R_DL, X86R_BL, X86R_AH, X86R_CH, X86R_DH, X86R_BH, X86R_RAX = 0, X86R_RCX, X86R_RDX, X86R_RBX, X86R_RSP, X86R_RBP, X86R_RSI, X86R_RDI, X86R_RIP, X86R_R8 = 0, X86R_R9, X86R_R10, X86R_R11, X86R_R12, X86R_R13, X86R_R14, X86R_R15, X86R_CS = 0, X86R_SS, X86R_DS, X86R_ES, X86R_FS, X86R_GS // Is this the right order? } Register; typedef struct operand_t { ut32 type; st8 sign; struct { Register reg; bool extended; }; union { struct { long offset; st8 offset_sign; Register regs[2]; int scale[2]; }; struct { ut64 immediate; bool is_good_flag; }; struct { char rep_op[MAX_REPOP_LENGTH]; }; }; bool explicit_size; ut32 dest_size; ut32 reg_size; } Operand; typedef struct Opcode_t { char *mnemonic; ut32 op[3]; size_t op_len; bool is_short; ut8 opcode[3]; int operands_count; Operand operands[MAX_OPERANDS]; bool has_bnd; } Opcode; static ut8 getsib(const ut8 sib) { if (!sib) { return 0; } return (sib & 0x8) ? 3 : getsib ((sib << 1) | 1) - 1; } static int is_al_reg(const Operand *op) { if (op->type & OT_MEMORY) { return 0; } if (op->reg == X86R_AL && op->type & OT_BYTE) { return 1; } return 0; } static int oprep(RAsm *a, ut8 *data, const Opcode *op); static int process_16bit_group_1(RAsm *a, ut8 *data, const Opcode *op, int op1) { int l = 0; int immediate = op->operands[1].immediate * op->operands[1].sign; data[l++] = 0x66; if (op->operands[1].immediate < 128) { data[l++] = 0x83; data[l++] = op->operands[0].reg | (0xc0 + op1 + op->operands[0].reg); } else { if (op->operands[0].reg == X86R_AX) { data[l++] = 0x05 + op1; } else { data[l++] = 0x81; data[l++] = (0xc0 + op1) | op->operands[0].reg; } } data[l++] = immediate; if (op->operands[1].immediate > 127) { data[l++] = immediate >> 8; } return l; } static int process_group_1(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int modrm = 0; int mod_byte = 0; int offset = 0; int mem_ref = 0; st32 immediate = 0; if (!op->operands[1].is_good_flag) { return -1; } if (a->bits == 64 && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; } if (!strcmp (op->mnemonic, "adc")) { modrm = 2; } else if (!strcmp (op->mnemonic, "add")) { modrm = 0; } else if (!strcmp (op->mnemonic, "or")) { modrm = 1; } else if (!strcmp (op->mnemonic, "and")) { modrm = 4; } else if (!strcmp (op->mnemonic, "xor")) { modrm = 6; } else if (!strcmp (op->mnemonic, "sbb")) { modrm = 3; } else if (!strcmp (op->mnemonic, "sub")) { modrm = 5; } else if (!strcmp (op->mnemonic, "cmp")) { modrm = 7; } immediate = op->operands[1].immediate * op->operands[1].sign; if (op->operands[0].type & OT_DWORD || op->operands[0].type & OT_QWORD) { if (op->operands[1].immediate < 128) { data[l++] = 0x83; } else if (op->operands[0].reg != X86R_EAX || op->operands[0].type & OT_MEMORY) { data[l++] = 0x81; } } else if (op->operands[0].type & OT_BYTE) { if (op->operands[1].immediate > 255) { eprintf ("Error: Immediate exceeds bounds\n"); return -1; } data[l++] = 0x80; } if (op->operands[0].type & OT_MEMORY) { offset = op->operands[0].offset * op->operands[0].offset_sign; if (op->operands[0].offset || op->operands[0].regs[0] == X86R_EBP) { mod_byte = 1; } if (offset < ST8_MIN || offset > ST8_MAX) { mod_byte = 2; } int reg0 = op->operands[0].regs[0]; if (reg0 == -1) { mem_ref = 1; reg0 = 5; mod_byte = 0; } data[l++] = mod_byte << 6 | modrm << 3 | reg0; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (mod_byte || mem_ref) { data[l++] = offset; if (mod_byte == 2 || mem_ref) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } else { if (op->operands[1].immediate > 127 && op->operands[0].reg == X86R_EAX) { data[l++] = 5 | modrm << 3 | op->operands[0].reg; } else { mod_byte = 3; data[l++] = mod_byte << 6 | modrm << 3 | op->operands[0].reg; } } data[l++] = immediate; if ((immediate > 127 || immediate < -128) && ((op->operands[0].type & OT_DWORD) || (op->operands[0].type & OT_QWORD))) { data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } return l; } static int process_group_2(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int modrm = 0; int mod_byte = 0; int reg0 = 0; if (a->bits == 64 && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; } if (!strcmp (op->mnemonic, "rol")) { modrm = 0; } else if (!strcmp (op->mnemonic, "ror")) { modrm = 1; } else if (!strcmp (op->mnemonic, "rcl")) { modrm = 2; } else if (!strcmp (op->mnemonic, "rcr")) { modrm = 3; } else if (!strcmp (op->mnemonic, "shl")) { modrm = 4; } else if (!strcmp (op->mnemonic, "shr")) { modrm = 5; } else if (!strcmp (op->mnemonic, "sal")) { modrm = 6; } else if (!strcmp (op->mnemonic, "sar")) { modrm = 7; } st32 immediate = op->operands[1].immediate * op->operands[1].sign; if (immediate > 255 || immediate < -128) { eprintf ("Error: Immediate exceeds bounds\n"); return -1; } if (op->operands[0].type & (OT_DWORD | OT_QWORD)) { if (op->operands[1].type & (OT_GPREG | OT_BYTE)) { data[l++] = 0xd3; } else if (immediate == 1) { data[l++] = 0xd1; } else { data[l++] = 0xc1; } } else if (op->operands[0].type & OT_BYTE) { const Operand *o = &op->operands[0]; if (o->regs[0] != -1 && o->regs[1] != -1) { data[l++] = 0xc0; data[l++] = 0x44; data[l++] = o->regs[0]| (o->regs[1]<<3); data[l++] = (ut8)((o->offset*o->offset_sign) & 0xff); data[l++] = immediate; return l; } else if (op->operands[1].type & (OT_GPREG | OT_WORD)) { data[l++] = 0xd2; } else if (immediate == 1) { data[l++] = 0xd0; } else { data[l++] = 0xc0; } } if (op->operands[0].type & OT_MEMORY) { reg0 = op->operands[0].regs[0]; mod_byte = 0; } else { reg0 = op->operands[0].reg; mod_byte = 3; } data[l++] = mod_byte << 6 | modrm << 3 | reg0; if (immediate != 1 && !(op->operands[1].type & OT_GPREG)) { data[l++] = immediate; } return l; } static int process_1byte_op(RAsm *a, ut8 *data, const Opcode *op, int op1) { int l = 0; int mod_byte = 0; int reg = 0; int rm = 0; int rex = 0; int mem_ref = 0; st32 offset = 0; int ebp_reg = 0; if (!op->operands[1].is_good_flag) { return -1; } if (op->operands[0].reg == X86R_AL && op->operands[1].type & OT_CONSTANT) { data[l++] = op1 + 4; data[l++] = op->operands[1].immediate * op->operands[1].sign; return l; } if (a->bits == 64) { if (!(op->operands[0].type & op->operands[1].type)) { return -1; } } if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) { if (op->operands[0].extended) { rex = 1; } if (op->operands[1].extended) { rex += 4; } data[l++] = 0x48 | rex; } if (op->operands[0].type & OT_MEMORY && op->operands[1].type & OT_REGALL) { if (a->bits == 64 && (op->operands[0].type & OT_DWORD) && (op->operands[1].type & OT_DWORD)) { data[l++] = 0x67; } if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) { data[l++] = op1; } else if (op->operands[0].type & (OT_DWORD | OT_QWORD) && op->operands[1].type & (OT_DWORD | OT_QWORD)) { data[l++] = op1 + 0x1; } else { eprintf ("Error: mismatched operand sizes\n"); return -1; } reg = op->operands[1].reg; rm = op->operands[0].regs[0]; offset = op->operands[0].offset * op->operands[0].offset_sign; if (rm == -1) { rm = 5; mem_ref = 1; } else { if (offset) { mod_byte = 1; if (offset < ST8_MIN || offset > ST8_MAX) { mod_byte = 2; } } else if (op->operands[0].regs[1] != X86R_UNDEFINED) { rm = 4; offset = op->operands[0].regs[1] << 3; } } } else if (op->operands[0].type & OT_REGALL) { if (op->operands[1].type & OT_MEMORY) { if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) { data[l++] = op1 + 0x2; } else if (op->operands[0].type & (OT_DWORD | OT_QWORD) && op->operands[1].type & (OT_DWORD | OT_QWORD)) { data[l++] = op1 + 0x3; } else { eprintf ("Error: mismatched operand sizes\n"); return -1; } reg = op->operands[0].reg; rm = op->operands[1].regs[0]; if (op->operands[1].scale[0] > 1) { if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[0].reg << 3 | 4; data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | op->operands[1].regs[1]; return l; } data[l++] = op->operands[0].reg << 3 | 4; // 4 = SIB data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | 5; data[l++] = op->operands[1].offset * op->operands[1].offset_sign; data[l++] = 0; data[l++] = 0; data[l++] = 0; return l; } offset = op->operands[1].offset * op->operands[1].offset_sign; if (offset) { mod_byte = 1; if (offset < ST8_MIN || offset > ST8_MAX) { mod_byte = 2; } } } else if (op->operands[1].type & OT_REGALL) { if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) { data[l++] = op1; } else if (op->operands[0].type & OT_DWORD && op->operands[1].type & OT_DWORD) { data[l++] = op1 + 0x1; } if (a->bits == 64) { if (op->operands[0].type & OT_QWORD && op->operands[1].type & OT_QWORD) { data[l++] = op1 + 0x1; } } mod_byte = 3; reg = op->operands[1].reg; rm = op->operands[0].reg; } } if (op->operands[0].regs[0] == X86R_EBP || op->operands[1].regs[0] == X86R_EBP) { //reg += 8; ebp_reg = 1; } data[l++] = mod_byte << 6 | reg << 3 | rm; if (op->operands[0].regs[0] == X86R_ESP || op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (offset || mem_ref || ebp_reg) { //if ((mod_byte > 0 && mod_byte < 3) || mem_ref) { data[l++] = offset; if (mod_byte == 2 || mem_ref) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } return l; } static int opadc(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x10); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x10); } static int opadd(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x00); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x00); } static int opand(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x20); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x20); } static int opcmp(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x38); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x38); } static int opsub(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x28); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x28); } static int opor(RAsm *a, ut8 * data, const Opcode *op) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x08); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x08); } static int opxadd(RAsm *a, ut8 *data, const Opcode *op) { int i = 0; if (op->operands_count < 2 ) { return -1; } if (a->bits == 64) { data[i++] = 0x48; }; data[i++] = 0x0f; if (op->operands[0].type & OT_BYTE && op->operands[1].type & OT_BYTE) { data[i++] = 0xc0; } else { data[i++] = 0xc1; } if (op->operands[0].type & OT_REGALL && op->operands[1].type & OT_REGALL) { // TODO memory modes data[i] |= 0xc0; data[i] |= (op->operands[1].reg << 3); data[i++] |= op->operands[0].reg; } return i; } static int opxor(RAsm *a, ut8 * data, const Opcode *op) { if (op->operands_count < 2) { return -1; } if (op->operands[0].type == 0x80 && op->operands[0].reg == X86R_UNDEFINED) { return -1; } if (op->operands[1].type == 0x80 && op->operands[0].reg == X86R_UNDEFINED) { return -1; } if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x30); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x30); } static int opnot(RAsm *a, ut8 * data, const Opcode *op) { int l = 0; if(op->operands[0].reg == X86R_UNDEFINED) { return -1; } data[l++] = 0xf7; data[l++] = 0xd0 | op->operands[0].reg; return l; } static int opsbb(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD) { return process_16bit_group_1 (a, data, op, 0x18); } if (!is_al_reg (&op->operands[0])) { return process_group_1 (a, data, op); } } return process_1byte_op (a, data, op, 0x18); } static int opbswap(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if (op->operands[0].type & OT_REGALL) { if (op->operands[0].reg == X86R_UNDEFINED) { return -1; } if (op->operands[0].type & OT_QWORD) { data[l++] = 0x48; data[l++] = 0x0f; data[l++] = 0xc8 + op->operands[0].reg; } else if (op->operands[0].type & OT_DWORD) { data[l++] = 0x0f; data[l++] = 0xc8 + op->operands[0].reg; } else { return -1; } } return l; } static int opcall(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int immediate = 0; int offset = 0; int mod = 0; if (op->operands[0].type & OT_GPREG) { if (op->operands[0].reg == X86R_UNDEFINED) { return -1; } if (a->bits == 64 && op->operands[0].extended) { data[l++] = 0x41; } data[l++] = 0xff; mod = 3; data[l++] = mod << 6 | 2 << 3 | op->operands[0].reg; } else if (op->operands[0].type & OT_MEMORY) { if (op->operands[0].regs[0] == X86R_UNDEFINED) { return -1; } data[l++] = 0xff; offset = op->operands[0].offset * op->operands[0].offset_sign; if (offset) { mod = 1; if (offset > 127 || offset < -128) { mod = 2; } } data[l++] = mod << 6 | 2 << 3 | op->operands[0].regs[0]; if (mod) { data[l++] = offset; if (mod == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } else { ut64 instr_offset = a->pc; data[l++] = 0xe8; immediate = op->operands[0].immediate * op->operands[0].sign; immediate -= instr_offset + 5; data[l++] = immediate; data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } return l; } static int opcmov(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int mod_byte = 0; int offset = 0; if (op->operands[0].type & OT_MEMORY || op->operands[1].type & OT_CONSTANT) { return -1; } data[l++] = 0x0f; char *cmov = op->mnemonic + 4; if (!strcmp (cmov, "o")) { data[l++] = 0x40; } else if (!strcmp (cmov, "no")) { data [l++] = 0x41; } else if (!strcmp (cmov, "b") || !strcmp (cmov, "c") || !strcmp (cmov, "nae")) { data [l++] = 0x42; } else if (!strcmp (cmov, "ae") || !strcmp (cmov, "nb") || !strcmp (cmov, "nc")) { data [l++] = 0x43; } else if (!strcmp (cmov, "e") || !strcmp (cmov, "z")) { data [l++] = 0x44; } else if (!strcmp (cmov, "ne") || !strcmp (cmov, "nz")) { data [l++] = 0x45; } else if (!strcmp (cmov, "be") || !strcmp (cmov, "na")) { data [l++] = 0x46; } else if (!strcmp (cmov, "a") || !strcmp (cmov, "nbe")) { data [l++] = 0x47; } else if (!strcmp (cmov, "s")) { data [l++] = 0x48; } else if (!strcmp (cmov, "ns")) { data [l++] = 0x49; } else if (!strcmp (cmov, "p") || !strcmp (cmov, "pe")) { data [l++] = 0x4a; } else if (!strcmp (cmov, "np") || !strcmp (cmov, "po")) { data [l++] = 0x4b; } else if (!strcmp (cmov, "l") || !strcmp (cmov, "nge")) { data [l++] = 0x4c; } else if (!strcmp (cmov, "ge") || !strcmp (cmov, "nl")) { data [l++] = 0x4d; } else if (!strcmp (cmov, "le") || !strcmp (cmov, "ng")) { data [l++] = 0x4e; } else if (!strcmp (cmov, "g") || !strcmp (cmov, "nle")) { data [l++] = 0x4f; } if (op->operands[0].type & OT_REGALL) { if (op->operands[1].type & OT_MEMORY) { if (op->operands[1].scale[0] > 1) { if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[0].reg << 3 | 4; data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | op->operands[1].regs[1]; return l; } offset = op->operands[1].offset * op->operands[1].offset_sign; if (op->operands[1].scale[0] == 2 && offset) { data[l++] = 0x40 | op->operands[0].reg << 3 | 4; // 4 = SIB } else { data[l++] = op->operands[0].reg << 3 | 4; // 4 = SIB } if (op->operands[1].scale[0] == 2) { data[l++] = op->operands[1].regs[0] << 3 | op->operands[1].regs[0]; } else { data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | 5; } if (offset) { data[l++] = offset; if (offset < ST8_MIN || offset > ST8_MAX) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } return l; } if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[0].reg << 3 | 4; data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0]; return l; } offset = op->operands[1].offset * op->operands[1].offset_sign; if (op->operands[1].offset || op->operands[1].regs[0] == X86R_EBP) { mod_byte = 1; } if (offset < ST8_MIN || offset > ST8_MAX) { mod_byte = 2; } data[l++] = mod_byte << 6 | op->operands[0].reg << 3 | op->operands[1].regs[0]; if (mod_byte) { data[l++] = offset; if (mod_byte == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } else { data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg; } } return l; } static int opmovx(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int word = 0; char *movx = op->mnemonic + 3; if (!(op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_MEMORY)) { return -1; } if (op->operands[1].type & OT_WORD) { word = 1; } data[l++] = 0x0f; if (!strcmp (movx, "zx")) { data[l++] = 0xb6 + word; } else if (!strcmp (movx, "sx")) { data[l++] = 0xbe + word; } data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0]; if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } return l; } static int opaam(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int immediate = op->operands[0].immediate * op->operands[0].sign; data[l++] = 0xd4; if (immediate == 0) { data[l++] = 0x0a; } else if (immediate < 256 && immediate > -129) { data[l++] = immediate; } return l; } static int opdec(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type) { eprintf ("Error: Invalid operands\n"); return -1; } int l = 0; int size = op->operands[0].type & ALL_SIZE; if (op->operands[0].explicit_size) { size = op->operands[0].dest_size; } if (size & OT_WORD) { data[l++] = 0x66; } //rex prefix int rex = 1 << 6; bool use_rex = false; if (size & OT_QWORD) { //W field use_rex = true; rex |= 1 << 3; } if (op->operands[0].extended) { //B field use_rex = true; rex |= 1; } //opcode selection int opcode; if (size & OT_BYTE) { opcode = 0xfe; } else { opcode = 0xff; } if (!(op->operands[0].type & OT_MEMORY)) { if (use_rex) { data[l++] = rex; } if (a->bits > 32 || size & OT_BYTE) { data[l++] = opcode; } if (a->bits == 32 && size & (OT_DWORD | OT_WORD)) { data[l++] = 0x48 | op->operands[0].reg; } else { data[l++] = 0xc8 | op->operands[0].reg; } return l; } //modrm and SIB selection bool rip_rel = op->operands[0].regs[0] == X86R_RIP; int offset = op->operands[0].offset * op->operands[0].offset_sign; int modrm = 0; int mod; int reg = 0; int rm; bool use_sib = false; int sib; //mod if (offset == 0) { mod = 0; } else if (offset < 128 && offset > -129) { mod = 1; } else { mod = 2; } if (op->operands[0].regs[0] & OT_WORD) { if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) { rm = B0000; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) { rm = B0001; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) { rm = B0010; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) { rm = B0011; } else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) { rm = B0100; } else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) { rm = B0101; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) { rm = B0111; } else { //TODO allow for displacement only when parser is reworked return -1; } modrm = (mod << 6) | (reg << 3) | rm; } else { //rm if (op->operands[0].extended) { rm = op->operands[0].reg; } else { rm = op->operands[0].regs[0]; } //[epb] alone is illegal, so we need to fake a [ebp+0] if (rm == 5 && mod == 0) { mod = 1; } //sib int index = op->operands[0].regs[1]; int scale = getsib(op->operands[0].scale[1]); if (index != -1) { use_sib = true; sib = (scale << 6) | (index << 3) | rm; } else if (rm == 4) { use_sib = true; sib = 0x24; } if (use_sib) { rm = B0100; } if (rip_rel) { modrm = (B0000 << 6) | (reg << 3) | B0101; sib = (scale << 6) | (B0100 << 3) | B0101; } else { modrm = (mod << 6) | (reg << 3) | rm; } modrm |= 1<<3; } if (use_rex) { data[l++] = rex; } data[l++] = opcode; data[l++] = modrm; if (use_sib) { data[l++] = sib; } //offset if (mod == 1) { data[l++] = offset; } else if (op->operands[0].regs[0] & OT_WORD && mod == 2) { data[l++] = offset; data[l++] = offset >> 8; } else if (mod == 2 || rip_rel) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } return l; } static int opidiv(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0x48; } switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x66; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xf6; } else { data[l++] = 0xf7; } if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x38 | op->operands[0].regs[0]; } else { data[l++] = 0xf8 | op->operands[0].reg; } break; default: return -1; } return l; } static int opdiv(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0x48; } switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x66; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xf6; } else { data[l++] = 0xf7; } if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x30 | op->operands[0].regs[0]; } else { data[l++] = 0xf0 | op->operands[0].reg; } break; default: return -1; } return l; } static int opimul(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int offset = 0; st64 immediate = 0; if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0x48; } switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x66; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xf6; } else { data[l++] = 0xf7; } if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x28 | op->operands[0].regs[0]; } else { data[l++] = 0xe8 | op->operands[0].reg; } break; case 2: if (op->operands[0].type & OT_GPREG) { if (op->operands[1].type & OT_CONSTANT) { if (op->operands[1].immediate == -1) { eprintf ("Error: Immediate exceeds max\n"); return -1; } immediate = op->operands[1].immediate * op->operands[1].sign; if (op->operands[0].type & OT_GPREG) { if (immediate >= 128) { data[l++] = 0x69; } else { data[l++] = 0x6b; } data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[0].reg; data[l++] = immediate; if (immediate >= 128) { data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } if (a->bits == 64 && immediate > UT32_MAX) { data[l++] = immediate >> 32; data[l++] = immediate >> 40; data[l++] = immediate >> 48; data[l++] = immediate >> 56; } } } else if (op->operands[1].type & OT_MEMORY) { data[l++] = 0x0f; data[l++] = 0xaf; if (op->operands[1].regs[0] != X86R_UNDEFINED) { offset = op->operands[1].offset * op->operands[1].offset_sign; if (offset != 0) { if (offset >= 128 || offset <= -128) { data[l] = 0x80; } else { data[l] = 0x40; } data[l++] |= op->operands[0].reg << 3 | op->operands[1].regs[0]; data[l++] = offset; if (offset >= 128 || offset <= -128) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else { if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = 0x04 | op->operands[0].reg << 3; data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0]; } else { data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0]; } } } else { immediate = op->operands[1].immediate * op->operands[1].sign; data[l++] = op->operands[0].reg << 3 | 0x5; data[l++] = immediate; data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } } else if (op->operands[1].type & OT_GPREG) { data[l++] = 0x0f; data[l++] = 0xaf; data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg; } } break; case 3: if (op->operands[0].type & OT_GPREG && (op->operands[1].type & OT_GPREG || op->operands[1].type & OT_MEMORY) && op->operands[2].type & OT_CONSTANT) { data[l++] = 0x6b; if (op->operands[1].type & OT_MEMORY) { if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = 0x04 | op->operands[0].reg << 3; data[l++] = op->operands[1].regs[0] | op->operands[1].regs[1] << 3; } else { offset = op->operands[1].offset * op->operands[1].offset_sign; if (offset != 0) { if (offset >= 128 || offset <= -128) { data[l] = 0x80; } else { data[l] = 0x40; } data[l++] |= op->operands[0].reg << 3; data[l++] = offset; if (offset >= 128 || offset <= -128) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else { data[l++] = 0x00 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } } } else { data[l++] = 0xc0 | op->operands[0].reg << 3 | op->operands[1].reg; } immediate = op->operands[2].immediate * op->operands[2].sign; data[l++] = immediate; if (immediate >= 128 || immediate <= -128) { data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } } break; default: return -1; } return l; } static int opin(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; st32 immediate = 0; if (op->operands[1].reg == X86R_DX) { if (op->operands[0].reg == X86R_AL && op->operands[0].type & OT_BYTE) { data[l++] = 0xec; return l; } if (op->operands[0].reg == X86R_AX && op->operands[0].type & OT_WORD) { data[l++] = 0x66; data[l++] = 0xed; return l; } if (op->operands[0].reg == X86R_EAX && op->operands[0].type & OT_DWORD) { data[l++] = 0xed; return l; } } else if (op->operands[1].type & OT_CONSTANT) { immediate = op->operands[1].immediate * op->operands[1].sign; if (immediate > 255 || immediate < -128) { return -1; } if (op->operands[0].reg == X86R_AL && op->operands[0].type & OT_BYTE) { data[l++] = 0xe4; } else if (op->operands[0].reg == X86R_AX && op->operands[0].type & OT_BYTE) { data[l++] = 0x66; data[l++] = 0xe5; } else if (op->operands[0].reg == X86R_EAX && op->operands[0].type & OT_DWORD) { data[l++] = 0xe5; } data[l++] = immediate; } return l; } static int opclflush(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int offset = 0; int mod_byte = 0; if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x0f; data[l++] = 0xae; offset = op->operands[0].offset * op->operands[0].offset_sign; if (offset) { if (offset < ST8_MIN || offset > ST8_MAX) { mod_byte = 2; } else { mod_byte = 1; } } data[l++] = (mod_byte << 6) | (7 << 3) | op->operands[0].regs[0]; if (mod_byte) { data[l++] = offset; if (mod_byte == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } return l; } static int opinc(RAsm *a, ut8 *data, const Opcode *op) { if (op->operands[1].type) { eprintf ("Error: Invalid operands\n"); return -1; } int l = 0; int size = op->operands[0].type & ALL_SIZE; if (op->operands[0].explicit_size) { size = op->operands[0].dest_size; } if (size & OT_WORD) { data[l++] = 0x66; } //rex prefix int rex = 1 << 6; bool use_rex = false; if (size & OT_QWORD) { //W field use_rex = true; rex |= 1 << 3; } if (op->operands[0].extended) { //B field use_rex = true; rex |= 1; } //opcode selection int opcode; if (size & OT_BYTE) { opcode = 0xfe; } else { opcode = 0xff; } if (!(op->operands[0].type & OT_MEMORY)) { if (use_rex) { data[l++] = rex; } if (a->bits > 32 || size & OT_BYTE) { data[l++] = opcode; } if (a->bits == 32 && size & (OT_DWORD | OT_WORD)) { data[l++] = 0x40 | op->operands[0].reg; } else { data[l++] = 0xc0 | op->operands[0].reg; } return l; } //modrm and SIB selection bool rip_rel = op->operands[0].regs[0] == X86R_RIP; int offset = op->operands[0].offset * op->operands[0].offset_sign; int modrm = 0; int mod; int reg = 0; int rm; bool use_sib = false; int sib; //mod if (offset == 0) { mod = 0; } else if (offset < 128 && offset > -129) { mod = 1; } else { mod = 2; } if (op->operands[0].regs[0] & OT_WORD) { if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) { rm = B0000; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) { rm = B0001; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) { rm = B0010; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) { rm = B0011; } else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) { rm = B0100; } else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) { rm = B0101; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) { rm = B0111; } else { //TODO allow for displacement only when parser is reworked return -1; } modrm = (mod << 6) | (reg << 3) | rm; } else { //rm if (op->operands[0].extended) { rm = op->operands[0].reg; } else { rm = op->operands[0].regs[0]; } //[epb] alone is illegal, so we need to fake a [ebp+0] if (rm == 5 && mod == 0) { mod = 1; } //sib int index = op->operands[0].regs[1]; int scale = getsib(op->operands[0].scale[1]); if (index != -1) { use_sib = true; sib = (scale << 6) | (index << 3) | rm; } else if (rm == 4) { use_sib = true; sib = 0x24; } if (use_sib) { rm = B0100; } if (rip_rel) { modrm = (B0000 << 6) | (reg << 3) | B0101; sib = (scale << 6) | (B0100 << 3) | B0101; } else { modrm = (mod << 6) | (reg << 3) | rm; } } if (use_rex) { data[l++] = rex; } data[l++] = opcode; data[l++] = modrm; if (use_sib) { data[l++] = sib; } //offset if (mod == 1) { data[l++] = offset; } else if (op->operands[0].regs[0] & OT_WORD && mod == 2) { data[l++] = offset; data[l++] = offset >> 8; } else if (mod == 2 || rip_rel) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } return l; } static int opint(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if (op->operands[0].type & OT_CONSTANT) { st32 immediate = op->operands[0].immediate * op->operands[0].sign; if (immediate <= 255 && immediate >= -128) { data[l++] = 0xcd; data[l++] = immediate; } } return l; } static int opjc(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; bool is_short = op->is_short; // st64 bigimm = op->operands[0].immediate * op->operands[0].sign; st64 immediate = op->operands[0].immediate * op->operands[0].sign; if (is_short && (immediate > ST8_MAX || immediate < ST8_MIN)) { return l; } immediate -= a->pc; if (immediate > ST32_MAX || immediate < -ST32_MAX) { return -1; } if (!strcmp (op->mnemonic, "jmp")) { if (op->operands[0].type & OT_GPREG) { data[l++] = 0xff; if (op->operands[0].type & OT_MEMORY) { if (op->operands[0].offset) { int offset = op->operands[0].offset * op->operands[0].offset_sign; if (offset >= 128 || offset <= -129) { data[l] = 0xa0; } else { data[l] = 0x60; } data[l++] |= op->operands[0].regs[0]; data[l++] = offset; if (op->operands[0].offset >= 0x80) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else { data[l++] = 0x20 | op->operands[0].regs[0]; } } else { data[l++] = 0xe0 | op->operands[0].reg; } } else { if (-0x80 <= (immediate - 2) && (immediate - 2) <= 0x7f) { /* relative byte address */ data[l++] = 0xeb; data[l++] = immediate - 2; } else { /* relative address */ immediate -= 5; data[l++] = 0xe9; data[l++] = immediate; data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } } return l; } if (immediate <= 0x81 && immediate > -0x7f) { is_short = true; } if (a->bits == 16 && (immediate > 0x81 || immediate < -0x7e)) { data[l++] = 0x66; is_short = false; immediate --; } if (!is_short) {data[l++] = 0x0f;} if (!strcmp (op->mnemonic, "ja") || !strcmp (op->mnemonic, "jnbe")) { data[l++] = 0x87; } else if (!strcmp (op->mnemonic, "jae") || !strcmp (op->mnemonic, "jnb") || !strcmp (op->mnemonic, "jnc")) { data[l++] = 0x83; } else if (!strcmp (op->mnemonic, "jz") || !strcmp (op->mnemonic, "je")) { data[l++] = 0x84; } else if (!strcmp (op->mnemonic, "jb") || !strcmp (op->mnemonic, "jnae") || !strcmp (op->mnemonic, "jc")) { data[l++] = 0x82; } else if (!strcmp (op->mnemonic, "jbe") || !strcmp (op->mnemonic, "jna")) { data[l++] = 0x86; } else if (!strcmp (op->mnemonic, "jg") || !strcmp (op->mnemonic, "jnle")) { data[l++] = 0x8f; } else if (!strcmp (op->mnemonic, "jge") || !strcmp (op->mnemonic, "jnl")) { data[l++] = 0x8d; } else if (!strcmp (op->mnemonic, "jl") || !strcmp (op->mnemonic, "jnge")) { data[l++] = 0x8c; } else if (!strcmp (op->mnemonic, "jle") || !strcmp (op->mnemonic, "jng")) { data[l++] = 0x8e; } else if (!strcmp (op->mnemonic, "jne") || !strcmp (op->mnemonic, "jnz")) { data[l++] = 0x85; } else if (!strcmp (op->mnemonic, "jno")) { data[l++] = 0x81; } else if (!strcmp (op->mnemonic, "jnp") || !strcmp (op->mnemonic, "jpo")) { data[l++] = 0x8b; } else if (!strcmp (op->mnemonic, "jns")) { data[l++] = 0x89; } else if (!strcmp (op->mnemonic, "jo")) { data[l++] = 0x80; } else if (!strcmp (op->mnemonic, "jp") || !strcmp(op->mnemonic, "jpe")) { data[l++] = 0x8a; } else if (!strcmp (op->mnemonic, "js") || !strcmp (op->mnemonic, "jz")) { data[l++] = 0x88; } if (is_short) { data[l-1] -= 0x10; } immediate -= is_short ? 2 : 6; data[l++] = immediate; if (!is_short) { data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } return l; } static int oplea(RAsm *a, ut8 *data, const Opcode *op){ int l = 0; int mod = 0; st32 offset = 0; int reg = 0; int rm = 0; if (op->operands[0].type & OT_REGALL && op->operands[1].type & (OT_MEMORY | OT_CONSTANT)) { if (a->bits == 64) { data[l++] = 0x48; } data[l++] = 0x8d; if (op->operands[1].regs[0] == X86R_UNDEFINED) { int high = 0xff00 & op->operands[1].offset; data[l++] = op->operands[0].reg << 3 | 5; data[l++] = op->operands[1].offset; data[l++] = high >> 8; data[l++] = op->operands[1].offset >> 16; data[l++] = op->operands[1].offset >> 24; return l; } else { reg = op->operands[0].reg; rm = op->operands[1].regs[0]; offset = op->operands[1].offset * op->operands[1].offset_sign; if (offset != 0 || op->operands[1].regs[0] == X86R_EBP) { mod = 1; if (offset >= 128 || offset < -128) { mod = 2; } data[l++] = mod << 6 | reg << 3 | rm; if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } data[l++] = offset; if (mod == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else { data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0]; if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } } } } return l; } static int oples(RAsm *a, ut8* data, const Opcode *op) { int l = 0; int offset = 0; int mod = 0; if (op->operands[1].type & OT_MEMORY) { data[l++] = 0xc4; if (op->operands[1].type & OT_GPREG) { offset = op->operands[1].offset * op->operands[1].offset_sign; if (offset) { mod = 1; if (offset > 128 || offset < -128) { mod = 2; } } data[l++] = mod << 6 | op->operands[0].reg << 3 | op->operands[1].regs[0]; if (mod) { data[l++] = offset; if (mod > 1) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } else { offset = op->operands[1].offset * op->operands[1].offset_sign; data[l++] = 0x05; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } return l; } static int opmov(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; st64 offset = 0; int mod = 0; int base = 0; int rex = 0; ut64 immediate = 0; if (op->operands[1].type & OT_CONSTANT) { if (!op->operands[1].is_good_flag) { return -1; } if (op->operands[1].immediate == -1) { return -1; } immediate = op->operands[1].immediate * op->operands[1].sign; if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD))) { if (!(op->operands[1].type & OT_CONSTANT) && op->operands[1].extended) { data[l++] = 0x49; } else { data[l++] = 0x48; } } else if (op->operands[0].extended) { data[l++] = 0x41; } if (op->operands[0].type & OT_WORD) { if (a->bits > 16) { data[l++] = 0x66; } } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xb0 | op->operands[0].reg; data[l++] = immediate; } else { if (a->bits == 64 && ((op->operands[0].type & OT_QWORD) | (op->operands[1].type & OT_QWORD)) && immediate < UT32_MAX) { data[l++] = 0xc7; data[l++] = 0xc0 | op->operands[0].reg; } else { data[l++] = 0xb8 | op->operands[0].reg; } data[l++] = immediate; data[l++] = immediate >> 8; if (!(op->operands[0].type & OT_WORD)) { data[l++] = immediate >> 16; data[l++] = immediate >> 24; } if (a->bits == 64 && immediate > UT32_MAX) { data[l++] = immediate >> 32; data[l++] = immediate >> 40; data[l++] = immediate >> 48; data[l++] = immediate >> 56; } } } else if (op->operands[0].type & OT_MEMORY) { if (!op->operands[0].explicit_size) { if (op->operands[0].type & OT_GPREG) { ((Opcode *)op)->operands[0].dest_size = op->operands[0].reg_size; } else { return -1; } } int dest_bits = 8 * ((op->operands[0].dest_size & ALL_SIZE) >> OPSIZE_SHIFT); int reg_bits = 8 * ((op->operands[0].reg_size & ALL_SIZE) >> OPSIZE_SHIFT); int offset = op->operands[0].offset * op->operands[0].offset_sign; //addr_size_override prefix bool use_aso = false; if (reg_bits < a->bits) { use_aso = true; } //op_size_override prefix bool use_oso = false; if (dest_bits == 16) { use_oso = true; } bool rip_rel = op->operands[0].regs[0] == X86R_RIP; //rex prefix int rex = 1 << 6; bool use_rex = false; if (dest_bits == 64) { //W field use_rex = true; rex |= 1 << 3; } if (op->operands[0].extended) { //B field use_rex = true; rex |= 1; } //opcode selection int opcode; if (dest_bits == 8) { opcode = 0xc6; } else { opcode = 0xc7; } //modrm and SIB selection int modrm = 0; int mod; int reg = 0; int rm; bool use_sib = false; int sib; //mod if (offset == 0) { mod = 0; } else if (offset < 128 && offset > -129) { mod = 1; } else { mod = 2; } if (reg_bits == 16) { if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_SI) { rm = B0000; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == X86R_DI) { rm = B0001; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_SI) { rm = B0010; } else if (op->operands[0].regs[0] == X86R_BP && op->operands[0].regs[1] == X86R_DI) { rm = B0011; } else if (op->operands[0].regs[0] == X86R_SI && op->operands[0].regs[1] == -1) { rm = B0100; } else if (op->operands[0].regs[0] == X86R_DI && op->operands[0].regs[1] == -1) { rm = B0101; } else if (op->operands[0].regs[0] == X86R_BX && op->operands[0].regs[1] == -1) { rm = B0111; } else { //TODO allow for displacement only when parser is reworked return -1; } modrm = (mod << 6) | (reg << 3) | rm; } else { //rm if (op->operands[0].extended) { rm = op->operands[0].reg; } else { rm = op->operands[0].regs[0]; } //[epb] alone is illegal, so we need to fake a [ebp+0] if (rm == 5 && mod == 0) { mod = 1; } //sib int index = op->operands[0].regs[1]; int scale = getsib(op->operands[0].scale[1]); if (index != -1) { use_sib = true; sib = (scale << 6) | (index << 3) | rm; } else if (rm == 4) { use_sib = true; sib = 0x24; } if (use_sib) { rm = B0100; } if (rip_rel) { modrm = (B0000 << 6) | (reg << 3) | B0101; sib = (scale << 6) | (B0100 << 3) | B0101; } else { modrm = (mod << 6) | (reg << 3) | rm; } } //build the final result if (use_aso) { data[l++] = 0x67; } if (use_oso) { data[l++] = 0x66; } if (use_rex) { data[l++] = rex; } data[l++] = opcode; data[l++] = modrm; if (use_sib) { data[l++] = sib; } //offset if (mod == 1) { data[l++] = offset; } else if (reg_bits == 16 && mod == 2) { data[l++] = offset; data[l++] = offset >> 8; } else if (mod == 2 || rip_rel) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } //immediate int byte; for (byte = 0; byte < dest_bits && byte < 32; byte += 8) { data[l++] = (immediate >> byte); } } } else if (op->operands[1].type & OT_REGALL && !(op->operands[1].type & OT_MEMORY)) { if (op->operands[0].type & OT_CONSTANT) { return -1; } if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG && op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { return -1; } // Check reg sizes match if (op->operands[0].type & OT_REGTYPE && op->operands[1].type & OT_REGTYPE) { if (!((op->operands[0].type & ALL_SIZE) & (op->operands[1].type & ALL_SIZE))) { return -1; } } if (a->bits == 64) { if (op->operands[0].extended) { rex = 1; } if (op->operands[1].extended) { rex += 4; } if (op->operands[1].type & OT_QWORD) { if (!(op->operands[0].type & OT_QWORD)) { data[l++] = 0x67; data[l++] = 0x48; } } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48 | rex; } if (op->operands[1].type & OT_DWORD && op->operands[0].type & OT_DWORD) { data[l++] = 0x40 | rex; } } else if (op->operands[0].extended && op->operands[1].extended) { data[l++] = 0x45; } offset = op->operands[0].offset * op->operands[0].offset_sign; if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { data[l++] = 0x8c; } else { if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; } data[l++] = (op->operands[0].type & OT_BYTE) ? 0x88 : 0x89; } if (op->operands[0].scale[0] > 1) { data[l++] = op->operands[1].reg << 3 | 4; data[l++] = getsib (op->operands[0].scale[0]) << 6 | op->operands[0].regs[0] << 3 | 5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (!(op->operands[0].type & OT_MEMORY)) { if (op->operands[0].reg == X86R_UNDEFINED || op->operands[1].reg == X86R_UNDEFINED) { return -1; } mod = 0x3; data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].reg; } else if (op->operands[0].regs[0] == X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[0].type & OT_MEMORY) { if (op->operands[0].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[1].reg << 3 | 0x4; data[l++] = op->operands[0].regs[1] << 3 | op->operands[0].regs[0]; return l; } if (offset) { mod = (offset > 128 || offset < -129) ? 0x2 : 0x1; } if (op->operands[0].regs[0] == X86R_EBP) { mod = 0x2; } data[l++] = mod << 6 | op->operands[1].reg << 3 | op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (offset) { data[l++] = offset; } if (mod == 2) { // warning C4293: '>>': shift count negative or too big, undefined behavior data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } else if (op->operands[1].type & OT_MEMORY) { if (op->operands[0].type & OT_MEMORY) { return -1; } offset = op->operands[1].offset * op->operands[1].offset_sign; if (op->operands[0].reg == X86R_EAX && op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = 0x48; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xa0; } else { data[l++] = 0xa1; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; if (a->bits == 64) { data[l++] = offset >> 32; data[l++] = offset >> 40; data[l++] = offset >> 48; data[l++] = offset >> 54; } return l; } if (op->operands[0].type & OT_BYTE && a->bits == 64 && op->operands[1].regs[0]) { if (op->operands[1].regs[0] >= X86R_R8 && op->operands[0].reg < 4) { data[l++] = 0x41; data[l++] = 0x8a; data[l++] = op->operands[0].reg << 3 | (op->operands[1].regs[0] - 8); return l; } return -1; } if (op->operands[1].type & OT_REGTYPE & OT_SEGMENTREG) { if (op->operands[1].scale[0] == 0) { return -1; } data[l++] = SEG_REG_PREFIXES[op->operands[1].regs[0]]; data[l++] = 0x8b; data[l++] = op->operands[0].reg << 3 | 0x5; data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; return l; } if (a->bits == 64) { if (op->operands[0].type & OT_QWORD) { if (!(op->operands[1].type & OT_QWORD)) { if (op->operands[1].regs[0] != -1) { data[l++] = 0x67; } data[l++] = 0x48; } } else if (op->operands[1].type & OT_DWORD) { data[l++] = 0x44; } else if (!(op->operands[1].type & OT_QWORD)) { data[l++] = 0x67; } if (op->operands[1].type & OT_QWORD && op->operands[0].type & OT_QWORD) { data[l++] = 0x48; } } if (op->operands[0].type & OT_WORD) { data[l++] = 0x66; data[l++] = op->operands[1].type & OT_BYTE ? 0x8a : 0x8b; } else { data[l++] = (op->operands[1].type & OT_BYTE || op->operands[0].type & OT_BYTE) ? 0x8a : 0x8b; } if (op->operands[1].regs[0] == X86R_UNDEFINED) { if (a->bits == 64) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = 0x25; } else { data[l++] = op->operands[0].reg << 3 | 0x5; } data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } else { if (op->operands[1].scale[0] > 1) { data[l++] = op->operands[0].reg << 3 | 4; if (op->operands[1].scale[0] >= 2) { base = 5; } if (base) { data[l++] = getsib (op->operands[1].scale[0]) << 6 | op->operands[1].regs[0] << 3 | base; } else { data[l++] = getsib (op->operands[1].scale[0]) << 3 | op->operands[1].regs[0]; } if (offset || base) { data[l++] = offset; data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } return l; } if (op->operands[1].regs[1] != X86R_UNDEFINED) { data[l++] = op->operands[0].reg << 3 | 0x4; data[l++] = op->operands[1].regs[1] << 3 | op->operands[1].regs[0]; return l; } if (offset || op->operands[1].regs[0] == X86R_EBP) { mod = 0x2; if (op->operands[1].offset > 127) { mod = 0x4; } } if (a->bits == 64 && offset && op->operands[0].type & OT_QWORD) { if (op->operands[1].regs[0] == X86R_RIP) { data[l++] = 0x5; } else { if (op->operands[1].offset > 127) { data[l++] = 0x80 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } else { data[l++] = 0x40 | op->operands[1].regs[0]; } } if (op->operands[1].offset > 127) { mod = 0x1; } } else { if (op->operands[1].regs[0] == X86R_EIP && (op->operands[0].type & OT_DWORD)) { data[l++] = 0x0d; } else if (op->operands[1].regs[0] == X86R_RIP && (op->operands[0].type & OT_QWORD)) { data[l++] = 0x05; } else { data[l++] = mod << 5 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } } if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } if (mod >= 0x2) { data[l++] = offset; if (op->operands[1].offset > 128 || op->operands[1].regs[0] == X86R_EIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else if (a->bits == 64 && (offset || op->operands[1].regs[0] == X86R_RIP)) { data[l++] = offset; if (op->operands[1].offset > 127 || op->operands[1].regs[0] == X86R_RIP) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } } } return l; } static int opmul(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0x48; } switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x66; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xf6; } else { data[l++] = 0xf7; } if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x20 | op->operands[0].regs[0]; } else { data[l++] = 0xe0 | op->operands[0].reg; } break; default: return -1; } return l; } static int oppop(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int offset = 0; int mod = 0; if (op->operands[0].type & OT_GPREG) { if (op->operands[0].type & OT_MEMORY) { return -1; } if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG) { ut8 base; if (op->operands[0].reg & X86R_FS) { data[l++] = 0x0f; base = 0x81; } else { base = 0x7; } data[l++] = base + (8 * op->operands[0].reg); } else { ut8 base = 0x58; data[l++] = base + op->operands[0].reg; } } else if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x8f; offset = op->operands[0].offset * op->operands[0].offset_sign; if (offset != 0 || op->operands[0].regs[0] == X86R_EBP) { mod = 1; if (offset >= 128 || offset < -128) { mod = 2; } data[l++] = mod << 6 | op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } data[l++] = offset; if (mod == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else { data[l++] = op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } } } return l; } static int oppush(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int mod = 0; st32 immediate = 0;; st32 offset = 0; if (op->operands[0].type & OT_GPREG && !(op->operands[0].type & OT_MEMORY)) { if (op->operands[0].type & OT_REGTYPE & OT_SEGMENTREG) { ut8 base; if (op->operands[0].reg & X86R_FS) { data[l++] = 0x0f; base = 0x80; } else { base = 0x6; } data[l++] = base + (8 * op->operands[0].reg); } else { if (op->operands[0].extended && a->bits == 64) { data[l++] = 0x41; } ut8 base = 0x50; data[l++] = base + op->operands[0].reg; } } else if (op->operands[0].type & OT_MEMORY) { data[l++] = 0xff; offset = op->operands[0].offset * op->operands[0].offset_sign; mod = 0; if (offset != 0 || op->operands[0].regs[0] == X86R_EBP) { mod = 1; if (offset >= 128 || offset < -128) { mod = 2; } data[l++] = mod << 6 | 6 << 3 | op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } data[l++] = offset; if (mod == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else { mod = 3; data[l++] = mod << 4 | op->operands[0].regs[0]; if (op->operands[0].regs[0] == X86R_ESP) { data[l++] = 0x24; } } } else { immediate = op->operands[0].immediate * op->operands[0].sign; if (immediate >= 128 || immediate < -128) { data[l++] = 0x68; data[l++] = immediate; data[l++] = immediate >> 8; data[l++] = immediate >> 16; data[l++] = immediate >> 24; } else { data[l++] = 0x6a; data[l++] = immediate; } } return l; } static int opout(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; st32 immediate = 0; if (op->operands[0].reg == X86R_DX) { if (op->operands[1].reg == X86R_AL && op->operands[1].type & OT_BYTE) { data[l++] = 0xee; return l; } if (op->operands[1].reg == X86R_AX && op->operands[1].type & OT_WORD) { data[l++] = 0x66; data[l++] = 0xef; return l; } if (op->operands[1].reg == X86R_EAX && op->operands[1].type & OT_DWORD) { data[l++] = 0xef; return l; } } else if (op->operands[0].type & OT_CONSTANT) { immediate = op->operands[0].immediate * op->operands[0].sign; if (immediate > 255 || immediate < -128) { return -1; } if (op->operands[1].reg == X86R_AL && op->operands[1].type & OT_BYTE) { data[l++] = 0xe6; } else if (op->operands[1].reg == X86R_AX && op->operands[1].type & OT_WORD) { data[l++] = 0x66; data[l++] = 0xe7; } else if (op->operands[1].reg == X86R_EAX && op->operands[1].type & OT_DWORD) { data[l++] = 0xe7; } else { return -1; } data[l++] = immediate; } else { return -1; } return l; } static int oploop(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; data[l++] = 0xe2; st8 delta = op->operands[0].immediate - a->pc - 2; data[l++] = (ut8)delta; return l; } static int opret(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int immediate = 0; if (a->bits == 16) { data[l++] = 0xc3; return l; } if (op->operands[0].type == OT_UNKNOWN) { data[l++] = 0xc3; } else if (op->operands[0].type & (OT_CONSTANT | OT_WORD)) { data[l++] = 0xc2; immediate = op->operands[0].immediate * op->operands[0].sign; data[l++] = immediate; data[l++] = immediate << 8; } return l; } static int opretf(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; st32 immediate = 0; if (op->operands[0].type & OT_CONSTANT) { immediate = op->operands[0].immediate * op->operands[0].sign; data[l++] = 0xca; data[l++] = immediate; data[l++] = immediate >> 8; } else if (op->operands[0].type == OT_UNKNOWN) { data[l++] = 0xcb; } return l; } static int opstos(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if (!strcmp(op->mnemonic, "stosw")) { data[l++] = 0x66; } if (!strcmp(op->mnemonic, "stosb")) { data[l++] = 0xaa; } else if (!strcmp(op->mnemonic, "stosw")) { data[l++] = 0xab; } else if (!strcmp(op->mnemonic, "stosd")) { data[l++] = 0xab; } return l; } static int opset(RAsm *a, ut8 *data, const Opcode *op) { if (!(op->operands[0].type & (OT_GPREG | OT_BYTE))) {return -1;} int l = 0; int mod = 0; int reg = op->operands[0].regs[0]; data[l++] = 0x0f; if (!strcmp (op->mnemonic, "seto")) { data[l++] = 0x90; } else if (!strcmp (op->mnemonic, "setno")) { data[l++] = 0x91; } else if (!strcmp (op->mnemonic, "setb") || !strcmp (op->mnemonic, "setnae") || !strcmp (op->mnemonic, "setc")) { data[l++] = 0x92; } else if (!strcmp (op->mnemonic, "setnb") || !strcmp (op->mnemonic, "setae") || !strcmp (op->mnemonic, "setnc")) { data[l++] = 0x93; } else if (!strcmp (op->mnemonic, "setz") || !strcmp (op->mnemonic, "sete")) { data[l++] = 0x94; } else if (!strcmp (op->mnemonic, "setnz") || !strcmp (op->mnemonic, "setne")) { data[l++] = 0x95; } else if (!strcmp (op->mnemonic, "setbe") || !strcmp (op->mnemonic, "setna")) { data[l++] = 0x96; } else if (!strcmp (op->mnemonic, "setnbe") || !strcmp (op->mnemonic, "seta")) { data[l++] = 0x97; } else if (!strcmp (op->mnemonic, "sets")) { data[l++] = 0x98; } else if (!strcmp (op->mnemonic, "setns")) { data[l++] = 0x99; } else if (!strcmp (op->mnemonic, "setp") || !strcmp (op->mnemonic, "setpe")) { data[l++] = 0x9a; } else if (!strcmp (op->mnemonic, "setnp") || !strcmp (op->mnemonic, "setpo")) { data[l++] = 0x9b; } else if (!strcmp (op->mnemonic, "setl") || !strcmp (op->mnemonic, "setnge")) { data[l++] = 0x9c; } else if (!strcmp (op->mnemonic, "setnl") || !strcmp (op->mnemonic, "setge")) { data[l++] = 0x9d; } else if (!strcmp (op->mnemonic, "setle") || !strcmp (op->mnemonic, "setng")) { data[l++] = 0x9e; } else if (!strcmp (op->mnemonic, "setnle") || !strcmp (op->mnemonic, "setg")) { data[l++] = 0x9f; } else { return -1; } if (!(op->operands[0].type & OT_MEMORY)) { mod = 3; reg = op->operands[0].reg; } data[l++] = mod << 6 | reg; return l; } static int optest(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if (!op->operands[0].type || !op->operands[1].type) { eprintf ("Error: Invalid operands\n"); return -1; } if (a->bits == 64) { if (op->operands[0].type & OT_MEMORY || op->operands[1].type & OT_MEMORY) { data[l++] = 0x67; } if (op->operands[0].type & OT_QWORD && op->operands[1].type & OT_QWORD) { if (op->operands[0].extended && op->operands[1].extended) { data[l++] = 0x4d; } else { data[l++] = 0x48; } } } if (op->operands[1].type & OT_CONSTANT) { if (op->operands[0].type & OT_BYTE) { data[l++] = 0xf6; data[l++] = op->operands[0].regs[0]; data[l++] = op->operands[1].immediate; return l; } data[l++] = 0xf7; if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x00 | op->operands[0].regs[0]; } else { data[l++] = 0xc0 | op->operands[0].reg; } data[l++] = op->operands[1].immediate >> 0; data[l++] = op->operands[1].immediate >> 8; data[l++] = op->operands[1].immediate >> 16; data[l++] = op->operands[1].immediate >> 24; return l; } if (op->operands[0].type & OT_BYTE || op->operands[1].type & OT_BYTE) { data[l++] = 0x84; } else { data[l++] = 0x85; } if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x00 | op->operands[1].reg << 3 | op->operands[0].regs[0]; } else { if (op->operands[1].type & OT_MEMORY) { data[l++] = 0x00 | op->operands[0].reg << 3 | op->operands[1].regs[0]; } else { data[l++] = 0xc0 | op->operands[1].reg << 3 | op->operands[0].reg; } } return l; } static int opxchg(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; int mod_byte = 0; int reg = 0; int rm = 0; st32 offset = 0; if (op->operands[0].type & OT_MEMORY || op->operands[1].type & OT_MEMORY) { data[l++] = 0x87; if (op->operands[0].type & OT_MEMORY) { rm = op->operands[0].regs[0]; offset = op->operands[0].offset * op->operands[0].offset_sign; reg = op->operands[1].reg; } else if (op->operands[1].type & OT_MEMORY) { rm = op->operands[1].regs[0]; offset = op->operands[1].offset * op->operands[1].offset_sign; reg = op->operands[0].reg; } if (offset) { mod_byte = 1; if (offset < ST8_MIN || offset > ST8_MAX) { mod_byte = 2; } } } else { if (op->operands[0].reg == X86R_EAX && op->operands[1].type & OT_GPREG) { data[l++] = 0x90 + op->operands[1].reg; return l; } else if (op->operands[1].reg == X86R_EAX && op->operands[0].type & OT_GPREG) { data[l++] = 0x90 + op->operands[0].reg; return l; } else if (op->operands[0].type & OT_GPREG && op->operands[1].type & OT_GPREG) { mod_byte = 3; data[l++] = 0x87; reg = op->operands[1].reg; rm = op->operands[0].reg; } } data[l++] = mod_byte << 6 | reg << 3 | rm; if (mod_byte > 0 && mod_byte < 3) { data[l++] = offset; if (mod_byte == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } return l; } static int opcdqe(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if (a->bits == 64) { data[l++] = 0x48; } data[l++] = 0x98; return l; } static int opfcmov(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; char* fcmov = op->mnemonic + strlen("fcmov"); switch (op->operands_count) { case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 && op->operands[1].type & OT_FPUREG & ~OT_REGALL ) { if ( !strcmp( fcmov, "b" ) ) { data[l++] = 0xda; data[l++] = 0xc0 | op->operands[1].reg; } else if ( !strcmp( fcmov, "e" ) ) { data[l++] = 0xda; data[l++] = 0xc8 | op->operands[1].reg; } else if ( !strcmp( fcmov, "be" ) ) { data[l++] = 0xda; data[l++] = 0xd0 | op->operands[1].reg; } else if ( !strcmp( fcmov, "u" ) ) { data[l++] = 0xda; data[l++] = 0xd8 | op->operands[1].reg; } else if ( !strcmp( fcmov, "nb" ) ) { data[l++] = 0xdb; data[l++] = 0xc0 | op->operands[1].reg; } else if ( !strcmp( fcmov, "ne" ) ) { data[l++] = 0xdb; data[l++] = 0xc8 | op->operands[1].reg; } else if ( !strcmp( fcmov, "nbe" ) ) { data[l++] = 0xdb; data[l++] = 0xd0 | op->operands[1].reg; } else if ( !strcmp( fcmov, "nu" ) ) { data[l++] = 0xdb; data[l++] = 0xd8 | op->operands[1].reg; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opffree(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if (op->operands[0].type & OT_FPUREG & ~OT_REGALL) { data[l++] = 0xdd; data[l++] = 0xc0 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfrstor(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if (op->operands[0].type & OT_MEMORY) { data[l++] = 0xdd; data[l++] = 0x20 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfxch(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 0: data[l++] = 0xd9; data[l++] = 0xc9; break; case 1: if (op->operands[0].type & OT_FPUREG & ~OT_REGALL) { data[l++] = 0xd9; data[l++] = 0xc8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfucom(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xdd; data[l++] = 0xe0 | op->operands[0].reg; } else { return -1; } break; case 0: data[l++] = 0xdd; data[l++] = 0xe1; break; default: return -1; } return l; } static int opfucomp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xdd; data[l++] = 0xe8 | op->operands[0].reg; } else { return -1; } break; case 0: data[l++] = 0xdd; data[l++] = 0xe9; break; default: return -1; } return l; } static int opfaddp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xde; data[l++] = 0xc0 | op->operands[0].reg; } else { return -1; } break; case 0: data[l++] = 0xde; data[l++] = 0xc1; break; default: return -1; } return l; } static int opfiadd(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x00 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x00 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfadd(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdc; data[l++] = 0x00 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xd8; data[l++] = 0x00 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 && op->operands[1].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xd8; data[l++] = 0xc0 | op->operands[1].reg; } else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xdc; data[l++] = 0xc0 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opficom(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x10 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x10 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opficomp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x18 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x18 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfild(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xdf; data[l++] = 0x00 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xdb; data[l++] = 0x00 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdf; data[l++] = 0x28 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfldcw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_WORD ) { data[l++] = 0xd9; data[l++] = 0x28 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfldenv(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0xd9; data[l++] = 0x20 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfbld(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_TBYTE ) { data[l++] = 0xdf; data[l++] = 0x20 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfbstp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_TBYTE ) { data[l++] = 0xdf; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfxrstor(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x0f; data[l++] = 0xae; data[l++] = 0x08 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfxsave(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x0f; data[l++] = 0xae; data[l++] = 0x00 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfist(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xdf; data[l++] = 0x10 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xdb; data[l++] = 0x10 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfistp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xdf; data[l++] = 0x18 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xdb; data[l++] = 0x18 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdf; data[l++] = 0x38 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfisttp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xdf; data[l++] = 0x08 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xdb; data[l++] = 0x08 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdd; data[l++] = 0x08 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfstenv(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x9b; data[l++] = 0xd9; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfnstenv(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0xd9; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfdiv(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xd8; data[l++] = 0x30 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdc; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 && op->operands[1].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xd8; data[l++] = 0xf0 | op->operands[1].reg; } else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xdc; data[l++] = 0xf8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfdivp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 0: data[l++] = 0xde; data[l++] = 0xf9; break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xde; data[l++] = 0xf8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfidiv(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x30 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfdivr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xd8; data[l++] = 0x38 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdc; data[l++] = 0x38 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 && op->operands[1].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xd8; data[l++] = 0xf8 | op->operands[1].reg; } else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xdc; data[l++] = 0xf0 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfdivrp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 0: data[l++] = 0xde; data[l++] = 0xf1; break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xde; data[l++] = 0xf0 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfidivr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x38 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x38 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfmul(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xd8; data[l++] = 0x08 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdc; data[l++] = 0x08 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 && op->operands[1].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xd8; data[l++] = 0xc8 | op->operands[1].reg; } else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xdc; data[l++] = 0xc8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfmulp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 0: data[l++] = 0xde; data[l++] = 0xc9; break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xde; data[l++] = 0xc8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfimul(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x08 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x08 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfsub(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xd8; data[l++] = 0x20 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdc; data[l++] = 0x20 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 && op->operands[1].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xd8; data[l++] = 0xe0 | op->operands[1].reg; } else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xdc; data[l++] = 0xe8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfsubp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 0: data[l++] = 0xde; data[l++] = 0xe9; break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xde; data[l++] = 0xe8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfisub(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x20 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x20 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfsubr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xd8; data[l++] = 0x28 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0xdc; data[l++] = 0x28 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 && op->operands[1].type & OT_FPUREG & ~OT_REGALL ) { data[l++] = 0xd8; data[l++] = 0xe8 | op->operands[1].reg; } else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xdc; data[l++] = 0xe0 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfsubrp(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 0: data[l++] = 0xde; data[l++] = 0xe1; break; case 2: if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) { data[l++] = 0xde; data[l++] = 0xe0 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opfisubr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { if ( op->operands[0].type & OT_DWORD ) { data[l++] = 0xda; data[l++] = 0x28 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_WORD ) { data[l++] = 0xde; data[l++] = 0x28 | op->operands[0].regs[0]; } else { return -1; } } else { return -1; } break; default: return -1; } return l; } static int opfnstcw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_WORD ) { data[l++] = 0xd9; data[l++] = 0x38 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfstcw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_WORD ) { data[l++] = 0x9b; data[l++] = 0xd9; data[l++] = 0x38 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfnstsw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_WORD ) { data[l++] = 0xdd; data[l++] = 0x38 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD && op->operands[0].reg == X86R_AX ) { data[l++] = 0xdf; data[l++] = 0xe0; } else { return -1; } break; default: return -1; } return l; } static int opfstsw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_WORD ) { data[l++] = 0x9b; data[l++] = 0xdd; data[l++] = 0x38 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_GPREG && op->operands[0].type & OT_WORD && op->operands[0].reg == X86R_AX ) { data[l++] = 0x9b; data[l++] = 0xdf; data[l++] = 0xe0; } else { return -1; } break; default: return -1; } return l; } static int opfnsave(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_DWORD ) { data[l++] = 0xdd; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opfsave(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_DWORD ) { data[l++] = 0x9b; data[l++] = 0xdd; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int oplldt(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x0f; data[l++] = 0x00; if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x10 | op->operands[0].regs[0]; } else { data[l++] = 0xd0 | op->operands[0].reg; } } else { return -1; } break; default: return -1; } return l; } static int oplmsw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x0f; data[l++] = 0x01; if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x30 | op->operands[0].regs[0]; } else { data[l++] = 0xf0 | op->operands[0].reg; } } else { return -1; } break; default: return -1; } return l; } static int oplgdt(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x0f; data[l++] = 0x01; data[l++] = 0x10 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int oplidt(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x0f; data[l++] = 0x01; data[l++] = 0x18 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opsgdt(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x0f; data[l++] = 0x01; data[l++] = 0x00 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opstmxcsr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_DWORD ) { data[l++] = 0x0f; data[l++] = 0xae; data[l++] = 0x18 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opstr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_WORD ) { data[l++] = 0x0f; data[l++] = 0x00; data[l++] = 0x08 | op->operands[0].regs[0]; } else if ( op->operands[0].type & OT_GPREG && op->operands[0].type & OT_DWORD ) { data[l++] = 0x0f; data[l++] = 0x00; data[l++] = 0xc8 | op->operands[0].reg; } else { return -1; } break; default: return -1; } return l; } static int opsidt(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x0f; data[l++] = 0x01; data[l++] = 0x08 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opsldt(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( a->bits == 64 ) { data[l++] = 0x48; } data[l++] = 0x0f; data[l++] = 0x00; if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x00 | op->operands[0].regs[0]; } else { data[l++] = 0xc0 | op->operands[0].reg; } break; default: return -1; } return l; } static int opsmsw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( a->bits == 64 ) { data[l++] = 0x48; } data[l++] = 0x0f; data[l++] = 0x01; if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x20 | op->operands[0].regs[0]; } else { data[l++] = 0xe0 | op->operands[0].reg; } break; default: return -1; } return l; } static int opverr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x0f; data[l++] = 0x00; if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x20 | op->operands[0].regs[0]; } else { data[l++] = 0xe0 | op->operands[0].reg; } } else { return -1; } break; default: return -1; } return l; } static int opverw(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x0f; data[l++] = 0x00; if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x28 | op->operands[0].regs[0]; } else { data[l++] = 0xe8 | op->operands[0].reg; } } else { return -1; } break; default: return -1; } return l; } static int opvmclear(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_QWORD ) { data[l++] = 0x66; data[l++] = 0x0f; data[l++] = 0xc7; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opvmon(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_QWORD ) { data[l++] = 0xf3; data[l++] = 0x0f; data[l++] = 0xc7; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opvmptrld(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_QWORD ) { data[l++] = 0x0f; data[l++] = 0xc7; data[l++] = 0x30 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } static int opvmptrst(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_MEMORY && op->operands[0].type & OT_QWORD ) { data[l++] = 0x0f; data[l++] = 0xc7; data[l++] = 0x38 | op->operands[0].regs[0]; } else { return -1; } break; default: return -1; } return l; } typedef struct lookup_t { char mnemonic[12]; int only_x32; int (*opdo)(RAsm*, ut8*, const Opcode*); ut64 opcode; int size; } LookupTable; LookupTable oplookup[] = { {"aaa", 0, NULL, 0x37, 1}, {"aad", 0, NULL, 0xd50a, 2}, {"aam", 0, opaam, 0}, {"aas", 0, NULL, 0x3f, 1}, {"adc", 0, &opadc, 0}, {"add", 0, &opadd, 0}, {"adx", 0, NULL, 0xd4, 1}, {"amx", 0, NULL, 0xd5, 1}, {"and", 0, &opand, 0}, {"bswap", 0, &opbswap, 0}, {"call", 0, &opcall, 0}, {"cbw", 0, NULL, 0x6698, 2}, {"cdq", 0, NULL, 0x99, 1}, {"cdqe", 0, &opcdqe, 0}, {"cwde", 0, &opcdqe, 0}, {"clc", 0, NULL, 0xf8, 1}, {"cld", 0, NULL, 0xfc, 1}, {"clflush", 0, &opclflush, 0}, {"clgi", 0, NULL, 0x0f01dd, 3}, {"cli", 0, NULL, 0xfa, 1}, {"clts", 0, NULL, 0x0f06, 2}, {"cmc", 0, NULL, 0xf5, 1}, {"cmovo", 0, &opcmov, 0}, {"cmovno", 0, &opcmov, 0}, {"cmovb", 0, &opcmov, 0}, {"cmovc", 0, &opcmov, 0}, {"cmovnae", 0, &opcmov, 0}, {"cmovae", 0, &opcmov, 0}, {"cmovnb", 0, &opcmov, 0}, {"cmovnc", 0, &opcmov, 0}, {"cmove", 0, &opcmov, 0}, {"cmovz", 0, &opcmov, 0}, {"cmovne", 0, &opcmov, 0}, {"cmovnz", 0, &opcmov, 0}, {"cmovbe", 0, &opcmov, 0}, {"cmovna", 0, &opcmov, 0}, {"cmova", 0, &opcmov, 0}, {"cmovnbe", 0, &opcmov, 0}, {"cmovne", 0, &opcmov, 0}, {"cmovnz", 0, &opcmov, 0}, {"cmovs", 0, &opcmov, 0}, {"cmovns", 0, &opcmov, 0}, {"cmovp", 0, &opcmov, 0}, {"cmovpe", 0, &opcmov, 0}, {"cmovnp", 0, &opcmov, 0}, {"cmovpo", 0, &opcmov, 0}, {"cmovl", 0, &opcmov, 0}, {"cmovnge", 0, &opcmov, 0}, {"cmovge", 0, &opcmov, 0}, {"cmovnl", 0, &opcmov, 0}, {"cmovle", 0, &opcmov, 0}, {"cmovng", 0, &opcmov, 0}, {"cmovg", 0, &opcmov, 0}, {"cmovnle", 0, &opcmov, 0}, {"cmp", 0, &opcmp, 0}, {"cmpsb", 0, NULL, 0xa6, 1}, {"cmpsd", 0, NULL, 0xa7, 1}, {"cmpsw", 0, NULL, 0x66a7, 2}, {"cpuid", 0, NULL, 0x0fa2, 2}, {"cwd", 0, NULL, 0x6699, 2}, {"cwde", 0, NULL, 0x98, 1}, {"daa", 0, NULL, 0x27, 1}, {"das", 0, NULL, 0x2f, 1}, {"dec", 0, &opdec, 0}, {"div", 0, &opdiv, 0}, {"emms", 0, NULL, 0x0f77, 2}, {"f2xm1", 0, NULL, 0xd9f0, 2}, {"fabs", 0, NULL, 0xd9e1, 2}, {"fadd", 0, &opfadd, 0}, {"faddp", 0, &opfaddp, 0}, {"fbld", 0, &opfbld, 0}, {"fbstp", 0, &opfbstp, 0}, {"fchs", 0, NULL, 0xd9e0, 2}, {"fclex", 0, NULL, 0x9bdbe2, 3}, {"fcmovb", 0, &opfcmov, 0}, {"fcmove", 0, &opfcmov, 0}, {"fcmovbe", 0, &opfcmov, 0}, {"fcmovu", 0, &opfcmov, 0}, {"fcmovnb", 0, &opfcmov, 0}, {"fcmovne", 0, &opfcmov, 0}, {"fcmovnbe", 0, &opfcmov, 0}, {"fcmovnu", 0, &opfcmov, 0}, {"fcos", 0, NULL, 0xd9ff, 2}, {"fdecstp", 0, NULL, 0xd9f6, 2}, {"fdiv", 0, &opfdiv, 0}, {"fdivp", 0, &opfdivp, 0}, {"fdivr", 0, &opfdivr, 0}, {"fdivrp", 0, &opfdivrp, 0}, {"femms", 0, NULL, 0x0f0e, 2}, {"ffree", 0, &opffree, 0}, {"fiadd", 0, &opfiadd, 0}, {"ficom", 0, &opficom, 0}, {"ficomp", 0, &opficomp, 0}, {"fidiv", 0, &opfidiv, 0}, {"fidivr", 0, &opfidivr, 0}, {"fild", 0, &opfild, 0}, {"fimul", 0, &opfimul, 0}, {"fincstp", 0, NULL, 0xd9f7, 2}, {"finit", 0, NULL, 0x9bdbe3, 3}, {"fist", 0, &opfist, 0}, {"fistp", 0, &opfistp, 0}, {"fisttp", 0, &opfisttp, 0}, {"fisub", 0, &opfisub, 0}, {"fisubr", 0, &opfisubr, 0}, {"fld1", 0, NULL, 0xd9e8, 2}, {"fldcw", 0, &opfldcw, 0}, {"fldenv", 0, &opfldenv, 0}, {"fldl2t", 0, NULL, 0xd9e9, 2}, {"fldl2e", 0, NULL, 0xd9ea, 2}, {"fldlg2", 0, NULL, 0xd9ec, 2}, {"fldln2", 0, NULL, 0xd9ed, 2}, {"fldpi", 0, NULL, 0xd9eb, 2}, {"fldz", 0, NULL, 0xd9ee, 2}, {"fmul", 0, &opfmul, 0}, {"fmulp", 0, &opfmulp, 0}, {"fnclex", 0, NULL, 0xdbe2, 2}, {"fninit", 0, NULL, 0xdbe3, 2}, {"fnop", 0, NULL, 0xd9d0, 2}, {"fnsave", 0, &opfnsave, 0}, {"fnstcw", 0, &opfnstcw, 0}, {"fnstenv", 0, &opfnstenv, 0}, {"fnstsw", 0, &opfnstsw, 0}, {"fpatan", 0, NULL, 0xd9f3, 2}, {"fprem", 0, NULL, 0xd9f8, 2}, {"fprem1", 0, NULL, 0xd9f5, 2}, {"fptan", 0, NULL, 0xd9f2, 2}, {"frndint", 0, NULL, 0xd9fc, 2}, {"frstor", 0, &opfrstor, 0}, {"fsave", 0, &opfsave, 0}, {"fscale", 0, NULL, 0xd9fd, 2}, {"fsin", 0, NULL, 0xd9fe, 2}, {"fsincos", 0, NULL, 0xd9fb, 2}, {"fsqrt", 0, NULL, 0xd9fa, 2}, {"fstcw", 0, &opfstcw, 0}, {"fstenv", 0, &opfstenv, 0}, {"fstsw", 0, &opfstsw, 0}, {"fsub", 0, &opfsub, 0}, {"fsubp", 0, &opfsubp, 0}, {"fsubr", 0, &opfsubr, 0}, {"fsubrp", 0, &opfsubrp, 0}, {"ftst", 0, NULL, 0xd9e4, 2}, {"fucom", 0, &opfucom, 0}, {"fucomp", 0, &opfucomp, 0}, {"fucompp", 0, NULL, 0xdae9, 2}, {"fwait", 0, NULL, 0x9b, 1}, {"fxam", 0, NULL, 0xd9e5, 2}, {"fxch", 0, &opfxch, 0}, {"fxrstor", 0, &opfxrstor, 0}, {"fxsave", 0, &opfxsave, 0}, {"fxtract", 0, NULL, 0xd9f4, 2}, {"fyl2x", 0, NULL, 0xd9f1, 2}, {"fyl2xp1", 0, NULL, 0xd9f9, 2}, {"getsec", 0, NULL, 0x0f37, 2}, {"hlt", 0, NULL, 0xf4, 1}, {"idiv", 0, &opidiv, 0}, {"imul", 0, &opimul, 0}, {"in", 0, &opin, 0}, {"inc", 0, &opinc, 0}, {"ins", 0, NULL, 0x6d, 1}, {"insb", 0, NULL, 0x6c, 1}, {"insd", 0, NULL, 0x6d, 1}, {"insw", 0, NULL, 0x666d, 2}, {"int", 0, &opint, 0}, {"int1", 0, NULL, 0xf1, 1}, {"int3", 0, NULL, 0xcc, 1}, {"into", 0, NULL, 0xce, 1}, {"invd", 0, NULL, 0x0f08, 2}, {"iret", 0, NULL, 0x66cf, 2}, {"iretd", 0, NULL, 0xcf, 1}, {"ja", 0, &opjc, 0}, {"jae", 0, &opjc, 0}, {"jb", 0, &opjc, 0}, {"jbe", 0, &opjc, 0}, {"jc", 0, &opjc, 0}, {"je", 0, &opjc, 0}, {"jg", 0, &opjc, 0}, {"jge", 0, &opjc, 0}, {"jl", 0, &opjc, 0}, {"jle", 0, &opjc, 0}, {"jmp", 0, &opjc, 0}, {"jna", 0, &opjc, 0}, {"jnae", 0, &opjc, 0}, {"jnb", 0, &opjc, 0}, {"jnbe", 0, &opjc, 0}, {"jnc", 0, &opjc, 0}, {"jne", 0, &opjc, 0}, {"jng", 0, &opjc, 0}, {"jnge", 0, &opjc, 0}, {"jnl", 0, &opjc, 0}, {"jnle", 0, &opjc, 0}, {"jno", 0, &opjc, 0}, {"jnp", 0, &opjc, 0}, {"jns", 0, &opjc, 0}, {"jnz", 0, &opjc, 0}, {"jo", 0, &opjc, 0}, {"jp", 0, &opjc, 0}, {"jpe", 0, &opjc, 0}, {"jpo", 0, &opjc, 0}, {"js", 0, &opjc, 0}, {"jz", 0, &opjc, 0}, {"lahf", 0, NULL, 0x9f}, {"lea", 0, &oplea, 0}, {"leave", 0, NULL, 0xc9, 1}, {"les", 0, &oples, 0}, {"lfence", 0, NULL, 0x0faee8, 3}, {"lgdt", 0, &oplgdt, 0}, {"lidt", 0, &oplidt, 0}, {"lldt", 0, &oplldt, 0}, {"lmsw", 0, &oplmsw, 0}, {"lodsb", 0, NULL, 0xac, 1}, {"lodsd", 0, NULL, 0xad, 1}, {"lodsw", 0, NULL, 0x66ad, 2}, {"loop", 0, &oploop, 0}, {"mfence", 0, NULL, 0x0faef0, 3}, {"monitor", 0, NULL, 0x0f01c8, 3}, {"mov", 0, &opmov, 0}, {"movsb", 0, NULL, 0xa4, 1}, {"movsd", 0, NULL, 0xa5, 1}, {"movsw", 0, NULL, 0x66a5, 2}, {"movzx", 0, &opmovx, 0}, {"movsx", 0, &opmovx, 0}, {"mul", 0, &opmul, 0}, {"mwait", 0, NULL, 0x0f01c9, 3}, {"nop", 0, NULL, 0x90, 1}, {"not", 0, &opnot, 0}, {"or", 0, &opor, 0}, {"out", 0, &opout, 0}, {"outsb", 0, NULL, 0x6e, 1}, {"outs", 0, NULL, 0x6f, 1}, {"outsd", 0, NULL, 0x6f, 1}, {"outsw", 0, NULL, 0x666f, 2}, {"pop", 0, &oppop, 0}, {"popa", 1, NULL, 0x61, 1}, {"popad", 1, NULL, 0x61, 1}, {"popal", 1, NULL, 0x61, 1}, {"popaw", 1, NULL, 0x6661, 2}, {"popfd", 1, NULL, 0x9d, 1}, {"prefetch", 0, NULL, 0x0f0d, 2}, {"push", 0, &oppush, 0}, {"pusha", 1, NULL, 0x60, 1}, {"pushad", 1, NULL, 0x60, 1}, {"pushal", 1, NULL, 0x60, 1}, {"pushfd", 0, NULL, 0x9c, 1}, {"rcl", 0, &process_group_2, 0}, {"rcr", 0, &process_group_2, 0}, {"rep", 0, &oprep, 0}, {"repe", 0, &oprep, 0}, {"repne", 0, &oprep, 0}, {"repz", 0, &oprep, 0}, {"repnz", 0, &oprep, 0}, {"rdmsr", 0, NULL, 0x0f32, 2}, {"rdpmc", 0, NULL, 0x0f33, 2}, {"rdtsc", 0, NULL, 0x0f31, 2}, {"rdtscp", 0, NULL, 0x0f01f9, 3}, {"ret", 0, &opret, 0}, {"retf", 0, &opretf, 0}, {"retw", 0, NULL, 0x66c3, 2}, {"rol", 0, &process_group_2, 0}, {"ror", 0, &process_group_2, 0}, {"rsm", 0, NULL, 0x0faa, 2}, {"sahf", 0, NULL, 0x9e, 1}, {"sal", 0, &process_group_2, 0}, {"salc", 0, NULL, 0xd6, 1}, {"sar", 0, &process_group_2, 0}, {"sbb", 0, &opsbb, 0}, {"scasb", 0, NULL, 0xae, 1}, {"scasd", 0, NULL, 0xaf, 1}, {"scasw", 0, NULL, 0x66af, 2}, {"seto", 0, &opset, 0}, {"setno", 0, &opset, 0}, {"setb", 0, &opset, 0}, {"setnae", 0, &opset, 0}, {"setc", 0, &opset, 0}, {"setnb", 0, &opset, 0}, {"setae", 0, &opset, 0}, {"setnc", 0, &opset, 0}, {"setz", 0, &opset, 0}, {"sete", 0, &opset, 0}, {"setnz", 0, &opset, 0}, {"setne", 0, &opset, 0}, {"setbe", 0, &opset, 0}, {"setna", 0, &opset, 0}, {"setnbe", 0, &opset, 0}, {"seta", 0, &opset, 0}, {"sets", 0, &opset, 0}, {"setns", 0, &opset, 0}, {"setp", 0, &opset, 0}, {"setpe", 0, &opset, 0}, {"setnp", 0, &opset, 0}, {"setpo", 0, &opset, 0}, {"setl", 0, &opset, 0}, {"setnge", 0, &opset, 0}, {"setnl", 0, &opset, 0}, {"setge", 0, &opset, 0}, {"setle", 0, &opset, 0}, {"setng", 0, &opset, 0}, {"setnle", 0, &opset, 0}, {"setg", 0, &opset, 0}, {"sfence", 0, NULL, 0x0faef8, 3}, {"sgdt", 0, &opsgdt, 0}, {"shl", 0, &process_group_2, 0}, {"shr", 0, &process_group_2, 0}, {"sidt", 0, &opsidt, 0}, {"sldt", 0, &opsldt, 0}, {"smsw", 0, &opsmsw, 0}, {"stc", 0, NULL, 0xf9, 1}, {"std", 0, NULL, 0xfd, 1}, {"stgi", 0, NULL, 0x0f01dc, 3}, {"sti", 0, NULL, 0xfb, 1}, {"stmxcsr", 0, &opstmxcsr, 0}, {"stosb", 0, &opstos, 0}, {"stosd", 0, &opstos, 0}, {"stosw", 0, &opstos, 0}, {"str", 0, &opstr, 0}, {"sub", 0, &opsub, 0}, {"swapgs", 0, NULL, 0x0f1ff8, 3}, {"syscall", 0, NULL, 0x0f05, 2}, {"sysenter", 0, NULL, 0x0f34, 2}, {"sysexit", 0, NULL, 0x0f35, 2}, {"sysret", 0, NULL, 0x0f07, 2}, {"ud2", 0, NULL, 0x0f0b, 2}, {"verr", 0, &opverr, 0}, {"verw", 0, &opverw, 0}, {"vmcall", 0, NULL, 0x0f01c1, 3}, {"vmclear", 0, &opvmclear, 0}, {"vmlaunch", 0, NULL, 0x0f01c2, 3}, {"vmload", 0, NULL, 0x0f01da, 3}, {"vmmcall", 0, NULL, 0x0f01d9, 3}, {"vmptrld", 0, &opvmptrld, 0}, {"vmptrst", 0, &opvmptrst, 0}, {"vmresume", 0, NULL, 0x0f01c3, 3}, {"vmrun", 0, NULL, 0x0f01d8, 3}, {"vmsave", 0, NULL, 0x0f01db, 3}, {"vmxoff", 0, NULL, 0x0f01c4, 3}, {"vmxon", 0, &opvmon, 0}, {"vzeroall", 0, NULL, 0xc5fc77, 3}, {"vzeroupper", 0, NULL, 0xc5f877, 3}, {"wait", 0, NULL, 0x9b, 1}, {"wbinvd", 0, NULL, 0x0f09, 2}, {"wrmsr", 0, NULL, 0x0f30, 2}, {"xadd", 0, &opxadd, 0}, {"xchg", 0, &opxchg, 0}, {"xgetbv", 0, NULL, 0x0f01d0, 3}, {"xlatb", 0, NULL, 0xd7, 1}, {"xor", 0, &opxor, 0}, {"xsetbv", 0, NULL, 0x0f01d1, 3}, {"test", 0, &optest, 0}, {"null", 0, NULL, 0, 0} }; static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { if (*begin > strlen (str)) { return TT_EOF; } // Skip whitespace while (begin && str[*begin] && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && str[*end] && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } } /** * Get the register at position pos in str. Increase pos afterwards. */ static Register parseReg(RAsm *a, const char *str, size_t *pos, ut32 *type) { int i; // Must be the same order as in enum register_t const char *regs[] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", NULL }; const char *regsext[] = { "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d", NULL }; const char *regs8[] = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", NULL }; const char *regs16[] = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", NULL }; const char *regs64[] = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "rip", NULL}; const char *regs64ext[] = { "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", NULL }; const char *sregs[] = { "es", "cs", "ss", "ds", "fs", "gs", NULL}; // Get token (especially the length) size_t nextpos, length; const char *token; getToken (str, pos, &nextpos); token = str + *pos; length = nextpos - *pos; *pos = nextpos; // General purpose registers if (length == 3 && token[0] == 'e') { for (i = 0; regs[i]; i++) { if (!r_str_ncasecmp (regs[i], token, length)) { *type = (OT_GPREG & OT_REG (i)) | OT_DWORD; return i; } } } if (length == 2 && (token[1] == 'l' || token[1] == 'h')) { for (i = 0; regs8[i]; i++) { if (!r_str_ncasecmp (regs8[i], token, length)) { *type = (OT_GPREG & OT_REG (i)) | OT_BYTE; return i; } } } if (length == 2) { for (i = 0; regs16[i]; i++) { if (!r_str_ncasecmp (regs16[i], token, length)) { *type = (OT_GPREG & OT_REG (i)) | OT_WORD; return i; } } // This isn't working properly yet for (i = 0; sregs[i]; i++) { if (!r_str_ncasecmp (sregs[i], token, length)) { *type = (OT_SEGMENTREG & OT_REG (i)) | OT_WORD; return i; } } } if (token[0] == 'r') { for (i = 0; regs64[i]; i++) { if (!r_str_ncasecmp (regs64[i], token, length)) { *type = (OT_GPREG & OT_REG (i)) | OT_QWORD; a->bits = 64; return i; } } for (i = 0; regs64ext[i]; i++) { if (!r_str_ncasecmp (regs64ext[i], token, length)) { *type = (OT_GPREG & OT_REG (i)) | OT_QWORD; a->bits = 64; return i + 9; } } for (i = 0; regsext[i]; i++) { if (!r_str_ncasecmp (regsext[i], token, length)) { *type = (OT_GPREG & OT_REG (i)) | OT_DWORD; if (a->bits < 32) { a->bits = 32; } return i + 9; } } } // Extended registers if (!r_str_ncasecmp ("st", token, 2)) { *type = (OT_FPUREG & ~OT_REGALL); *pos = 3; } if (!r_str_ncasecmp ("mm", token, 2)) { *type = (OT_MMXREG & ~OT_REGALL); *pos = 3; } if (!r_str_ncasecmp ("xmm", token, 3)) { *type = (OT_XMMREG & ~OT_REGALL); *pos = 4; } // Now read number, possibly with parantheses if (*type & (OT_FPUREG | OT_MMXREG | OT_XMMREG) & ~OT_REGALL) { Register reg = X86R_UNDEFINED; // pass by '(',if there is one if (getToken (str, pos, &nextpos) == TT_SPECIAL && str[*pos] == '(') { *pos = nextpos; } // read number // const int maxreg = (a->bits == 64) ? 15 : 7; if (getToken (str, pos, &nextpos) != TT_NUMBER || (reg = getnum (a, str + *pos)) > 7) { if ((int)reg > 15) { eprintf ("Too large register index!\n"); return X86R_UNDEFINED; } else { reg -= 8; } } *pos = nextpos; // pass by ')' if (getToken (str, pos, &nextpos) == TT_SPECIAL && str[*pos] == ')') { *pos = nextpos; } // Safety to prevent a shift bigger than 31. Reg // should never be > 8 anyway if (reg > 7) { eprintf ("Too large register index!\n"); return X86R_UNDEFINED; } *type |= (OT_REG (reg) & ~OT_REGTYPE); return reg; } return X86R_UNDEFINED; } static void parse_segment_offset(RAsm *a, const char *str, size_t *pos, Operand *op, int reg_index) { int nextpos = *pos; char *c = strchr (str + nextpos, ':'); if (c) { nextpos ++; // Skip the ':' c = strchr (str + nextpos, '['); if (c) {nextpos ++;} // Skip the '[' // Assign registers to match behaviour of OT_MEMORY type op->regs[reg_index] = op->reg; op->type |= OT_MEMORY; op->offset_sign = 1; char *p = strchr (str + nextpos, '-'); if (p) { op->offset_sign = -1; nextpos ++; } op->scale[reg_index] = getnum (a, str + nextpos); op->offset = op->scale[reg_index]; } } // Parse operand static int parseOperand(RAsm *a, const char *str, Operand *op, bool isrepop) { size_t pos, nextpos = 0; x86newTokenType last_type; int size_token = 1; bool explicit_size = false; int reg_index = 0; // Reset type op->type = 0; // Consume tokens denoting the operand size while (size_token) { pos = nextpos; last_type = getToken (str, &pos, &nextpos); // Token may indicate size: then skip if (!r_str_ncasecmp (str + pos, "ptr", 3)) { continue; } else if (!r_str_ncasecmp (str + pos, "byte", 4)) { op->type |= OT_MEMORY | OT_BYTE; op->dest_size = OT_BYTE; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "word", 4)) { op->type |= OT_MEMORY | OT_WORD; op->dest_size = OT_WORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "dword", 5)) { op->type |= OT_MEMORY | OT_DWORD; op->dest_size = OT_DWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "qword", 5)) { op->type |= OT_MEMORY | OT_QWORD; op->dest_size = OT_QWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "oword", 5)) { op->type |= OT_MEMORY | OT_OWORD; op->dest_size = OT_OWORD; explicit_size = true; } else if (!r_str_ncasecmp (str + pos, "tbyte", 5)) { op->type |= OT_MEMORY | OT_TBYTE; op->dest_size = OT_TBYTE; explicit_size = true; } else { // the current token doesn't denote a size size_token = 0; } } // Next token: register, immediate, or '[' if (str[pos] == '[') { // Don't care about size, if none is given. if (!op->type) { op->type = OT_MEMORY; } // At the moment, we only accept plain linear combinations: // part := address | [factor *] register // address := part {+ part}* op->offset = op->scale[0] = op->scale[1] = 0; ut64 temp = 1; Register reg = X86R_UNDEFINED; bool first_reg = true; while (str[pos] != ']') { if (pos > nextpos) { // eprintf ("Error parsing instruction\n"); break; } pos = nextpos; if (!str[pos]) { break; } last_type = getToken (str, &pos, &nextpos); if (last_type == TT_SPECIAL) { if (str[pos] == '+' || str[pos] == '-' || str[pos] == ']') { if (reg != X86R_UNDEFINED) { op->regs[reg_index] = reg; op->scale[reg_index] = temp; ++reg_index; } else { op->offset += temp; op->regs[reg_index] = X86R_UNDEFINED; } temp = 1; reg = X86R_UNDEFINED; } else if (str[pos] == '*') { // go to ], + or - to get scale // Something to do here? // Seems we are just ignoring '*' or assuming it implicitly. } } else if (last_type == TT_WORD) { ut32 reg_type = 0; // We can't multiply registers if (reg != X86R_UNDEFINED) { op->type = 0; // Make the result invalid } // Reset nextpos: parseReg wants to parse from the beginning nextpos = pos; reg = parseReg (a, str, &nextpos, &reg_type); if (first_reg) { op->extended = false; if (reg > 8) { op->extended = true; op->reg = reg - 9; } first_reg = false; } else if (reg > 8) { op->reg = reg - 9; } if (reg_type & OT_REGTYPE & OT_SEGMENTREG) { op->reg = reg; op->type = reg_type; parse_segment_offset (a, str, &nextpos, op, reg_index); return nextpos; } // Still going to need to know the size if not specified if (!explicit_size) { op->type |= reg_type; } op->reg_size = reg_type; op->explicit_size = explicit_size; // Addressing only via general purpose registers if (!(reg_type & OT_GPREG)) { op->type = 0; // Make the result invalid } } else { char *p = strchr (str, '+'); op->offset_sign = 1; if (!p) { p = strchr (str, '-'); if (p) { op->offset_sign = -1; } } //with SIB notation, we need to consider the right sign char * plus = strchr (str, '+'); char * minus = strchr (str, '-'); char * closeB = strchr (str, ']'); if (plus && minus && plus < closeB && minus < closeB) { op->offset_sign = -1; } // If there's a scale, we don't want to parse out the // scale with the offset (scale + offset) otherwise the scale // will be the sum of the two. This splits the numbers char *tmp; tmp = malloc (strlen (str + pos) + 1); strcpy (tmp, str + pos); strtok (tmp, "+-"); st64 read = getnum (a, tmp); free (tmp); temp *= read; } } } else if (last_type == TT_WORD) { // register nextpos = pos; RFlagItem *flag; if (isrepop) { op->is_good_flag = false; strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1); op->rep_op[MAX_REPOP_LENGTH - 1] = '\0'; return nextpos; } op->reg = parseReg (a, str, &nextpos, &op->type); op->extended = false; if (op->reg > 8) { op->extended = true; op->reg -= 9; } if (op->type & OT_REGTYPE & OT_SEGMENTREG) { parse_segment_offset (a, str, &nextpos, op, reg_index); return nextpos; } if (op->reg == X86R_UNDEFINED) { op->is_good_flag = false; if (a->num && a->num->value == 0) { return nextpos; } op->type = OT_CONSTANT; RCore *core = a->num? (RCore *)(a->num->userptr): NULL; if (core && (flag = r_flag_get (core->flags, str))) { op->is_good_flag = true; } char *p = strchr (str, '-'); if (p) { op->sign = -1; str = ++p; } op->immediate = getnum (a, str); } else if (op->reg < X86R_UNDEFINED) { strncpy (op->rep_op, str, MAX_REPOP_LENGTH - 1); op->rep_op[MAX_REPOP_LENGTH - 1] = '\0'; } } else { // immediate // We don't know the size, so let's just set no size flag. op->type = OT_CONSTANT; op->sign = 1; char *p = strchr (str, '-'); if (p) { op->sign = -1; str = ++p; } op->immediate = getnum (a, str); } return nextpos; } static int parseOpcode(RAsm *a, const char *op, Opcode *out) { out->has_bnd = false; bool isrepop = false; if (!strncmp (op, "bnd ", 4)) { out->has_bnd = true; op += 4; } char *args = strchr (op, ' '); out->mnemonic = args ? r_str_ndup (op, args - op) : strdup (op); out->operands[0].type = out->operands[1].type = 0; out->operands[0].extended = out->operands[1].extended = false; out->operands[0].reg = out->operands[0].regs[0] = out->operands[0].regs[1] = X86R_UNDEFINED; out->operands[1].reg = out->operands[1].regs[0] = out->operands[1].regs[1] = X86R_UNDEFINED; out->operands[0].immediate = out->operands[1].immediate = 0; out->operands[0].sign = out->operands[1].sign = 1; out->operands[0].is_good_flag = out->operands[1].is_good_flag = true; out->is_short = false; out->operands_count = 0; if (args) { args++; } else { return 1; } if (!r_str_ncasecmp (args, "short", 5)) { out->is_short = true; args += 5; } if (!strncmp (out->mnemonic, "rep", 3)) { isrepop = true; } parseOperand (a, args, &(out->operands[0]), isrepop); out->operands_count = 1; while (out->operands_count < MAX_OPERANDS) { args = strchr (args, ','); if (!args) { break; } args++; parseOperand (a, args, &(out->operands[out->operands_count]), isrepop); out->operands_count++; } return 0; } static ut64 getnum(RAsm *a, const char *s) { if (!s) { return 0; } if (*s == '$') { s++; } return r_num_math (a->num, s); } static int oprep(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; LookupTable *lt_ptr; int retval; if (!strcmp (op->mnemonic, "rep") || !strcmp (op->mnemonic, "repe") || !strcmp (op->mnemonic, "repz")) { data[l++] = 0xf3; } else if (!strcmp (op->mnemonic, "repne") || !strcmp (op->mnemonic, "repnz")) { data[l++] = 0xf2; } Opcode instr = {0}; parseOpcode (a, op->operands[0].rep_op, &instr); for (lt_ptr = oplookup; strcmp (lt_ptr->mnemonic, "null"); lt_ptr++) { if (!r_str_casecmp (instr.mnemonic, lt_ptr->mnemonic)) { if (lt_ptr->opcode > 0) { if (lt_ptr->only_x32 && a->bits == 64) { return -1; } ut8 *ptr = (ut8 *)&lt_ptr->opcode; int i = 0; for (; i < lt_ptr->size; i++) { data[i + l] = ptr[lt_ptr->size - (i + 1)]; } free (instr.mnemonic); return l + lt_ptr->size; } else { if (lt_ptr->opdo) { data += l; if (instr.has_bnd) { data[l] = 0xf2; data++; } retval = lt_ptr->opdo (a, data, &instr); // if op supports bnd then the first byte will // be 0xf2. if (instr.has_bnd) { retval++; } return l + retval; } break; } } } free (instr.mnemonic); return -1; } static int assemble(RAsm *a, RAsmOp *ao, const char *str) { ut8 __data[32] = {0}; ut8 *data = __data; char op[128]; LookupTable *lt_ptr; int retval = -1; Opcode instr = {0}; strncpy (op, str, sizeof (op) - 1); op[sizeof (op) - 1] = '\0'; parseOpcode (a, op, &instr); for (lt_ptr = oplookup; strcmp (lt_ptr->mnemonic, "null"); lt_ptr++) { if (!r_str_casecmp (instr.mnemonic, lt_ptr->mnemonic)) { if (lt_ptr->opcode > 0) { if (!lt_ptr->only_x32 || a->bits != 64) { ut8 *ptr = (ut8 *)&lt_ptr->opcode; int i = 0; for (; i < lt_ptr->size; i++) { data[i] = ptr[lt_ptr->size - (i + 1)]; } retval = lt_ptr->size; } } else { if (lt_ptr->opdo) { if (instr.has_bnd) { data[0] = 0xf2; data ++; } retval = lt_ptr->opdo (a, data, &instr); // if op supports bnd then the first byte will // be 0xf2. if (instr.has_bnd) { retval++; } } } break; } } r_asm_op_set_buf (ao, __data, retval); free (instr.mnemonic); return retval; } RAsmPlugin r_asm_plugin_x86_nz = { .name = "x86.nz", .desc = "x86 handmade assembler", .license = "LGPL3", .arch = "x86", .bits = 16 | 32 | 64, .endian = R_SYS_ENDIAN_LITTLE, .assemble = &assemble }; #ifndef CORELIB R_API RLibStruct radare_plugin = { .type = R_LIB_TYPE_ASM, .data = &r_asm_plugin_x86_nz, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_458_0
crossvul-cpp_data_good_268_0
/* * Copyright (c) 2007-2011 Grégoire Henry, Juliusz Chroboczek * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* \summary: Babel Routing Protocol printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" static const char tstr[] = "[|babel]"; static void babel_print_v2(netdissect_options *, const u_char *cp, u_int length); void babel_print(netdissect_options *ndo, const u_char *cp, u_int length) { ND_PRINT((ndo, "babel")); ND_TCHECK2(*cp, 4); if(cp[0] != 42) { ND_PRINT((ndo, " invalid header")); return; } else { ND_PRINT((ndo, " %d", cp[1])); } switch(cp[1]) { case 2: babel_print_v2(ndo, cp, length); break; default: ND_PRINT((ndo, " unknown version")); break; } return; trunc: ND_PRINT((ndo, " %s", tstr)); return; } /* TLVs */ #define MESSAGE_PAD1 0 #define MESSAGE_PADN 1 #define MESSAGE_ACK_REQ 2 #define MESSAGE_ACK 3 #define MESSAGE_HELLO 4 #define MESSAGE_IHU 5 #define MESSAGE_ROUTER_ID 6 #define MESSAGE_NH 7 #define MESSAGE_UPDATE 8 #define MESSAGE_REQUEST 9 #define MESSAGE_MH_REQUEST 10 #define MESSAGE_TSPC 11 #define MESSAGE_HMAC 12 #define MESSAGE_UPDATE_SRC_SPECIFIC 13 #define MESSAGE_REQUEST_SRC_SPECIFIC 14 #define MESSAGE_MH_REQUEST_SRC_SPECIFIC 15 /* sub-TLVs */ #define MESSAGE_SUB_PAD1 0 #define MESSAGE_SUB_PADN 1 #define MESSAGE_SUB_DIVERSITY 2 #define MESSAGE_SUB_TIMESTAMP 3 /* Diversity sub-TLV channel codes */ static const struct tok diversity_str[] = { { 0, "reserved" }, { 255, "all" }, { 0, NULL } }; static const char * format_id(const u_char *id) { static char buf[25]; snprintf(buf, 25, "%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]); buf[24] = '\0'; return buf; } static const unsigned char v4prefix[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 }; static const char * format_prefix(netdissect_options *ndo, const u_char *prefix, unsigned char plen) { static char buf[50]; if(plen >= 96 && memcmp(prefix, v4prefix, 12) == 0) snprintf(buf, 50, "%s/%u", ipaddr_string(ndo, prefix + 12), plen - 96); else snprintf(buf, 50, "%s/%u", ip6addr_string(ndo, prefix), plen); buf[49] = '\0'; return buf; } static const char * format_address(netdissect_options *ndo, const u_char *prefix) { if(memcmp(prefix, v4prefix, 12) == 0) return ipaddr_string(ndo, prefix + 12); else return ip6addr_string(ndo, prefix); } static const char * format_interval(const uint16_t i) { static char buf[sizeof("000.00s")]; if (i == 0) return "0.0s (bogus)"; snprintf(buf, sizeof(buf), "%u.%02us", i / 100, i % 100); return buf; } static const char * format_interval_update(const uint16_t i) { return i == 0xFFFF ? "infinity" : format_interval(i); } static const char * format_timestamp(const uint32_t i) { static char buf[sizeof("0000.000000s")]; snprintf(buf, sizeof(buf), "%u.%06us", i / 1000000, i % 1000000); return buf; } /* Return number of octets consumed from the input buffer (not the prefix length * in bytes), or -1 for encoding error. */ static int network_prefix(int ae, int plen, unsigned int omitted, const unsigned char *p, const unsigned char *dp, unsigned int len, unsigned char *p_r) { unsigned pb; unsigned char prefix[16]; int consumed = 0; if(plen >= 0) pb = (plen + 7) / 8; else if(ae == 1) pb = 4; else pb = 16; if(pb > 16) return -1; memset(prefix, 0, 16); switch(ae) { case 0: break; case 1: if(omitted > 4 || pb > 4 || (pb > omitted && len < pb - omitted)) return -1; memcpy(prefix, v4prefix, 12); if(omitted) { if (dp == NULL) return -1; memcpy(prefix, dp, 12 + omitted); } if(pb > omitted) { memcpy(prefix + 12 + omitted, p, pb - omitted); consumed = pb - omitted; } break; case 2: if(omitted > 16 || (pb > omitted && len < pb - omitted)) return -1; if(omitted) { if (dp == NULL) return -1; memcpy(prefix, dp, omitted); } if(pb > omitted) { memcpy(prefix + omitted, p, pb - omitted); consumed = pb - omitted; } break; case 3: if(pb > 8 && len < pb - 8) return -1; prefix[0] = 0xfe; prefix[1] = 0x80; if(pb > 8) { memcpy(prefix + 8, p, pb - 8); consumed = pb - 8; } break; default: return -1; } memcpy(p_r, prefix, 16); return consumed; } static int network_address(int ae, const unsigned char *a, unsigned int len, unsigned char *a_r) { return network_prefix(ae, -1, 0, a, NULL, len, a_r); } /* * Sub-TLVs consume the "extra data" of Babel TLVs (see Section 4.3 of RFC6126), * their encoding is similar to the encoding of TLVs, but the type namespace is * different: * * o Type 0 stands for Pad1 sub-TLV with the same encoding as the Pad1 TLV. * o Type 1 stands for PadN sub-TLV with the same encoding as the PadN TLV. * o Type 2 stands for Diversity sub-TLV, which propagates diversity routing * data. Its body is a variable-length sequence of 8-bit unsigned integers, * each representing per-hop number of interferring radio channel for the * prefix. Channel 0 is invalid and must not be used in the sub-TLV, channel * 255 interferes with any other channel. * o Type 3 stands for Timestamp sub-TLV, used to compute RTT between * neighbours. In the case of a Hello TLV, the body stores a 32-bits * timestamp, while in the case of a IHU TLV, two 32-bits timestamps are * stored. * * Sub-TLV types 0 and 1 are valid for any TLV type, whether sub-TLV type 2 is * only valid for TLV type 8 (Update). Note that within an Update TLV a missing * Diversity sub-TLV is not the same as a Diversity sub-TLV with an empty body. * The former would mean a lack of any claims about the interference, and the * latter would state that interference is definitely absent. * A type 3 sub-TLV is valid both for Hello and IHU TLVs, though the exact * semantic of the sub-TLV is different in each case. */ static void subtlvs_print(netdissect_options *ndo, const u_char *cp, const u_char *ep, const uint8_t tlv_type) { uint8_t subtype, sublen; const char *sep; uint32_t t1, t2; while (cp < ep) { subtype = *cp++; if(subtype == MESSAGE_SUB_PAD1) { ND_PRINT((ndo, " sub-pad1")); continue; } if(cp == ep) goto invalid; sublen = *cp++; if(cp + sublen > ep) goto invalid; switch(subtype) { case MESSAGE_SUB_PADN: ND_PRINT((ndo, " sub-padn")); cp += sublen; break; case MESSAGE_SUB_DIVERSITY: ND_PRINT((ndo, " sub-diversity")); if (sublen == 0) { ND_PRINT((ndo, " empty")); break; } sep = " "; while(sublen--) { ND_PRINT((ndo, "%s%s", sep, tok2str(diversity_str, "%u", *cp++))); sep = "-"; } if(tlv_type != MESSAGE_UPDATE && tlv_type != MESSAGE_UPDATE_SRC_SPECIFIC) ND_PRINT((ndo, " (bogus)")); break; case MESSAGE_SUB_TIMESTAMP: ND_PRINT((ndo, " sub-timestamp")); if(tlv_type == MESSAGE_HELLO) { if(sublen < 4) goto invalid; t1 = EXTRACT_32BITS(cp); ND_PRINT((ndo, " %s", format_timestamp(t1))); } else if(tlv_type == MESSAGE_IHU) { if(sublen < 8) goto invalid; t1 = EXTRACT_32BITS(cp); ND_PRINT((ndo, " %s", format_timestamp(t1))); t2 = EXTRACT_32BITS(cp + 4); ND_PRINT((ndo, "|%s", format_timestamp(t2))); } else ND_PRINT((ndo, " (bogus)")); cp += sublen; break; default: ND_PRINT((ndo, " sub-unknown-0x%02x", subtype)); cp += sublen; } /* switch */ } /* while */ return; invalid: ND_PRINT((ndo, "%s", istr)); } #define ICHECK(i, l) \ if ((i) + (l) > bodylen || (i) + (l) > length) goto invalid; static void babel_print_v2(netdissect_options *ndo, const u_char *cp, u_int length) { u_int i; u_short bodylen; u_char v4_prefix[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 }; u_char v6_prefix[16] = {0}; ND_TCHECK2(*cp, 4); if (length < 4) goto invalid; bodylen = EXTRACT_16BITS(cp + 2); ND_PRINT((ndo, " (%u)", bodylen)); /* Process the TLVs in the body */ i = 0; while(i < bodylen) { const u_char *message; u_int type, len; message = cp + 4 + i; ND_TCHECK2(*message, 1); if((type = message[0]) == MESSAGE_PAD1) { ND_PRINT((ndo, ndo->ndo_vflag ? "\n\tPad 1" : " pad1")); i += 1; continue; } ND_TCHECK2(*message, 2); ICHECK(i, 2); len = message[1]; ND_TCHECK2(*message, 2 + len); ICHECK(i, 2 + len); switch(type) { case MESSAGE_PADN: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " padN")); else ND_PRINT((ndo, "\n\tPad %d", len + 2)); } break; case MESSAGE_ACK_REQ: { u_short nonce, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ack-req")); else { ND_PRINT((ndo, "\n\tAcknowledgment Request ")); if(len < 6) goto invalid; nonce = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); ND_PRINT((ndo, "%04x %s", nonce, format_interval(interval))); } } break; case MESSAGE_ACK: { u_short nonce; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ack")); else { ND_PRINT((ndo, "\n\tAcknowledgment ")); if(len < 2) goto invalid; nonce = EXTRACT_16BITS(message + 2); ND_PRINT((ndo, "%04x", nonce)); } } break; case MESSAGE_HELLO: { u_short seqno, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " hello")); else { ND_PRINT((ndo, "\n\tHello ")); if(len < 6) goto invalid; seqno = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); ND_PRINT((ndo, "seqno %u interval %s", seqno, format_interval(interval))); /* Extra data. */ if(len > 6) subtlvs_print(ndo, message + 8, message + 2 + len, type); } } break; case MESSAGE_IHU: { unsigned short txcost, interval; if (!ndo->ndo_vflag) ND_PRINT((ndo, " ihu")); else { u_char address[16]; int rc; ND_PRINT((ndo, "\n\tIHU ")); if(len < 6) goto invalid; txcost = EXTRACT_16BITS(message + 4); interval = EXTRACT_16BITS(message + 6); rc = network_address(message[2], message + 8, len - 6, address); if(rc < 0) { ND_PRINT((ndo, "%s", tstr)); break; } ND_PRINT((ndo, "%s txcost %u interval %s", format_address(ndo, address), txcost, format_interval(interval))); /* Extra data. */ if((u_int)rc < len - 6) subtlvs_print(ndo, message + 8 + rc, message + 2 + len, type); } } break; case MESSAGE_ROUTER_ID: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " router-id")); else { ND_PRINT((ndo, "\n\tRouter Id")); if(len < 10) goto invalid; ND_PRINT((ndo, " %s", format_id(message + 4))); } } break; case MESSAGE_NH: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " nh")); else { int rc; u_char nh[16]; ND_PRINT((ndo, "\n\tNext Hop")); if(len < 2) goto invalid; rc = network_address(message[2], message + 4, len - 2, nh); if(rc < 0) goto invalid; ND_PRINT((ndo, " %s", format_address(ndo, nh))); } } break; case MESSAGE_UPDATE: { if (!ndo->ndo_vflag) { ND_PRINT((ndo, " update")); if(len < 10) ND_PRINT((ndo, "/truncated")); else ND_PRINT((ndo, "%s%s%s", (message[3] & 0x80) ? "/prefix": "", (message[3] & 0x40) ? "/id" : "", (message[3] & 0x3f) ? "/unknown" : "")); } else { u_short interval, seqno, metric; u_char plen; int rc; u_char prefix[16]; ND_PRINT((ndo, "\n\tUpdate")); if(len < 10) goto invalid; plen = message[4] + (message[2] == 1 ? 96 : 0); rc = network_prefix(message[2], message[4], message[5], message + 12, message[2] == 1 ? v4_prefix : v6_prefix, len - 10, prefix); if(rc < 0) goto invalid; interval = EXTRACT_16BITS(message + 6); seqno = EXTRACT_16BITS(message + 8); metric = EXTRACT_16BITS(message + 10); ND_PRINT((ndo, "%s%s%s %s metric %u seqno %u interval %s", (message[3] & 0x80) ? "/prefix": "", (message[3] & 0x40) ? "/id" : "", (message[3] & 0x3f) ? "/unknown" : "", format_prefix(ndo, prefix, plen), metric, seqno, format_interval_update(interval))); if(message[3] & 0x80) { if(message[2] == 1) memcpy(v4_prefix, prefix, 16); else memcpy(v6_prefix, prefix, 16); } /* extra data? */ if((u_int)rc < len - 10) subtlvs_print(ndo, message + 12 + rc, message + 2 + len, type); } } break; case MESSAGE_REQUEST: { if (!ndo->ndo_vflag) ND_PRINT((ndo, " request")); else { int rc; u_char prefix[16], plen; ND_PRINT((ndo, "\n\tRequest ")); if(len < 2) goto invalid; plen = message[3] + (message[2] == 1 ? 96 : 0); rc = network_prefix(message[2], message[3], 0, message + 4, NULL, len - 2, prefix); if(rc < 0) goto invalid; ND_PRINT((ndo, "for %s", message[2] == 0 ? "any" : format_prefix(ndo, prefix, plen))); } } break; case MESSAGE_MH_REQUEST : { if (!ndo->ndo_vflag) ND_PRINT((ndo, " mh-request")); else { int rc; u_short seqno; u_char prefix[16], plen; ND_PRINT((ndo, "\n\tMH-Request ")); if(len < 14) goto invalid; seqno = EXTRACT_16BITS(message + 4); rc = network_prefix(message[2], message[3], 0, message + 16, NULL, len - 14, prefix); if(rc < 0) goto invalid; plen = message[3] + (message[2] == 1 ? 96 : 0); ND_PRINT((ndo, "(%u hops) for %s seqno %u id %s", message[6], format_prefix(ndo, prefix, plen), seqno, format_id(message + 8))); } } break; case MESSAGE_TSPC : if (!ndo->ndo_vflag) ND_PRINT((ndo, " tspc")); else { ND_PRINT((ndo, "\n\tTS/PC ")); if(len < 6) goto invalid; ND_PRINT((ndo, "timestamp %u packetcounter %u", EXTRACT_32BITS (message + 4), EXTRACT_16BITS(message + 2))); } break; case MESSAGE_HMAC : { if (!ndo->ndo_vflag) ND_PRINT((ndo, " hmac")); else { unsigned j; ND_PRINT((ndo, "\n\tHMAC ")); if(len < 18) goto invalid; ND_PRINT((ndo, "key-id %u digest-%u ", EXTRACT_16BITS(message + 2), len - 2)); for (j = 0; j < len - 2; j++) ND_PRINT((ndo, "%02X", message[4 + j])); } } break; case MESSAGE_UPDATE_SRC_SPECIFIC : { if(!ndo->ndo_vflag) { ND_PRINT((ndo, " ss-update")); } else { u_char prefix[16], src_prefix[16]; u_short interval, seqno, metric; u_char ae, plen, src_plen, omitted; int rc; int parsed_len = 10; ND_PRINT((ndo, "\n\tSS-Update")); if(len < 10) goto invalid; ae = message[2]; src_plen = message[3]; plen = message[4]; omitted = message[5]; interval = EXTRACT_16BITS(message + 6); seqno = EXTRACT_16BITS(message + 8); metric = EXTRACT_16BITS(message + 10); rc = network_prefix(ae, plen, omitted, message + 2 + parsed_len, ae == 1 ? v4_prefix : v6_prefix, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; parsed_len += rc; ND_PRINT((ndo, " %s from", format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, " %s metric %u seqno %u interval %s", format_prefix(ndo, src_prefix, src_plen), metric, seqno, format_interval_update(interval))); /* extra data? */ if((u_int)parsed_len < len) subtlvs_print(ndo, message + 2 + parsed_len, message + 2 + len, type); } } break; case MESSAGE_REQUEST_SRC_SPECIFIC : { if(!ndo->ndo_vflag) ND_PRINT((ndo, " ss-request")); else { int rc, parsed_len = 3; u_char ae, plen, src_plen, prefix[16], src_prefix[16]; ND_PRINT((ndo, "\n\tSS-Request ")); if(len < 3) goto invalid; ae = message[2]; plen = message[3]; src_plen = message[4]; rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; parsed_len += rc; if(ae == 0) { ND_PRINT((ndo, "for any")); } else { ND_PRINT((ndo, "for (%s, ", format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, "%s)", format_prefix(ndo, src_prefix, src_plen))); } } } break; case MESSAGE_MH_REQUEST_SRC_SPECIFIC : { if(!ndo->ndo_vflag) ND_PRINT((ndo, " ss-mh-request")); else { int rc, parsed_len = 14; u_short seqno; u_char ae, plen, src_plen, prefix[16], src_prefix[16], hopc; const u_char *router_id = NULL; ND_PRINT((ndo, "\n\tSS-MH-Request ")); if(len < 14) goto invalid; ae = message[2]; plen = message[3]; seqno = EXTRACT_16BITS(message + 4); hopc = message[6]; src_plen = message[7]; router_id = message + 8; rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, prefix); if(rc < 0) goto invalid; if(ae == 1) plen += 96; parsed_len += rc; rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, NULL, len - parsed_len, src_prefix); if(rc < 0) goto invalid; if(ae == 1) src_plen += 96; ND_PRINT((ndo, "(%u hops) for (%s, ", hopc, format_prefix(ndo, prefix, plen))); ND_PRINT((ndo, "%s) seqno %u id %s", format_prefix(ndo, src_prefix, src_plen), seqno, format_id(router_id))); } } break; default: if (!ndo->ndo_vflag) ND_PRINT((ndo, " unknown")); else ND_PRINT((ndo, "\n\tUnknown message type %d", type)); } i += len + 2; } return; trunc: ND_PRINT((ndo, " %s", tstr)); return; invalid: ND_PRINT((ndo, "%s", istr)); return; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_268_0
crossvul-cpp_data_good_5312_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType CorrectPSDOpacity(LayerInfo *layer_info, ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (layer_info->opacity == OpaqueAlpha) return(MagickTrue); layer_info->image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1) #endif for (y=0; y < (ssize_t) layer_info->image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1, exception); if (q == (Quantum *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha( layer_info->image,q))*layer_info->opacity),q); q+=GetPixelChannels(layer_info->image); } if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse) status=MagickFalse; } return(status); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (p+count > blocks+length) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if (*(p+4) == 0) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); return; } switch (type) { case -1: { SetPixelAlpha(image, pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLEOffsets(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *offsets; ssize_t y; offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets)); if(offsets != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) offsets[y]=(MagickOffsetType) ReadBlobShort(image); else offsets[y]=(MagickOffsetType) ReadBlobLong(image); } } return offsets; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *offsets,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < offsets[y]) length=(size_t) offsets[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) offsets[y],compact_pixels); if (count != (ssize_t) offsets[y]) break; count=DecodePSDPixels((size_t) offsets[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } ResetMagickMemory(&stream, 0, sizeof(z_stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(unsigned int) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(unsigned int) count; if(inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if (ret != Z_OK && ret != Z_STREAM_END) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } } if (compression == ZipWithPrediction) { p=pixels; while(count > 0) { length=image->columns; while(--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,const size_t channel, const PSDCompressionType compression,ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ if (layer_info->channel_info[channel].type != -2 || (layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02)) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); SetImageType(mask,GrayscaleType,exception); channel_image=mask; } offset=TellBlob(channel_image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *offsets; offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,offsets,exception); offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (status != MagickFalse) { PixelInfo color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->alpha_trait=UndefinedPixelTrait; GetPixelInfo(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; SetImageColor(layer_info->mask.image,&color,exception); (void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp, MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y, exception); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { status=CompositeImage(layer_info->image,layer_info->mask.image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=(int) ReadBlobLong(image); layer_info[i].page.x=(int) ReadBlobLong(image); y=(int) ReadBlobLong(image); x=(int) ReadBlobLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(int) ReadBlobLong(image); layer_info[i].mask.page.x=(int) ReadBlobLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) (length); j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(size_t) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); /* Skip the rest of the variable data until we support it. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " unsupported data: length=%.20g",(double) ((MagickOffsetType) (size-combined_length))); if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,psd_info,&layer_info[i],exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : UndefinedPixelTrait; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : UndefinedPixelTrait; } else image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : UndefinedPixelTrait; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) { Image *merged; SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static void WritePackbitsLength(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, unsigned char *compact_pixels,const QuantumType quantum_type, ExceptionInfo *exception) { QuantumInfo *quantum_info; register const Quantum *p; size_t length, packet_size; ssize_t y; unsigned char *pixels; if (next_image->depth > 8) next_image->depth=16; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) SetPSDOffset(psd_info,image,length); } quantum_info=DestroyQuantumInfo(quantum_info); } static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info, Image *image,Image *next_image,unsigned char *compact_pixels, const QuantumType quantum_type,const MagickBooleanType compression_flag, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t length, packet_size; unsigned char *pixels; (void) psd_info; if ((compression_flag != MagickFalse) && (next_image->compression != RLECompression)) (void) WriteBlobMSBShort(image,0); if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression != RLECompression) (void) WriteBlob(image,length,pixels); else { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); (void) WriteBlob(image,length,compact_pixels); } } quantum_info=DestroyQuantumInfo(quantum_info); } static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } static void WritePascalString(Image* inImage,const char *inString,int inPad) { size_t length; register ssize_t i; /* Max length is 255. */ length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString); if (length == 0) (void) WriteBlobByte(inImage,0); else { (void) WriteBlobByte(inImage,(unsigned char) length); (void) WriteBlob(inImage, length, (const unsigned char *) inString); } length++; if ((length % inPad) == 0) return; for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++) (void) WriteBlobByte(inImage,0); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *property; const StringInfo *icc_profile; Image *base_image, *next_image; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t channel_size, channelLength, layer_count, layer_info_size, length, num_channels, packet_size, rounded_layer_info_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ if (SetImageGray(image,exception) != MagickFalse) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } layer_count=0; layer_info_size=2; base_image=GetNextImageInList(image); if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL)) base_image=image; next_image=base_image; while ( next_image != NULL ) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsImageGray(next_image) != MagickFalse) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL; else num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL; channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2); layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 : 16)+4*1+4+num_channels*channelLength); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) layer_info_size+=16; else { size_t layer_length; layer_length=strlen(property); layer_info_size+=8+layer_length+(4-(layer_length % 4)); } layer_count++; next_image=GetNextImageInList(next_image); } if (layer_count == 0) (void) SetPSDSize(&psd_info,image,0); else { CompressionType compression; (void) SetPSDSize(&psd_info,image,layer_info_size+ (psd_info.version == 1 ? 8 : 16)); if ((layer_info_size/2) != ((layer_info_size+1)/2)) rounded_layer_info_size=layer_info_size+1; else rounded_layer_info_size=layer_info_size; (void) SetPSDSize(&psd_info,image,rounded_layer_info_size); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobMSBShort(image,-(unsigned short) layer_count); else (void) WriteBlobMSBShort(image,(unsigned short) layer_count); layer_count=1; compression=base_image->compression; for (next_image=base_image; next_image != NULL; ) { next_image->compression=NoCompression; (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y); (void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); (void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); packet_size=next_image->depth > 8 ? 2UL : 1UL; channel_size=(unsigned int) ((packet_size*next_image->rows* next_image->columns)+2); if ((IsImageGray(next_image) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else if (next_image->colorspace != CMYKColorspace) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->alpha_trait ? 5 : 4)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,1); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,2); (void) SetPSDSize(&psd_info,image,channel_size); (void) WriteBlobMSBShort(image,3); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->alpha_trait) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); (void) WriteBlobByte(image,255); /* layer opacity */ (void) WriteBlobByte(image,0); (void) WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ (void) WriteBlobByte(image,0); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { char layer_name[MagickPathExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t label_length; label_length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4- (label_length % 4))+8)); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); WritePascalString(image,property,4); } next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; while (next_image != NULL) { status=WriteImageChannels(&psd_info,image_info,image,next_image, MagickTrue,exception); next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ base_image->compression=compression; } /* Write composite image. */ if (status != MagickFalse) status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse, exception); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_5312_0
crossvul-cpp_data_bad_2664_0
/* * Copyright (C) 1999 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Extensively modified by Hannes Gredler (hannes@gredler.at) for more * complete BGP support. */ /* \summary: Border Gateway Protocol (BGP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "af.h" #include "l2vpn.h" struct bgp { uint8_t bgp_marker[16]; uint16_t bgp_len; uint8_t bgp_type; }; #define BGP_SIZE 19 /* unaligned */ #define BGP_OPEN 1 #define BGP_UPDATE 2 #define BGP_NOTIFICATION 3 #define BGP_KEEPALIVE 4 #define BGP_ROUTE_REFRESH 5 static const struct tok bgp_msg_values[] = { { BGP_OPEN, "Open"}, { BGP_UPDATE, "Update"}, { BGP_NOTIFICATION, "Notification"}, { BGP_KEEPALIVE, "Keepalive"}, { BGP_ROUTE_REFRESH, "Route Refresh"}, { 0, NULL} }; struct bgp_open { uint8_t bgpo_marker[16]; uint16_t bgpo_len; uint8_t bgpo_type; uint8_t bgpo_version; uint16_t bgpo_myas; uint16_t bgpo_holdtime; uint32_t bgpo_id; uint8_t bgpo_optlen; /* options should follow */ }; #define BGP_OPEN_SIZE 29 /* unaligned */ struct bgp_opt { uint8_t bgpopt_type; uint8_t bgpopt_len; /* variable length */ }; #define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */ #define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */ struct bgp_notification { uint8_t bgpn_marker[16]; uint16_t bgpn_len; uint8_t bgpn_type; uint8_t bgpn_major; uint8_t bgpn_minor; }; #define BGP_NOTIFICATION_SIZE 21 /* unaligned */ struct bgp_route_refresh { uint8_t bgp_marker[16]; uint16_t len; uint8_t type; uint8_t afi[2]; /* the compiler messes this structure up */ uint8_t res; /* when doing misaligned sequences of int8 and int16 */ uint8_t safi; /* afi should be int16 - so we have to access it using */ }; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */ #define BGP_ROUTE_REFRESH_SIZE 23 #define bgp_attr_lenlen(flags, p) \ (((flags) & 0x10) ? 2 : 1) #define bgp_attr_len(flags, p) \ (((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p)) #define BGPTYPE_ORIGIN 1 #define BGPTYPE_AS_PATH 2 #define BGPTYPE_NEXT_HOP 3 #define BGPTYPE_MULTI_EXIT_DISC 4 #define BGPTYPE_LOCAL_PREF 5 #define BGPTYPE_ATOMIC_AGGREGATE 6 #define BGPTYPE_AGGREGATOR 7 #define BGPTYPE_COMMUNITIES 8 /* RFC1997 */ #define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */ #define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */ #define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */ #define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */ #define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */ #define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */ #define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */ #define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */ #define BGPTYPE_AS4_PATH 17 /* RFC6793 */ #define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */ #define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */ #define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */ #define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */ #define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */ #define BGPTYPE_AIGP 26 /* RFC7311 */ #define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */ #define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */ #define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */ #define BGPTYPE_ATTR_SET 128 /* RFC6368 */ #define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */ static const struct tok bgp_attr_values[] = { { BGPTYPE_ORIGIN, "Origin"}, { BGPTYPE_AS_PATH, "AS Path"}, { BGPTYPE_AS4_PATH, "AS4 Path"}, { BGPTYPE_NEXT_HOP, "Next Hop"}, { BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"}, { BGPTYPE_LOCAL_PREF, "Local Preference"}, { BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"}, { BGPTYPE_AGGREGATOR, "Aggregator"}, { BGPTYPE_AGGREGATOR4, "Aggregator4"}, { BGPTYPE_COMMUNITIES, "Community"}, { BGPTYPE_ORIGINATOR_ID, "Originator ID"}, { BGPTYPE_CLUSTER_LIST, "Cluster List"}, { BGPTYPE_DPA, "DPA"}, { BGPTYPE_ADVERTISERS, "Advertisers"}, { BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"}, { BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"}, { BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"}, { BGPTYPE_EXTD_COMMUNITIES, "Extended Community"}, { BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"}, { BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"}, { BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"}, { BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"}, { BGPTYPE_AIGP, "Accumulated IGP Metric"}, { BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"}, { BGPTYPE_ENTROPY_LABEL, "Entropy Label"}, { BGPTYPE_LARGE_COMMUNITY, "Large Community"}, { BGPTYPE_ATTR_SET, "Attribute Set"}, { 255, "Reserved for development"}, { 0, NULL} }; #define BGP_AS_SET 1 #define BGP_AS_SEQUENCE 2 #define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */ #define BGP_AS_SEG_TYPE_MIN BGP_AS_SET #define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET static const struct tok bgp_as_path_segment_open_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "{ "}, { BGP_CONFED_AS_SEQUENCE, "( "}, { BGP_CONFED_AS_SET, "({ "}, { 0, NULL} }; static const struct tok bgp_as_path_segment_close_values[] = { { BGP_AS_SEQUENCE, ""}, { BGP_AS_SET, "}"}, { BGP_CONFED_AS_SEQUENCE, ")"}, { BGP_CONFED_AS_SET, "})"}, { 0, NULL} }; #define BGP_OPT_AUTH 1 #define BGP_OPT_CAP 2 static const struct tok bgp_opt_values[] = { { BGP_OPT_AUTH, "Authentication Information"}, { BGP_OPT_CAP, "Capabilities Advertisement"}, { 0, NULL} }; #define BGP_CAPCODE_MP 1 /* RFC2858 */ #define BGP_CAPCODE_RR 2 /* RFC2918 */ #define BGP_CAPCODE_ORF 3 /* RFC5291 */ #define BGP_CAPCODE_MR 4 /* RFC3107 */ #define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */ #define BGP_CAPCODE_RESTART 64 /* RFC4724 */ #define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */ #define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */ #define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */ #define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */ #define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */ #define BGP_CAPCODE_RR_CISCO 128 static const struct tok bgp_capcode_values[] = { { BGP_CAPCODE_MP, "Multiprotocol Extensions"}, { BGP_CAPCODE_RR, "Route Refresh"}, { BGP_CAPCODE_ORF, "Cooperative Route Filtering"}, { BGP_CAPCODE_MR, "Multiple Routes to a Destination"}, { BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"}, { BGP_CAPCODE_RESTART, "Graceful Restart"}, { BGP_CAPCODE_AS_NEW, "32-Bit AS Number"}, { BGP_CAPCODE_DYN_CAP, "Dynamic Capability"}, { BGP_CAPCODE_MULTISESS, "Multisession BGP"}, { BGP_CAPCODE_ADD_PATH, "Multiple Paths"}, { BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"}, { BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"}, { 0, NULL} }; #define BGP_NOTIFY_MAJOR_MSG 1 #define BGP_NOTIFY_MAJOR_OPEN 2 #define BGP_NOTIFY_MAJOR_UPDATE 3 #define BGP_NOTIFY_MAJOR_HOLDTIME 4 #define BGP_NOTIFY_MAJOR_FSM 5 #define BGP_NOTIFY_MAJOR_CEASE 6 #define BGP_NOTIFY_MAJOR_CAP 7 static const struct tok bgp_notify_major_values[] = { { BGP_NOTIFY_MAJOR_MSG, "Message Header Error"}, { BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"}, { BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"}, { BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"}, { BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"}, { BGP_NOTIFY_MAJOR_CEASE, "Cease"}, { BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"}, { 0, NULL} }; /* draft-ietf-idr-cease-subcode-02 */ #define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1 /* draft-ietf-idr-shutdown-07 */ #define BGP_NOTIFY_MINOR_CEASE_SHUT 2 #define BGP_NOTIFY_MINOR_CEASE_RESET 4 #define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128 static const struct tok bgp_notify_minor_cease_values[] = { { BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"}, { BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"}, { 3, "Peer Unconfigured"}, { BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"}, { 5, "Connection Rejected"}, { 6, "Other Configuration Change"}, { 7, "Connection Collision Resolution"}, { 0, NULL} }; static const struct tok bgp_notify_minor_msg_values[] = { { 1, "Connection Not Synchronized"}, { 2, "Bad Message Length"}, { 3, "Bad Message Type"}, { 0, NULL} }; static const struct tok bgp_notify_minor_open_values[] = { { 1, "Unsupported Version Number"}, { 2, "Bad Peer AS"}, { 3, "Bad BGP Identifier"}, { 4, "Unsupported Optional Parameter"}, { 5, "Authentication Failure"}, { 6, "Unacceptable Hold Time"}, { 7, "Capability Message Error"}, { 0, NULL} }; static const struct tok bgp_notify_minor_update_values[] = { { 1, "Malformed Attribute List"}, { 2, "Unrecognized Well-known Attribute"}, { 3, "Missing Well-known Attribute"}, { 4, "Attribute Flags Error"}, { 5, "Attribute Length Error"}, { 6, "Invalid ORIGIN Attribute"}, { 7, "AS Routing Loop"}, { 8, "Invalid NEXT_HOP Attribute"}, { 9, "Optional Attribute Error"}, { 10, "Invalid Network Field"}, { 11, "Malformed AS_PATH"}, { 0, NULL} }; static const struct tok bgp_notify_minor_fsm_values[] = { { 0, "Unspecified Error"}, { 1, "In OpenSent State"}, { 2, "In OpenConfirm State"}, { 3, "In Established State"}, { 0, NULL } }; static const struct tok bgp_notify_minor_cap_values[] = { { 1, "Invalid Action Value" }, { 2, "Invalid Capability Length" }, { 3, "Malformed Capability Value" }, { 4, "Unsupported Capability Code" }, { 0, NULL } }; static const struct tok bgp_origin_values[] = { { 0, "IGP"}, { 1, "EGP"}, { 2, "Incomplete"}, { 0, NULL} }; #define BGP_PMSI_TUNNEL_RSVP_P2MP 1 #define BGP_PMSI_TUNNEL_LDP_P2MP 2 #define BGP_PMSI_TUNNEL_PIM_SSM 3 #define BGP_PMSI_TUNNEL_PIM_SM 4 #define BGP_PMSI_TUNNEL_PIM_BIDIR 5 #define BGP_PMSI_TUNNEL_INGRESS 6 #define BGP_PMSI_TUNNEL_LDP_MP2MP 7 static const struct tok bgp_pmsi_tunnel_values[] = { { BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"}, { BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"}, { BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"}, { BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"}, { BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"}, { BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"}, { BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"}, { 0, NULL} }; static const struct tok bgp_pmsi_flag_values[] = { { 0x01, "Leaf Information required"}, { 0, NULL} }; #define BGP_AIGP_TLV 1 static const struct tok bgp_aigp_values[] = { { BGP_AIGP_TLV, "AIGP"}, { 0, NULL} }; /* Subsequent address family identifier, RFC2283 section 7 */ #define SAFNUM_RES 0 #define SAFNUM_UNICAST 1 #define SAFNUM_MULTICAST 2 #define SAFNUM_UNIMULTICAST 3 /* deprecated now */ /* labeled BGP RFC3107 */ #define SAFNUM_LABUNICAST 4 /* RFC6514 */ #define SAFNUM_MULTICAST_VPN 5 /* draft-nalawade-kapoor-tunnel-safi */ #define SAFNUM_TUNNEL 64 /* RFC4761 */ #define SAFNUM_VPLS 65 /* RFC6037 */ #define SAFNUM_MDT 66 /* RFC4364 */ #define SAFNUM_VPNUNICAST 128 /* RFC6513 */ #define SAFNUM_VPNMULTICAST 129 #define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */ /* RFC4684 */ #define SAFNUM_RT_ROUTING_INFO 132 #define BGP_VPN_RD_LEN 8 static const struct tok bgp_safi_values[] = { { SAFNUM_RES, "Reserved"}, { SAFNUM_UNICAST, "Unicast"}, { SAFNUM_MULTICAST, "Multicast"}, { SAFNUM_UNIMULTICAST, "Unicast+Multicast"}, { SAFNUM_LABUNICAST, "labeled Unicast"}, { SAFNUM_TUNNEL, "Tunnel"}, { SAFNUM_VPLS, "VPLS"}, { SAFNUM_MDT, "MDT"}, { SAFNUM_VPNUNICAST, "labeled VPN Unicast"}, { SAFNUM_VPNMULTICAST, "labeled VPN Multicast"}, { SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"}, { SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"}, { SAFNUM_MULTICAST_VPN, "Multicast VPN"}, { 0, NULL } }; /* well-known community */ #define BGP_COMMUNITY_NO_EXPORT 0xffffff01 #define BGP_COMMUNITY_NO_ADVERT 0xffffff02 #define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03 /* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */ #define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */ #define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */ #define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */ /* rfc2547 bgp-mpls-vpns */ #define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */ #define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */ #define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */ #define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */ #define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */ #define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */ #define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */ /* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */ #define BGP_EXT_COM_EIGRP_GEN 0x8800 #define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801 #define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802 #define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803 #define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804 #define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805 static const struct tok bgp_extd_comm_flag_values[] = { { 0x8000, "vendor-specific"}, { 0x4000, "non-transitive"}, { 0, NULL}, }; static const struct tok bgp_extd_comm_subtype_values[] = { { BGP_EXT_COM_RT_0, "target"}, { BGP_EXT_COM_RT_1, "target"}, { BGP_EXT_COM_RT_2, "target"}, { BGP_EXT_COM_RO_0, "origin"}, { BGP_EXT_COM_RO_1, "origin"}, { BGP_EXT_COM_RO_2, "origin"}, { BGP_EXT_COM_LINKBAND, "link-BW"}, { BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"}, { BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"}, { BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"}, { BGP_EXT_COM_OSPF_RID, "ospf-router-id"}, { BGP_EXT_COM_OSPF_RID2, "ospf-router-id"}, { BGP_EXT_COM_L2INFO, "layer2-info"}, { BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" }, { BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" }, { BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" }, { BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" }, { BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" }, { BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" }, { BGP_EXT_COM_SOURCE_AS, "source-AS" }, { BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"}, { BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"}, { BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"}, { 0, NULL}, }; /* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */ #define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */ #define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */ #define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */ #define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */ #define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/ #define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */ #define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */ static const struct tok bgp_extd_comm_ospf_rtype_values[] = { { BGP_OSPF_RTYPE_RTR, "Router" }, { BGP_OSPF_RTYPE_NET, "Network" }, { BGP_OSPF_RTYPE_SUM, "Summary" }, { BGP_OSPF_RTYPE_EXT, "External" }, { BGP_OSPF_RTYPE_NSSA,"NSSA External" }, { BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" }, { 0, NULL }, }; /* ADD-PATH Send/Receive field values */ static const struct tok bgp_add_path_recvsend[] = { { 1, "Receive" }, { 2, "Send" }, { 3, "Both" }, { 0, NULL }, }; static char astostr[20]; /* * as_printf * * Convert an AS number into a string and return string pointer. * * Depending on bflag is set or not, AS number is converted into ASDOT notation * or plain number notation. * */ static char * as_printf(netdissect_options *ndo, char *str, int size, u_int asnum) { if (!ndo->ndo_bflag || asnum <= 0xFFFF) { snprintf(str, size, "%u", asnum); } else { snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF); } return str; } #define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv; int decode_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; ND_TCHECK(pptr[0]); ITEMCHECK(1); plen = pptr[0]; if (32 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[1], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix4(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ /* this is one of the weirdnesses of rfc3107 the label length (actually the label + COS bits) is added to the prefix length; we also do only read out just one label - there is no real application for advertisement of stacked labels in a single BGP message */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (32 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } /* * bgp_vpn_ip_print * * print an ipv4 or ipv6 address into a buffer dependend on address length. */ static char * bgp_vpn_ip_print(netdissect_options *ndo, const u_char *pptr, u_int addr_length) { /* worst case string is s fully formatted v6 address */ static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")]; char *pos = addr; switch(addr_length) { case (sizeof(struct in_addr) << 3): /* 32 */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr)); break; case (sizeof(struct in6_addr) << 3): /* 128 */ ND_TCHECK2(pptr[0], sizeof(struct in6_addr)); snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr)); break; default: snprintf(pos, sizeof(addr), "bogus address length %u", addr_length); break; } pos += strlen(pos); trunc: *(pos) = '\0'; return (addr); } /* * bgp_vpn_sg_print * * print an multicast s,g entry into a buffer. * the s,g entry is encoded like this. * * +-----------------------------------+ * | Multicast Source Length (1 octet) | * +-----------------------------------+ * | Multicast Source (Variable) | * +-----------------------------------+ * | Multicast Group Length (1 octet) | * +-----------------------------------+ * | Multicast Group (Variable) | * +-----------------------------------+ * * return the number of bytes read from the wire. */ static int bgp_vpn_sg_print(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr_length; u_int total_length, offset; total_length = 0; /* Source address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Source address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Source %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } /* Group address length, encoded in bits */ ND_TCHECK2(pptr[0], 1); addr_length = *pptr++; /* Group address */ ND_TCHECK2(pptr[0], (addr_length >> 3)); total_length += (addr_length >> 3) + 1; offset = strlen(buf); if (addr_length) { snprintf(buf + offset, buflen - offset, ", Group %s", bgp_vpn_ip_print(ndo, pptr, addr_length)); pptr += (addr_length >> 3); } trunc: return (total_length); } /* RDs and RTs share the same semantics * we use bgp_vpn_rd_print for * printing route targets inside a NLRI */ char * bgp_vpn_rd_print(netdissect_options *ndo, const u_char *pptr) { /* allocate space for the largest possible string */ static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")]; char *pos = rd; /* ok lets load the RD format */ switch (EXTRACT_16BITS(pptr)) { /* 2-byte-AS:number fmt*/ case 0: snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)", EXTRACT_16BITS(pptr+2), EXTRACT_32BITS(pptr+4), *(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7)); break; /* IP-address:AS fmt*/ case 1: snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u", *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; /* 4-byte-AS:number fmt*/ case 2: snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)), EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6)); break; default: snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format"); break; } pos += strlen(pos); *(pos) = '\0'; return (rd); } static int decode_rt_routing_info(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_target[8]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (0 == plen) { snprintf(buf, buflen, "default route target"); return 1; } if (32 > plen) return -1; plen-=32; /* adjust prefix length */ if (64 < plen) return -1; memset(&route_target, 0, sizeof(route_target)); ND_TCHECK2(pptr[1], (plen + 7) / 8); memcpy(&route_target, &pptr[1], (plen + 7) / 8); if (plen % 8) { ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "origin AS: %s, route target %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), bgp_vpn_rd_print(ndo, (u_char *)&route_target)); return 5 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_prefix4(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (32 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { ((u_char *)&addr)[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ipaddr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * +-------------------------------+ * | | * | RD:IPv4-address (12 octets) | * | | * +-------------------------------+ * | MDT Group-address (4 octets) | * +-------------------------------+ */ #define MDT_VPN_NLRI_LEN 16 static int decode_mdt_vpn_nlri(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { const u_char *rd; const u_char *vpn_ip; ND_TCHECK(pptr[0]); /* if the NLRI is not predefined length, quit.*/ if (*pptr != MDT_VPN_NLRI_LEN * 8) return -1; pptr++; /* RD */ ND_TCHECK2(pptr[0], 8); rd = pptr; pptr+=8; /* IPv4 address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); vpn_ip = pptr; pptr+=sizeof(struct in_addr); /* MDT Group Address */ ND_TCHECK2(pptr[0], sizeof(struct in_addr)); snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s", bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr)); return MDT_VPN_NLRI_LEN + 1; trunc: return -2; } #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2 #define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3 #define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6 #define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7 static const struct tok bgp_multicast_vpn_route_type_values[] = { { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"}, { BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"}, { 0, NULL} }; static int decode_multicast_vpn(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t route_type, route_length, addr_length, sg_length; u_int offset; ND_TCHECK2(pptr[0], 2); route_type = *pptr++; route_length = *pptr++; snprintf(buf, buflen, "Route-Type: %s (%u), length: %u", tok2str(bgp_multicast_vpn_route_type_values, "Unknown", route_type), route_type, route_length); switch(route_type) { case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s", bgp_vpn_rd_print(ndo, pptr), bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, (route_length - BGP_VPN_RD_LEN) << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); addr_length = route_length - sg_length; ND_TCHECK2(pptr[0], addr_length); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", Originator %s", bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s", bgp_vpn_rd_print(ndo, pptr)); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); offset = strlen(buf); snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s", bgp_vpn_rd_print(ndo, pptr), as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); pptr += BGP_VPN_RD_LEN; bgp_vpn_sg_print(ndo, pptr, buf, buflen); break; /* * no per route-type printing yet. */ case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: default: break; } return route_length + 2; trunc: return -2; } /* * As I remember, some versions of systems have an snprintf() that * returns -1 if the buffer would have overflowed. If the return * value is negative, set buflen to 0, to indicate that we've filled * the buffer up. * * If the return value is greater than buflen, that means that * the buffer would have overflowed; again, set buflen to 0 in * that case. */ #define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \ if (stringlen<0) \ buflen=0; \ else if ((u_int)stringlen>buflen) \ buflen=0; \ else { \ buflen-=stringlen; \ buf+=stringlen; \ } static int decode_labeled_vpn_l2(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len; ND_TCHECK2(pptr[0], 2); plen=EXTRACT_16BITS(pptr); tlen=plen; pptr+=2; /* Old and new L2VPN NLRI share AFI/SAFI * -> Assume a 12 Byte-length NLRI is auto-discovery-only * and > 17 as old format. Complain for the middle case */ if (plen==12) { /* assume AD-only with RD, BGPNH */ ND_TCHECK2(pptr[0],12); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s", bgp_vpn_rd_print(ndo, pptr), ipaddr_string(ndo, pptr+8) ); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=12; tlen-=12; return plen; } else if (plen>17) { /* assume old format */ /* RD, ID, LBLKOFF, LBLBASE */ ND_TCHECK2(pptr[0],15); buf[0]='\0'; stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u", bgp_vpn_rd_print(ndo, pptr), EXTRACT_16BITS(pptr+8), EXTRACT_16BITS(pptr+10), EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */ UPDATE_BUF_BUFLEN(buf, buflen, stringlen); pptr+=15; tlen-=15; /* ok now the variable part - lets read out TLVs*/ while (tlen>0) { if (tlen < 3) return -1; ND_TCHECK2(pptr[0], 3); tlv_type=*pptr++; tlv_len=EXTRACT_16BITS(pptr); ttlv_len=tlv_len; pptr+=2; switch(tlv_type) { case 1: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */ while (ttlv_len>0) { ND_TCHECK(pptr[0]); if (buflen!=0) { stringlen=snprintf(buf,buflen, "%02x",*pptr++); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } ttlv_len--; } break; default: if (buflen!=0) { stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u", tlv_type, tlv_len); UPDATE_BUF_BUFLEN(buf, buflen, stringlen); } break; } tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */ } return plen+2; } else { /* complain bitterly ? */ /* fall through */ goto trunc; } trunc: return -2; } int decode_prefix6(netdissect_options *ndo, const u_char *pd, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; ND_TCHECK(pd[0]); ITEMCHECK(1); plen = pd[0]; if (128 < plen) return -1; itemlen -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pd[1], plenbytes); ITEMCHECK(plenbytes); memcpy(&addr, &pd[1], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen); return 1 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_prefix6(netdissect_options *ndo, const u_char *pptr, u_int itemlen, char *buf, u_int buflen) { struct in6_addr addr; u_int plen, plenbytes; /* prefix length and label = 4 bytes */ ND_TCHECK2(pptr[0], 4); ITEMCHECK(4); plen = pptr[0]; /* get prefix length */ if (24 > plen) return -1; plen-=24; /* adjust prefixlen - labellength */ if (128 < plen) return -1; itemlen -= 4; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; ND_TCHECK2(pptr[4], plenbytes); memcpy(&addr, &pptr[4], plenbytes); if (plen % 8) { addr.s6_addr[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "%s/%d, label:%u %s", ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 4 + plenbytes; trunc: return -2; badtlv: return -3; } static int decode_labeled_vpn_prefix6(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { struct in6_addr addr; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (128 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr.s6_addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), ip6addr_string(ndo, &addr), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } static int decode_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[4], (plen + 7) / 8); memcpy(&addr, &pptr[4], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, buflen, "%s/%d", isonsap_string(ndo, addr,(plen + 7) / 8), plen); return 1 + (plen + 7) / 8; trunc: return -2; } static int decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } /* * bgp_attr_get_as_size * * Try to find the size of the ASs encoded in an as-path. It is not obvious, as * both Old speakers that do not support 4 byte AS, and the new speakers that do * support, exchange AS-Path with the same path-attribute type value 0x02. */ static int bgp_attr_get_as_size(netdissect_options *ndo, uint8_t bgpa_type, const u_char *pptr, int len) { const u_char *tptr = pptr; /* * If the path attribute is the optional AS4 path type, then we already * know, that ASs must be encoded in 4 byte format. */ if (bgpa_type == BGPTYPE_AS4_PATH) { return 4; } /* * Let us assume that ASs are of 2 bytes in size, and check if the AS-Path * TLV is good. If not, ask the caller to try with AS encoded as 4 bytes * each. */ while (tptr < pptr + len) { ND_TCHECK(tptr[0]); /* * If we do not find a valid segment type, our guess might be wrong. */ if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) { goto trunc; } ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * 2; } /* * If we correctly reached end of the AS path attribute data content, * then most likely ASs were indeed encoded as 2 bytes. */ if (tptr == pptr + len) { return 2; } trunc: /* * We can come here, either we did not have enough data, or if we * try to decode 4 byte ASs in 2 byte format. Either way, return 4, * so that calller can try to decode each AS as of 4 bytes. If indeed * there was not enough data, it will crib and end the parse anyways. */ return 4; } static int bgp_attr_print(netdissect_options *ndo, u_int atype, const u_char *pptr, u_int len) { int i; uint16_t af; uint8_t safi, snpa, nhlen; union { /* copy buffer for bandwidth values */ float f; uint32_t i; } bw; int advance; u_int tlen; const u_char *tptr; char buf[MAXHOSTNAMELEN + 100]; int as_size; tptr = pptr; tlen=len; switch (atype) { case BGPTYPE_ORIGIN: if (len != 1) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK(*tptr); ND_PRINT((ndo, "%s", tok2str(bgp_origin_values, "Unknown Origin Typecode", tptr[0]))); } break; /* * Process AS4 byte path and AS2 byte path attributes here. */ case BGPTYPE_AS4_PATH: case BGPTYPE_AS_PATH: if (len % 2) { ND_PRINT((ndo, "invalid len")); break; } if (!len) { ND_PRINT((ndo, "empty")); break; } /* * BGP updates exchanged between New speakers that support 4 * byte AS, ASs are always encoded in 4 bytes. There is no * definitive way to find this, just by the packet's * contents. So, check for packet's TLV's sanity assuming * 2 bytes first, and it does not pass, assume that ASs are * encoded in 4 bytes format and move on. */ as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); while (tptr < pptr + len) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values, "?", tptr[0]))); for (i = 0; i < tptr[1] * as_size; i += as_size) { ND_TCHECK2(tptr[2 + i], as_size); ND_PRINT((ndo, "%s ", as_printf(ndo, astostr, sizeof(astostr), as_size == 2 ? EXTRACT_16BITS(&tptr[2 + i]) : EXTRACT_32BITS(&tptr[2 + i])))); } ND_TCHECK(tptr[0]); ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values, "?", tptr[0]))); ND_TCHECK(tptr[1]); tptr += 2 + tptr[1] * as_size; } break; case BGPTYPE_NEXT_HOP: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); } break; case BGPTYPE_MULTI_EXIT_DISC: case BGPTYPE_LOCAL_PREF: if (len != 4) ND_PRINT((ndo, "invalid len")); else { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr))); } break; case BGPTYPE_ATOMIC_AGGREGATE: if (len != 0) ND_PRINT((ndo, "invalid len")); break; case BGPTYPE_AGGREGATOR: /* * Depending on the AS encoded is of 2 bytes or of 4 bytes, * the length of this PA can be either 6 bytes or 8 bytes. */ if (len != 6 && len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], len); if (len == 6) { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), ipaddr_string(ndo, tptr + 2))); } else { ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); } break; case BGPTYPE_AGGREGATOR4: if (len != 8) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, " AS #%s, origin %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); break; case BGPTYPE_COMMUNITIES: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint32_t comm; ND_TCHECK2(tptr[0], 4); comm = EXTRACT_32BITS(tptr); switch (comm) { case BGP_COMMUNITY_NO_EXPORT: ND_PRINT((ndo, " NO_EXPORT")); break; case BGP_COMMUNITY_NO_ADVERT: ND_PRINT((ndo, " NO_ADVERTISE")); break; case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: ND_PRINT((ndo, " NO_EXPORT_SUBCONFED")); break; default: ND_PRINT((ndo, "%u:%u%s", (comm >> 16) & 0xffff, comm & 0xffff, (tlen>4) ? ", " : "")); break; } tlen -=4; tptr +=4; } break; case BGPTYPE_ORIGINATOR_ID: if (len != 4) { ND_PRINT((ndo, "invalid len")); break; } ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); break; case BGPTYPE_CLUSTER_LIST: if (len % 4) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "%s%s", ipaddr_string(ndo, tptr), (tlen>4) ? ", " : "")); tlen -=4; tptr +=4; } break; case BGPTYPE_MP_REACH_NLRI: ND_TCHECK2(tptr[0], 3); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): case (AFNUM_VPLS<<8 | SAFNUM_VPLS): break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); goto done; break; } tptr +=3; ND_TCHECK(tptr[0]); nhlen = tptr[0]; tlen = nhlen; tptr++; if (tlen) { int nnh = 0; ND_PRINT((ndo, "\n\t nexthop: ")); while (tlen > 0) { if ( nnh++ > 0 ) { ND_PRINT((ndo, ", " )); } switch(af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): case (AFNUM_INET<<8 | SAFNUM_MDT): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr))); tlen -= sizeof(struct in_addr); tptr += sizeof(struct in_addr); } break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): if (tlen < (int)sizeof(struct in6_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr))); tlen -= sizeof(struct in6_addr); tptr += sizeof(struct in6_addr); } break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); } break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < (int)sizeof(struct in_addr)) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], sizeof(struct in_addr)); ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr))); tlen -= (sizeof(struct in_addr)); tptr += (sizeof(struct in_addr)); } break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen))); tptr += tlen; tlen = 0; break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): if (tlen < BGP_VPN_RD_LEN+1) { ND_PRINT((ndo, "invalid len")); tlen = 0; } else { ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "RD: %s, %s", bgp_vpn_rd_print(ndo, tptr), isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); /* rfc986 mapped IPv4 address ? */ if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); /* rfc1888 mapped IPv6 address ? */ else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); tptr += tlen; tlen = 0; } break; default: ND_TCHECK2(tptr[0], tlen); ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); tptr += tlen; tlen = 0; goto done; break; } } } ND_PRINT((ndo, ", nh-length: %u", nhlen)); tptr += tlen; ND_TCHECK(tptr[0]); snpa = tptr[0]; tptr++; if (snpa) { ND_PRINT((ndo, "\n\t %u SNPA", snpa)); for (/*nothing*/; snpa > 0; snpa--) { ND_TCHECK(tptr[0]); ND_PRINT((ndo, "\n\t %d bytes", tptr[0])); tptr += tptr[0] + 1; } } else { ND_PRINT((ndo, ", no SNPA")); } while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*tptr,tlen); ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } done: break; case BGPTYPE_MP_UNREACH_NLRI: ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); af = EXTRACT_16BITS(tptr); safi = tptr[2]; ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)", tok2str(af_values, "Unknown AFI", af), af, (safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */ tok2str(bgp_safi_values, "Unknown SAFI", safi), safi)); if (len == BGP_MP_NLRI_MINSIZE) ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); tptr += 3; while (len - (tptr - pptr) > 0) { switch (af<<8 | safi) { case (AFNUM_INET<<8 | SAFNUM_UNICAST): case (AFNUM_INET<<8 | SAFNUM_MULTICAST): case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_UNICAST): case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else if (advance == -3) break; /* bytes left, but not enough */ else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_VPLS<<8 | SAFNUM_VPLS): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MDT): advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); if (advance == -1) ND_PRINT((ndo, "\n\t (illegal prefix length)")); else if (advance == -2) goto trunc; else ND_PRINT((ndo, "\n\t %s", buf)); break; default: ND_TCHECK2(*(tptr-3),tlen); ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tptr-3, "\n\t ", tlen); advance = 0; tptr = pptr + len; break; } if (advance < 0) break; tptr += advance; } break; case BGPTYPE_EXTD_COMMUNITIES: if (len % 8) { ND_PRINT((ndo, "invalid len")); break; } while (tlen>0) { uint16_t extd_comm; ND_TCHECK2(tptr[0], 2); extd_comm=EXTRACT_16BITS(tptr); ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]", tok2str(bgp_extd_comm_subtype_values, "unknown extd community typecode", extd_comm), extd_comm, bittok2str(bgp_extd_comm_flag_values, "none", extd_comm))); ND_TCHECK2(*(tptr+2), 6); switch(extd_comm) { case BGP_EXT_COM_RT_0: case BGP_EXT_COM_RO_0: case BGP_EXT_COM_L2VPN_RT_0: ND_PRINT((ndo, ": %u:%u (= %s)", EXTRACT_16BITS(tptr+2), EXTRACT_32BITS(tptr+4), ipaddr_string(ndo, tptr+4))); break; case BGP_EXT_COM_RT_1: case BGP_EXT_COM_RO_1: case BGP_EXT_COM_L2VPN_RT_1: case BGP_EXT_COM_VRF_RT_IMP: ND_PRINT((ndo, ": %s:%u", ipaddr_string(ndo, tptr+2), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_RT_2: case BGP_EXT_COM_RO_2: ND_PRINT((ndo, ": %s:%u", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); break; case BGP_EXT_COM_LINKBAND: bw.i = EXTRACT_32BITS(tptr+2); ND_PRINT((ndo, ": bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case BGP_EXT_COM_VPN_ORIGIN: case BGP_EXT_COM_VPN_ORIGIN2: case BGP_EXT_COM_VPN_ORIGIN3: case BGP_EXT_COM_VPN_ORIGIN4: case BGP_EXT_COM_OSPF_RID: case BGP_EXT_COM_OSPF_RID2: ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2))); break; case BGP_EXT_COM_OSPF_RTYPE: case BGP_EXT_COM_OSPF_RTYPE2: ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s", ipaddr_string(ndo, tptr+2), tok2str(bgp_extd_comm_ospf_rtype_values, "unknown (0x%02x)", *(tptr+6)), (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "", ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : "")); break; case BGP_EXT_COM_L2INFO: ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u", tok2str(l2vpn_encaps_values, "unknown encaps", *(tptr+2)), *(tptr+3), EXTRACT_16BITS(tptr+4))); break; case BGP_EXT_COM_SOURCE_AS: ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2))); break; default: ND_TCHECK2(*tptr,8); print_unknown_data(ndo, tptr, "\n\t ", 8); break; } tlen -=8; tptr +=8; } break; case BGPTYPE_PMSI_TUNNEL: { uint8_t tunnel_type, flags; tunnel_type = *(tptr+1); flags = *tptr; tlen = len; ND_TCHECK2(tptr[0], 5); ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u", tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type), tunnel_type, bittok2str(bgp_pmsi_flag_values, "none", flags), EXTRACT_24BITS(tptr+2)>>4)); tptr +=5; tlen -= 5; switch (tunnel_type) { case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ case BGP_PMSI_TUNNEL_PIM_BIDIR: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Sender %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_PIM_SSM: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s", ipaddr_string(ndo, tptr), ipaddr_string(ndo, tptr+4))); break; case BGP_PMSI_TUNNEL_INGRESS: ND_TCHECK2(tptr[0], 4); ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s", ipaddr_string(ndo, tptr))); break; case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ case BGP_PMSI_TUNNEL_LDP_MP2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; case BGP_PMSI_TUNNEL_RSVP_P2MP: ND_TCHECK2(tptr[0], 8); ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr+4))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr, "\n\t ", tlen); } } break; } case BGPTYPE_AIGP: { uint8_t type; uint16_t length; ND_TCHECK2(tptr[0], 3); tlen = len; while (tlen >= 3) { type = *tptr; length = EXTRACT_16BITS(tptr+1); ND_PRINT((ndo, "\n\t %s TLV (%u), length %u", tok2str(bgp_aigp_values, "Unknown", type), type, length)); /* * Check if we can read the TLV data. */ ND_TCHECK2(tptr[3], length - 3); switch (type) { case BGP_AIGP_TLV: ND_TCHECK2(tptr[3], 8); ND_PRINT((ndo, ", metric %" PRIu64, EXTRACT_64BITS(tptr+3))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo, tptr+3,"\n\t ", length-3); } } tptr += length; tlen -= length; } break; } case BGPTYPE_ATTR_SET: ND_TCHECK2(tptr[0], 4); if (len < 4) goto trunc; ND_PRINT((ndo, "\n\t Origin AS: %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); tptr+=4; len -=4; while (len) { u_int aflags, alenlen, alen; ND_TCHECK2(tptr[0], 2); if (len < 2) goto trunc; aflags = *tptr; atype = *(tptr + 1); tptr += 2; len -= 2; alenlen = bgp_attr_lenlen(aflags, tptr); ND_TCHECK2(tptr[0], alenlen); if (len < alenlen) goto trunc; alen = bgp_attr_len(aflags, tptr); tptr += alenlen; len -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } /* FIXME check for recursion */ if (!bgp_attr_print(ndo, atype, tptr, alen)) return 0; tptr += alen; len -= alen; } break; case BGPTYPE_LARGE_COMMUNITY: if (len == 0 || len % 12) { ND_PRINT((ndo, "invalid len")); break; } ND_PRINT((ndo, "\n\t ")); while (len > 0) { ND_TCHECK2(*tptr, 12); ND_PRINT((ndo, "%u:%u:%u%s", EXTRACT_32BITS(tptr), EXTRACT_32BITS(tptr + 4), EXTRACT_32BITS(tptr + 8), (len > 12) ? ", " : "")); tptr += 12; len -= 12; } break; default: ND_TCHECK2(*pptr,len); ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */ if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, pptr, "\n\t ", len); break; } if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ ND_TCHECK2(*pptr,len); print_unknown_data(ndo, pptr, "\n\t ", len); } return 1; trunc: return 0; } static void bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_open_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_open bgpo; struct bgp_opt bgpopt; const u_char *opt; int i; ND_TCHECK2(dat[0], BGP_OPEN_SIZE); memcpy(&bgpo, dat, BGP_OPEN_SIZE); ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version)); ND_PRINT((ndo, "my AS %s, ", as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas)))); ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime))); ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id))); ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen)); /* some little sanity checking */ if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE) return; /* ugly! */ opt = &((const struct bgp_open *)dat)->bgpo_optlen; opt++; i = 0; while (i < bgpo.bgpo_optlen) { ND_TCHECK2(opt[i], BGP_OPT_SIZE); memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE); if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) { ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len)); break; } ND_PRINT((ndo, "\n\t Option %s (%u), length: %u", tok2str(bgp_opt_values,"Unknown", bgpopt.bgpopt_type), bgpopt.bgpopt_type, bgpopt.bgpopt_len)); /* now let's decode the options we know*/ switch(bgpopt.bgpopt_type) { case BGP_OPT_CAP: bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE], bgpopt.bgpopt_len); break; case BGP_OPT_AUTH: default: ND_PRINT((ndo, "\n\t no decoder for option %u", bgpopt.bgpopt_type)); break; } i += BGP_OPT_SIZE + bgpopt.bgpopt_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_update_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; const u_char *p; int withdrawn_routes_len; int len; int i; ND_TCHECK2(dat[0], BGP_SIZE); if (length < BGP_SIZE) goto trunc; memcpy(&bgp, dat, BGP_SIZE); p = dat + BGP_SIZE; /*XXX*/ length -= BGP_SIZE; /* Unfeasible routes */ ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; withdrawn_routes_len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len) { /* * Without keeping state from the original NLRI message, * it's not possible to tell if this a v4 or v6 route, * so only try to decode it if we're not v6 enabled. */ ND_TCHECK2(p[0], withdrawn_routes_len); if (length < withdrawn_routes_len) goto trunc; ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len)); p += withdrawn_routes_len; length -= withdrawn_routes_len; } ND_TCHECK2(p[0], 2); if (length < 2) goto trunc; len = EXTRACT_16BITS(p); p += 2; length -= 2; if (withdrawn_routes_len == 0 && len == 0 && length == 0) { /* No withdrawn routes, no path attributes, no NLRI */ ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)")); return; } if (len) { /* do something more useful!*/ while (len) { int aflags, atype, alenlen, alen; ND_TCHECK2(p[0], 2); if (len < 2) goto trunc; if (length < 2) goto trunc; aflags = *p; atype = *(p + 1); p += 2; len -= 2; length -= 2; alenlen = bgp_attr_lenlen(aflags, p); ND_TCHECK2(p[0], alenlen); if (len < alenlen) goto trunc; if (length < alenlen) goto trunc; alen = bgp_attr_len(aflags, p); p += alenlen; len -= alenlen; length -= alenlen; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_attr_values, "Unknown Attribute", atype), atype, alen)); if (aflags) { ND_PRINT((ndo, ", Flags [%s%s%s%s", aflags & 0x80 ? "O" : "", aflags & 0x40 ? "T" : "", aflags & 0x20 ? "P" : "", aflags & 0x10 ? "E" : "")); if (aflags & 0xf) ND_PRINT((ndo, "+%x", aflags & 0xf)); ND_PRINT((ndo, "]: ")); } if (len < alen) goto trunc; if (length < alen) goto trunc; if (!bgp_attr_print(ndo, atype, p, alen)) goto trunc; p += alen; len -= alen; length -= alen; } } if (length) { /* * XXX - what if they're using the "Advertisement of * Multiple Paths in BGP" feature: * * https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/ * * http://tools.ietf.org/html/draft-ietf-idr-add-paths-06 */ ND_PRINT((ndo, "\n\t Updated routes:")); while (length) { char buf[MAXHOSTNAMELEN + 100]; i = decode_prefix4(ndo, p, length, buf, sizeof(buf)); if (i == -1) { ND_PRINT((ndo, "\n\t (illegal prefix length)")); break; } else if (i == -2) goto trunc; else if (i == -3) goto trunc; /* bytes left, but not enough */ else { ND_PRINT((ndo, "\n\t %s", buf)); p += i; length -= i; } } } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_notification_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp_notification bgpn; const u_char *tptr; uint8_t shutdown_comm_length; uint8_t remainder_offset; ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE); memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE); /* some little sanity checking */ if (length<BGP_NOTIFICATION_SIZE) return; ND_PRINT((ndo, ", %s (%u)", tok2str(bgp_notify_major_values, "Unknown Error", bgpn.bgpn_major), bgpn.bgpn_major)); switch (bgpn.bgpn_major) { case BGP_NOTIFY_MAJOR_MSG: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_msg_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_OPEN: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_open_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_UPDATE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_update_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_FSM: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_fsm_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CAP: ND_PRINT((ndo, " subcode %s (%u)", tok2str(bgp_notify_minor_cap_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); break; case BGP_NOTIFY_MAJOR_CEASE: ND_PRINT((ndo, ", subcode %s (%u)", tok2str(bgp_notify_minor_cease_values, "Unknown", bgpn.bgpn_minor), bgpn.bgpn_minor)); /* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes * for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES */ if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 7); ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u", tok2str(af_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr), tok2str(bgp_safi_values, "Unknown", *(tptr+2)), *(tptr+2), EXTRACT_32BITS(tptr+3))); } /* * draft-ietf-idr-shutdown describes a method to send a communication * intended for human consumption regarding the Administrative Shutdown */ if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT || bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) && length >= BGP_NOTIFICATION_SIZE + 1) { tptr = dat + BGP_NOTIFICATION_SIZE; ND_TCHECK2(*tptr, 1); shutdown_comm_length = *(tptr); remainder_offset = 0; /* garbage, hexdump it all */ if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN || shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) { ND_PRINT((ndo, ", invalid Shutdown Communication length")); } else if (shutdown_comm_length == 0) { ND_PRINT((ndo, ", empty Shutdown Communication")); remainder_offset += 1; } /* a proper shutdown communication */ else { ND_TCHECK2(*(tptr+1), shutdown_comm_length); ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length)); (void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL); ND_PRINT((ndo, "\"")); remainder_offset += shutdown_comm_length + 1; } /* if there is trailing data, hexdump it */ if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) { ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE))); hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE)); } } break; default: break; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static void bgp_route_refresh_print(netdissect_options *ndo, const u_char *pptr, int len) { const struct bgp_route_refresh *bgp_route_refresh_header; ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE); /* some little sanity checking */ if (len<BGP_ROUTE_REFRESH_SIZE) return; bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr; ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)", tok2str(af_values,"Unknown", /* this stinks but the compiler pads the structure * weird */ EXTRACT_16BITS(&bgp_route_refresh_header->afi)), EXTRACT_16BITS(&bgp_route_refresh_header->afi), tok2str(bgp_safi_values,"Unknown", bgp_route_refresh_header->safi), bgp_route_refresh_header->safi)); if (ndo->ndo_vflag > 1) { ND_TCHECK2(*pptr, len); print_unknown_data(ndo, pptr, "\n\t ", len); } return; trunc: ND_PRINT((ndo, "[|BGP]")); } static int bgp_header_print(netdissect_options *ndo, const u_char *dat, int length) { struct bgp bgp; ND_TCHECK2(dat[0], BGP_SIZE); memcpy(&bgp, dat, BGP_SIZE); ND_PRINT((ndo, "\n\t%s Message (%u), length: %u", tok2str(bgp_msg_values, "Unknown", bgp.bgp_type), bgp.bgp_type, length)); switch (bgp.bgp_type) { case BGP_OPEN: bgp_open_print(ndo, dat, length); break; case BGP_UPDATE: bgp_update_print(ndo, dat, length); break; case BGP_NOTIFICATION: bgp_notification_print(ndo, dat, length); break; case BGP_KEEPALIVE: break; case BGP_ROUTE_REFRESH: bgp_route_refresh_print(ndo, dat, length); break; default: /* we have no decoder for the BGP message */ ND_TCHECK2(*dat, length); ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type)); print_unknown_data(ndo, dat, "\n\t ", length); break; } return 1; trunc: ND_PRINT((ndo, "[|BGP]")); return 0; } void bgp_print(netdissect_options *ndo, const u_char *dat, int length) { const u_char *p; const u_char *ep; const u_char *start; const u_char marker[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; struct bgp bgp; uint16_t hlen; ep = dat + length; if (ndo->ndo_snapend < dat + length) ep = ndo->ndo_snapend; ND_PRINT((ndo, ": BGP")); if (ndo->ndo_vflag < 1) /* lets be less chatty */ return; p = dat; start = p; while (p < ep) { if (!ND_TTEST2(p[0], 1)) break; if (p[0] != 0xff) { p++; continue; } if (!ND_TTEST2(p[0], sizeof(marker))) break; if (memcmp(p, marker, sizeof(marker)) != 0) { p++; continue; } /* found BGP header */ ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/ memcpy(&bgp, p, BGP_SIZE); if (start != p) ND_PRINT((ndo, " [|BGP]")); hlen = ntohs(bgp.bgp_len); if (hlen < BGP_SIZE) { ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen, BGP_SIZE)); break; } if (ND_TTEST2(p[0], hlen)) { if (!bgp_header_print(ndo, p, hlen)) return; p += hlen; start = p; } else { ND_PRINT((ndo, "\n[|BGP %s]", tok2str(bgp_msg_values, "Unknown Message Type", bgp.bgp_type))); break; } } return; trunc: ND_PRINT((ndo, " [|BGP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2664_0
crossvul-cpp_data_bad_3907_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { WINPR_UNUSED(update); if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; if (update->autoCalculateBitmapData) { bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %" PRIu32 "", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*)realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int)bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int)palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static BOOL update_read_synchronize(rdpUpdate* update, wStream* s) { WINPR_UNUSED(update); return Stream_SafeSeek(s, 2); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp) { BYTE* newMask; UINT32 scanlineSize; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum of 96 for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > 96) || (pointer_color->height > 96)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } static BOOL _update_read_pointer_large(wStream* s, POINTER_LARGE_UPDATE* pointer) { BYTE* newMask; UINT32 scanlineSize; if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer->xorBpp); Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotX); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer->hotSpotY); /* yPos (2 bytes) */ Stream_Read_UINT16(s, pointer->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer->height); /* height (2 bytes) */ if ((pointer->width > 384) || (pointer->height > 384)) goto fail; Stream_Read_UINT16(s, pointer->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer->lengthXorMask); /* lengthXorMask (2 bytes) */ if (pointer->hotSpotX >= pointer->width) pointer->hotSpotX = 0; if (pointer->hotSpotY >= pointer->height) pointer->hotSpotY = 0; if (pointer->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will * consume 10 bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to * the next even number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer->lengthXorMask) goto fail; scanlineSize = (7 + pointer->xorBpp * pointer->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%" PRIu32 " height=%" PRIu32 ", %" PRIu32 " instead of %" PRIu32 "", pointer->width, pointer->height, pointer->lengthXorMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->xorMaskData, pointer->lengthXorMask); if (!newMask) goto fail; pointer->xorMaskData = newMask; Stream_Read(s, pointer->xorMaskData, pointer->lengthXorMask); } if (pointer->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will * consume 2 bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even * number of bytes). */ if (Stream_GetRemainingLength(s) < pointer->lengthAndMask) goto fail; scanlineSize = ((7 + pointer->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer->height != pointer->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %" PRIu32 " instead of %" PRIu32 "", pointer->lengthAndMask, scanlineSize * pointer->height); goto fail; } newMask = realloc(pointer->andMaskData, pointer->lengthAndMask); if (!newMask) goto fail; pointer->andMaskData = newMask; Stream_Read(s, pointer->andMaskData, pointer->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_LARGE_UPDATE* update_read_pointer_large(rdpUpdate* update, wStream* s) { POINTER_LARGE_UPDATE* pointer = calloc(1, sizeof(POINTER_LARGE_UPDATE)); if (!pointer) goto fail; if (!_update_read_pointer_large(s, pointer)) goto fail; return pointer; fail: free_pointer_large_update(update->context, pointer); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %" PRIu32 "", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER_LARGE: { POINTER_LARGE_UPDATE* pointer_large = update_read_pointer_large(update, s); if (pointer_large) { rc = IFCALLRESULT(FALSE, pointer->PointerLarge, context, pointer_large); free_pointer_large_update(context, pointer_large); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", UPDATE_TYPE_STRINGS[updateType]); if (!update_begin_paint(update)) goto fail; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); goto fail; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: if (!update_read_synchronize(update, s)) goto fail; rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } fail: if (!update_end_paint(update)) rc = FALSE; if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%" PRIu16 "] failed", update_type_to_string(updateType), updateType); return FALSE; } return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL _update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) { if (!update_end_paint(update)) return FALSE; } s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL _update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_DBG(TAG, "sending %" PRIu16 " orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update_end_paint(update); update_begin_paint(update); } } static void update_force_flush(rdpContext* context) { update_flush(context); } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update_begin_paint(update); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } static BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } static BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } static int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]; length += update_prepare_bounds(context, orderInfo); return length; } static int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, size_t offset) { size_t position; WINPR_UNUSED(context); position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order( cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order( cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order(create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order(rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_large(wStream* s, const POINTER_LARGE_UPDATE* pointer) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer->lengthAndMask + pointer->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer->xorBpp); Stream_Write_UINT16(s, pointer->cacheIndex); Stream_Write_UINT16(s, pointer->hotSpotX); Stream_Write_UINT16(s, pointer->hotSpotY); Stream_Write_UINT16(s, pointer->width); Stream_Write_UINT16(s, pointer->height); Stream_Write_UINT32(s, pointer->lengthAndMask); Stream_Write_UINT32(s, pointer->lengthXorMask); Stream_Write(s, pointer->xorMaskData, pointer->lengthXorMask); Stream_Write(s, pointer->andMaskData, pointer->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_large(rdpContext* context, const POINTER_LARGE_UPDATE* pointer) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_large(s, pointer)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_LARGE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t)numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*)calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { RECTANGLE_16* prect = NULL; RECTANGLE_16 rect = { 0 }; BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0) { if (Stream_GetRemainingLength(s) < sizeof(RECTANGLE_16)) return FALSE; Stream_Read_UINT16(s, rect.left); Stream_Read_UINT16(s, rect.top); Stream_Read_UINT16(s, rect.right); Stream_Read_UINT16(s, rect.bottom); prect = &rect; } if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, prect); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } static UINT16 update_calculate_new_or_existing_window(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { UINT16 orderSize = 11; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) orderSize += 2 + stateOrder->titleInfo.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) orderSize += 2 + stateOrder->numWindowRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) orderSize += 8; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) orderSize += 2 + stateOrder->numVisibilityRects * sizeof(RECTANGLE_16); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) orderSize += 2 + stateOrder->OverlayDescription.length; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) orderSize += 1; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) orderSize += 1; return orderSize; } static BOOL update_send_new_or_existing_window(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_new_or_existing_window(orderInfo, stateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) != 0) Stream_Write_UINT32(s, stateOrder->ownerWindowId); if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) != 0) { Stream_Write_UINT32(s, stateOrder->style); Stream_Write_UINT32(s, stateOrder->extendedStyle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) != 0) { Stream_Write_UINT8(s, stateOrder->showState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) != 0) { Stream_Write_UINT16(s, stateOrder->titleInfo.length); Stream_Write(s, stateOrder->titleInfo.string, stateOrder->titleInfo.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->clientOffsetX); Stream_Write_INT32(s, stateOrder->clientOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->clientAreaWidth); Stream_Write_UINT32(s, stateOrder->clientAreaHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginLeft); Stream_Write_UINT32(s, stateOrder->resizeMarginRight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) != 0) { Stream_Write_UINT32(s, stateOrder->resizeMarginTop); Stream_Write_UINT32(s, stateOrder->resizeMarginBottom); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) != 0) { Stream_Write_UINT8(s, stateOrder->RPContent); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) != 0) { Stream_Write_UINT32(s, stateOrder->rootParentHandle); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) != 0) { Stream_Write_INT32(s, stateOrder->windowOffsetX); Stream_Write_INT32(s, stateOrder->windowOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) != 0) { Stream_Write_INT32(s, stateOrder->windowClientDeltaX); Stream_Write_INT32(s, stateOrder->windowClientDeltaY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) != 0) { Stream_Write_UINT32(s, stateOrder->windowWidth); Stream_Write_UINT32(s, stateOrder->windowHeight); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) != 0) { Stream_Write_UINT16(s, stateOrder->numWindowRects); Stream_Write(s, stateOrder->windowRects, stateOrder->numWindowRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) != 0) { Stream_Write_UINT32(s, stateOrder->visibleOffsetX); Stream_Write_UINT32(s, stateOrder->visibleOffsetY); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) != 0) { Stream_Write_UINT16(s, stateOrder->numVisibilityRects); Stream_Write(s, stateOrder->visibilityRects, stateOrder->numVisibilityRects * sizeof(RECTANGLE_16)); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION) != 0) { Stream_Write_UINT16(s, stateOrder->OverlayDescription.length); Stream_Write(s, stateOrder->OverlayDescription.string, stateOrder->OverlayDescription.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON) != 0) { Stream_Write_UINT8(s, stateOrder->TaskbarButton); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER) != 0) { Stream_Write_UINT8(s, stateOrder->EnforceServerZOrder); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarState); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE) != 0) { Stream_Write_UINT8(s, stateOrder->AppBarEdge); } update->numberOrders++; return TRUE; } static BOOL update_send_window_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static BOOL update_send_window_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_STATE_ORDER* stateOrder) { return update_send_new_or_existing_window(context, orderInfo, stateOrder); } static UINT16 update_calculate_window_icon_order(const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { UINT16 orderSize = 23; ICON_INFO* iconInfo = iconOrder->iconInfo; orderSize += iconInfo->cbBitsColor + iconInfo->cbBitsMask; if (iconInfo->bpp <= 8) orderSize += 2 + iconInfo->cbColorTable; return orderSize; } static BOOL update_send_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_ICON_ORDER* iconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); ICON_INFO* iconInfo = iconOrder->iconInfo; UINT16 orderSize = update_calculate_window_icon_order(orderInfo, iconOrder); update_check_flush(context, orderSize); s = update->us; if (!s || !iconInfo) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, iconInfo->cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo->cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo->bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo->width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo->height); /* Height (2 bytes) */ if (iconInfo->bpp <= 8) { Stream_Write_UINT16(s, iconInfo->cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo->cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo->cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo->bitsMask, iconInfo->cbBitsMask); /* BitsMask (variable) */ if (iconInfo->bpp <= 8) { Stream_Write(s, iconInfo->colorTable, iconInfo->cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo->bitsColor, iconInfo->cbBitsColor); /* BitsColor (variable) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const WINDOW_CACHED_ICON_ORDER* cachedIconOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 14; CACHED_ICON_INFO cachedIcon = cachedIconOrder->cachedIcon; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ /* Write body */ Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ update->numberOrders++; return TRUE; } static BOOL update_send_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 11; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_new_or_existing_notification_icons_order( const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { UINT16 orderSize = 15; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) orderSize += 4; if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { orderSize += 2 + iconStateOrder->toolTip.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; orderSize += 12 + infoTip.text.length + infoTip.title.length; } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { orderSize += 4; } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; orderSize += 12; if (iconInfo.bpp <= 8) orderSize += 2 + iconInfo.cbColorTable; orderSize += iconInfo.cbBitsMask + iconInfo.cbBitsColor; } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { orderSize += 3; } return orderSize; } static BOOL update_send_new_or_existing_notification_icons(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); BOOL versionFieldPresent = FALSE; UINT16 orderSize = update_calculate_new_or_existing_notification_icons_order(orderInfo, iconStateOrder); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, orderSize)) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_INT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ /* Write body */ if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) != 0) { versionFieldPresent = TRUE; Stream_Write_UINT32(s, iconStateOrder->version); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) != 0) { Stream_Write_UINT16(s, iconStateOrder->toolTip.length); Stream_Write(s, iconStateOrder->toolTip.string, iconStateOrder->toolTip.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) != 0) { NOTIFY_ICON_INFOTIP infoTip = iconStateOrder->infoTip; /* info tip should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, infoTip.timeout); /* Timeout (4 bytes) */ Stream_Write_UINT32(s, infoTip.flags); /* InfoFlags (4 bytes) */ Stream_Write_UINT16(s, infoTip.text.length); /* InfoTipText (variable) */ Stream_Write(s, infoTip.text.string, infoTip.text.length); Stream_Write_UINT16(s, infoTip.title.length); /* Title (variable) */ Stream_Write(s, infoTip.title.string, infoTip.title.length); } if ((orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) != 0) { /* notify state should not be sent when version is 0 */ if (versionFieldPresent && iconStateOrder->version == 0) return FALSE; Stream_Write_UINT32(s, iconStateOrder->state); } if ((orderInfo->fieldFlags & WINDOW_ORDER_ICON) != 0) { ICON_INFO iconInfo = iconStateOrder->icon; Stream_Write_UINT16(s, iconInfo.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, iconInfo.cacheId); /* CacheId (1 byte) */ Stream_Write_UINT8(s, iconInfo.bpp); /* Bpp (1 byte) */ Stream_Write_UINT16(s, iconInfo.width); /* Width (2 bytes) */ Stream_Write_UINT16(s, iconInfo.height); /* Height (2 bytes) */ if (iconInfo.bpp <= 8) { Stream_Write_UINT16(s, iconInfo.cbColorTable); /* CbColorTable (2 bytes) */ } Stream_Write_UINT16(s, iconInfo.cbBitsMask); /* CbBitsMask (2 bytes) */ Stream_Write_UINT16(s, iconInfo.cbBitsColor); /* CbBitsColor (2 bytes) */ Stream_Write(s, iconInfo.bitsMask, iconInfo.cbBitsMask); /* BitsMask (variable) */ orderSize += iconInfo.cbBitsMask; if (iconInfo.bpp <= 8) { Stream_Write(s, iconInfo.colorTable, iconInfo.cbColorTable); /* ColorTable (variable) */ } Stream_Write(s, iconInfo.bitsColor, iconInfo.cbBitsColor); /* BitsColor (variable) */ } else if ((orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) != 0) { CACHED_ICON_INFO cachedIcon = iconStateOrder->cachedIcon; Stream_Write_UINT16(s, cachedIcon.cacheEntry); /* CacheEntry (2 bytes) */ Stream_Write_UINT8(s, cachedIcon.cacheId); /* CacheId (1 byte) */ } update->numberOrders++; return TRUE; } static BOOL update_send_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const NOTIFY_ICON_STATE_ORDER* iconStateOrder) { return update_send_new_or_existing_notification_icons(context, orderInfo, iconStateOrder); } static BOOL update_send_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 15; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; /* Write Hdr */ Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ Stream_Write_UINT32(s, orderInfo->windowId); /* WindowID (4 bytes) */ Stream_Write_UINT32(s, orderInfo->notifyIconId); /* NotifyIconId (4 bytes) */ update->numberOrders++; return TRUE; } static UINT16 update_calculate_monitored_desktop(const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT16 orderSize = 7; if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { orderSize += 4; } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { orderSize += 1 + (4 * monitoredDesktop->numWindowIds); } return orderSize; } static BOOL update_send_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, const MONITORED_DESKTOP_ORDER* monitoredDesktop) { UINT32 i; wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = update_calculate_monitored_desktop(orderInfo, monitoredDesktop); update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND) { Stream_Write_UINT32(s, monitoredDesktop->activeWindowId); /* activeWindowId (4 bytes) */ } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER) { Stream_Write_UINT8(s, monitoredDesktop->numWindowIds); /* numWindowIds (1 byte) */ /* windowIds */ for (i = 0; i < monitoredDesktop->numWindowIds; i++) { Stream_Write_UINT32(s, monitoredDesktop->windowIds[i]); } } update->numberOrders++; return TRUE; } static BOOL update_send_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) { wStream* s; rdpUpdate* update = context->update; BYTE controlFlags = ORDER_SECONDARY | (ORDER_TYPE_WINDOW << 2); UINT16 orderSize = 7; update_check_flush(context, orderSize); s = update->us; if (!s) return FALSE; Stream_Write_UINT8(s, controlFlags); /* Header (1 byte) */ Stream_Write_UINT16(s, orderSize); /* OrderSize (2 bytes) */ Stream_Write_UINT32(s, orderInfo->fieldFlags); /* FieldsPresentFlags (4 bytes) */ update->numberOrders++; return TRUE; } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = _update_begin_paint; update->EndPaint = _update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->ServerStatusInfo = rdp_send_server_status_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerLarge = update_send_pointer_large; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; update->window->WindowCreate = update_send_window_create; update->window->WindowUpdate = update_send_window_update; update->window->WindowIcon = update_send_window_icon; update->window->WindowCachedIcon = update_send_window_cached_icon; update->window->WindowDelete = update_send_window_delete; update->window->NotifyIconCreate = update_send_notify_icon_create; update->window->NotifyIconUpdate = update_send_notify_icon_update; update->window->NotifyIconDelete = update_send_notify_icon_delete; update->window->MonitoredDesktop = update_send_monitored_desktop; update->window->NonMonitoredDesktop = update_send_non_monitored_desktop; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->OverlayDescription.string); free(window_state->titleInfo.string); free(window_state->windowRects); free(window_state->visibilityRects); memset(window_state, 0, sizeof(WINDOW_STATE_ORDER)); } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; WINPR_UNUSED(rdp); update = (rdpUpdate*)calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); InitializeCriticalSection(&(update->mux)); update->pointer = (rdpPointerUpdate*)calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*)calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*)calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*)calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*)calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->autoCalculateBitmapData = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window); } MessageQueue_Free(update->queue); DeleteCriticalSection(&update->mux); free(update); } } BOOL update_begin_paint(rdpUpdate* update) { if (!update) return FALSE; EnterCriticalSection(&update->mux); if (!update->BeginPaint) return TRUE; return update->BeginPaint(update->context); } BOOL update_end_paint(rdpUpdate* update) { BOOL rc = FALSE; if (!update) return FALSE; if (update->EndPaint) rc = update->EndPaint(update->context); LeaveCriticalSection(&update->mux); return rc; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3907_0
crossvul-cpp_data_good_3358_0
/* * IPV6 GSO/GRO offload support * Linux INET6 implementation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <linux/socket.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/printk.h> #include <net/protocol.h> #include <net/ipv6.h> #include <net/inet_common.h> #include "ip6_offload.h" static int ipv6_gso_pull_exthdrs(struct sk_buff *skb, int proto) { const struct net_offload *ops = NULL; for (;;) { struct ipv6_opt_hdr *opth; int len; if (proto != NEXTHDR_HOP) { ops = rcu_dereference(inet6_offloads[proto]); if (unlikely(!ops)) break; if (!(ops->flags & INET6_PROTO_GSO_EXTHDR)) break; } if (unlikely(!pskb_may_pull(skb, 8))) break; opth = (void *)skb->data; len = ipv6_optlen(opth); if (unlikely(!pskb_may_pull(skb, len))) break; opth = (void *)skb->data; proto = opth->nexthdr; __skb_pull(skb, len); } return proto; } static struct sk_buff *ipv6_gso_segment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); struct ipv6hdr *ipv6h; const struct net_offload *ops; int proto; struct frag_hdr *fptr; unsigned int unfrag_ip6hlen; unsigned int payload_len; u8 *prevhdr; int offset = 0; bool encap, udpfrag; int nhoff; bool gso_partial; skb_reset_network_header(skb); nhoff = skb_network_header(skb) - skb_mac_header(skb); if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h)))) goto out; encap = SKB_GSO_CB(skb)->encap_level > 0; if (encap) features &= skb->dev->hw_enc_features; SKB_GSO_CB(skb)->encap_level += sizeof(*ipv6h); ipv6h = ipv6_hdr(skb); __skb_pull(skb, sizeof(*ipv6h)); segs = ERR_PTR(-EPROTONOSUPPORT); proto = ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr); if (skb->encapsulation && skb_shinfo(skb)->gso_type & (SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6)) udpfrag = proto == IPPROTO_UDP && encap; else udpfrag = proto == IPPROTO_UDP && !skb->encapsulation; ops = rcu_dereference(inet6_offloads[proto]); if (likely(ops && ops->callbacks.gso_segment)) { skb_reset_transport_header(skb); segs = ops->callbacks.gso_segment(skb, features); } if (IS_ERR_OR_NULL(segs)) goto out; gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL); for (skb = segs; skb; skb = skb->next) { ipv6h = (struct ipv6hdr *)(skb_mac_header(skb) + nhoff); if (gso_partial) payload_len = skb_shinfo(skb)->gso_size + SKB_GSO_CB(skb)->data_offset + skb->head - (unsigned char *)(ipv6h + 1); else payload_len = skb->len - nhoff - sizeof(*ipv6h); ipv6h->payload_len = htons(payload_len); skb->network_header = (u8 *)ipv6h - skb->head; if (udpfrag) { unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr); if (unfrag_ip6hlen < 0) return ERR_PTR(unfrag_ip6hlen); fptr = (struct frag_hdr *)((u8 *)ipv6h + unfrag_ip6hlen); fptr->frag_off = htons(offset); if (skb->next) fptr->frag_off |= htons(IP6_MF); offset += (ntohs(ipv6h->payload_len) - sizeof(struct frag_hdr)); } if (encap) skb_reset_inner_headers(skb); } out: return segs; } /* Return the total length of all the extension hdrs, following the same * logic in ipv6_gso_pull_exthdrs() when parsing ext-hdrs. */ static int ipv6_exthdrs_len(struct ipv6hdr *iph, const struct net_offload **opps) { struct ipv6_opt_hdr *opth = (void *)iph; int len = 0, proto, optlen = sizeof(*iph); proto = iph->nexthdr; for (;;) { if (proto != NEXTHDR_HOP) { *opps = rcu_dereference(inet6_offloads[proto]); if (unlikely(!(*opps))) break; if (!((*opps)->flags & INET6_PROTO_GSO_EXTHDR)) break; } opth = (void *)opth + optlen; optlen = ipv6_optlen(opth); len += optlen; proto = opth->nexthdr; } return len; } static struct sk_buff **ipv6_gro_receive(struct sk_buff **head, struct sk_buff *skb) { const struct net_offload *ops; struct sk_buff **pp = NULL; struct sk_buff *p; struct ipv6hdr *iph; unsigned int nlen; unsigned int hlen; unsigned int off; u16 flush = 1; int proto; off = skb_gro_offset(skb); hlen = off + sizeof(*iph); iph = skb_gro_header_fast(skb, off); if (skb_gro_header_hard(skb, hlen)) { iph = skb_gro_header_slow(skb, hlen, off); if (unlikely(!iph)) goto out; } skb_set_network_header(skb, off); skb_gro_pull(skb, sizeof(*iph)); skb_set_transport_header(skb, skb_gro_offset(skb)); flush += ntohs(iph->payload_len) != skb_gro_len(skb); rcu_read_lock(); proto = iph->nexthdr; ops = rcu_dereference(inet6_offloads[proto]); if (!ops || !ops->callbacks.gro_receive) { __pskb_pull(skb, skb_gro_offset(skb)); skb_gro_frag0_invalidate(skb); proto = ipv6_gso_pull_exthdrs(skb, proto); skb_gro_pull(skb, -skb_transport_offset(skb)); skb_reset_transport_header(skb); __skb_push(skb, skb_gro_offset(skb)); ops = rcu_dereference(inet6_offloads[proto]); if (!ops || !ops->callbacks.gro_receive) goto out_unlock; iph = ipv6_hdr(skb); } NAPI_GRO_CB(skb)->proto = proto; flush--; nlen = skb_network_header_len(skb); for (p = *head; p; p = p->next) { const struct ipv6hdr *iph2; __be32 first_word; /* <Version:4><Traffic_Class:8><Flow_Label:20> */ if (!NAPI_GRO_CB(p)->same_flow) continue; iph2 = (struct ipv6hdr *)(p->data + off); first_word = *(__be32 *)iph ^ *(__be32 *)iph2; /* All fields must match except length and Traffic Class. * XXX skbs on the gro_list have all been parsed and pulled * already so we don't need to compare nlen * (nlen != (sizeof(*iph2) + ipv6_exthdrs_len(iph2, &ops))) * memcmp() alone below is suffcient, right? */ if ((first_word & htonl(0xF00FFFFF)) || memcmp(&iph->nexthdr, &iph2->nexthdr, nlen - offsetof(struct ipv6hdr, nexthdr))) { NAPI_GRO_CB(p)->same_flow = 0; continue; } /* flush if Traffic Class fields are different */ NAPI_GRO_CB(p)->flush |= !!(first_word & htonl(0x0FF00000)); NAPI_GRO_CB(p)->flush |= flush; /* If the previous IP ID value was based on an atomic * datagram we can overwrite the value and ignore it. */ if (NAPI_GRO_CB(skb)->is_atomic) NAPI_GRO_CB(p)->flush_id = 0; } NAPI_GRO_CB(skb)->is_atomic = true; NAPI_GRO_CB(skb)->flush |= flush; skb_gro_postpull_rcsum(skb, iph, nlen); pp = call_gro_receive(ops->callbacks.gro_receive, head, skb); out_unlock: rcu_read_unlock(); out: skb_gro_flush_final(skb, pp, flush); return pp; } static struct sk_buff **sit_ip6ip6_gro_receive(struct sk_buff **head, struct sk_buff *skb) { /* Common GRO receive for SIT and IP6IP6 */ if (NAPI_GRO_CB(skb)->encap_mark) { NAPI_GRO_CB(skb)->flush = 1; return NULL; } NAPI_GRO_CB(skb)->encap_mark = 1; return ipv6_gro_receive(head, skb); } static struct sk_buff **ip4ip6_gro_receive(struct sk_buff **head, struct sk_buff *skb) { /* Common GRO receive for SIT and IP6IP6 */ if (NAPI_GRO_CB(skb)->encap_mark) { NAPI_GRO_CB(skb)->flush = 1; return NULL; } NAPI_GRO_CB(skb)->encap_mark = 1; return inet_gro_receive(head, skb); } static int ipv6_gro_complete(struct sk_buff *skb, int nhoff) { const struct net_offload *ops; struct ipv6hdr *iph = (struct ipv6hdr *)(skb->data + nhoff); int err = -ENOSYS; if (skb->encapsulation) { skb_set_inner_protocol(skb, cpu_to_be16(ETH_P_IPV6)); skb_set_inner_network_header(skb, nhoff); } iph->payload_len = htons(skb->len - nhoff - sizeof(*iph)); rcu_read_lock(); nhoff += sizeof(*iph) + ipv6_exthdrs_len(iph, &ops); if (WARN_ON(!ops || !ops->callbacks.gro_complete)) goto out_unlock; err = ops->callbacks.gro_complete(skb, nhoff); out_unlock: rcu_read_unlock(); return err; } static int sit_gro_complete(struct sk_buff *skb, int nhoff) { skb->encapsulation = 1; skb_shinfo(skb)->gso_type |= SKB_GSO_IPXIP4; return ipv6_gro_complete(skb, nhoff); } static int ip6ip6_gro_complete(struct sk_buff *skb, int nhoff) { skb->encapsulation = 1; skb_shinfo(skb)->gso_type |= SKB_GSO_IPXIP6; return ipv6_gro_complete(skb, nhoff); } static int ip4ip6_gro_complete(struct sk_buff *skb, int nhoff) { skb->encapsulation = 1; skb_shinfo(skb)->gso_type |= SKB_GSO_IPXIP6; return inet_gro_complete(skb, nhoff); } static struct packet_offload ipv6_packet_offload __read_mostly = { .type = cpu_to_be16(ETH_P_IPV6), .callbacks = { .gso_segment = ipv6_gso_segment, .gro_receive = ipv6_gro_receive, .gro_complete = ipv6_gro_complete, }, }; static const struct net_offload sit_offload = { .callbacks = { .gso_segment = ipv6_gso_segment, .gro_receive = sit_ip6ip6_gro_receive, .gro_complete = sit_gro_complete, }, }; static const struct net_offload ip4ip6_offload = { .callbacks = { .gso_segment = inet_gso_segment, .gro_receive = ip4ip6_gro_receive, .gro_complete = ip4ip6_gro_complete, }, }; static const struct net_offload ip6ip6_offload = { .callbacks = { .gso_segment = ipv6_gso_segment, .gro_receive = sit_ip6ip6_gro_receive, .gro_complete = ip6ip6_gro_complete, }, }; static int __init ipv6_offload_init(void) { if (tcpv6_offload_init() < 0) pr_crit("%s: Cannot add TCP protocol offload\n", __func__); if (ipv6_exthdrs_offload_init() < 0) pr_crit("%s: Cannot add EXTHDRS protocol offload\n", __func__); dev_add_offload(&ipv6_packet_offload); inet_add_offload(&sit_offload, IPPROTO_IPV6); inet6_add_offload(&ip6ip6_offload, IPPROTO_IPV6); inet6_add_offload(&ip4ip6_offload, IPPROTO_IPIP); return 0; } fs_initcall(ipv6_offload_init);
./CrossVul/dataset_final_sorted/CWE-125/c/good_3358_0
crossvul-cpp_data_bad_932_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L) #endif for (y=0; y < (ssize_t) Cr_image->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) Cr_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]); Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]); Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register Quantum *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register Quantum *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_932_0
crossvul-cpp_data_bad_3032_0
/* * linux/kernel/posix-timers.c * * * 2002-10-15 Posix Clocks & timers * by George Anzinger george@mvista.com * * Copyright (C) 2002 2003 by MontaVista Software. * * 2004-06-01 Fix CLOCK_REALTIME clock/timer TIMER_ABSTIME bug. * Copyright (C) 2004 Boris Hu * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * MontaVista Software | 1237 East Arques Avenue | Sunnyvale | CA 94085 | USA */ /* These are all the functions necessary to implement * POSIX clocks & timers */ #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/time.h> #include <linux/mutex.h> #include <linux/sched/task.h> #include <linux/uaccess.h> #include <linux/list.h> #include <linux/init.h> #include <linux/compiler.h> #include <linux/hash.h> #include <linux/posix-clock.h> #include <linux/posix-timers.h> #include <linux/syscalls.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <linux/export.h> #include <linux/hashtable.h> #include <linux/compat.h> #include "timekeeping.h" #include "posix-timers.h" /* * Management arrays for POSIX timers. Timers are now kept in static hash table * with 512 entries. * Timer ids are allocated by local routine, which selects proper hash head by * key, constructed from current->signal address and per signal struct counter. * This keeps timer ids unique per process, but now they can intersect between * processes. */ /* * Lets keep our timers in a slab cache :-) */ static struct kmem_cache *posix_timers_cache; static DEFINE_HASHTABLE(posix_timers_hashtable, 9); static DEFINE_SPINLOCK(hash_lock); static const struct k_clock * const posix_clocks[]; static const struct k_clock *clockid_to_kclock(const clockid_t id); static const struct k_clock clock_realtime, clock_monotonic; /* * we assume that the new SIGEV_THREAD_ID shares no bits with the other * SIGEV values. Here we put out an error if this assumption fails. */ #if SIGEV_THREAD_ID != (SIGEV_THREAD_ID & \ ~(SIGEV_SIGNAL | SIGEV_NONE | SIGEV_THREAD)) #error "SIGEV_THREAD_ID must not share bit with other SIGEV values!" #endif /* * parisc wants ENOTSUP instead of EOPNOTSUPP */ #ifndef ENOTSUP # define ENANOSLEEP_NOTSUP EOPNOTSUPP #else # define ENANOSLEEP_NOTSUP ENOTSUP #endif /* * The timer ID is turned into a timer address by idr_find(). * Verifying a valid ID consists of: * * a) checking that idr_find() returns other than -1. * b) checking that the timer id matches the one in the timer itself. * c) that the timer owner is in the callers thread group. */ /* * CLOCKs: The POSIX standard calls for a couple of clocks and allows us * to implement others. This structure defines the various * clocks. * * RESOLUTION: Clock resolution is used to round up timer and interval * times, NOT to report clock times, which are reported with as * much resolution as the system can muster. In some cases this * resolution may depend on the underlying clock hardware and * may not be quantifiable until run time, and only then is the * necessary code is written. The standard says we should say * something about this issue in the documentation... * * FUNCTIONS: The CLOCKs structure defines possible functions to * handle various clock functions. * * The standard POSIX timer management code assumes the * following: 1.) The k_itimer struct (sched.h) is used for * the timer. 2.) The list, it_lock, it_clock, it_id and * it_pid fields are not modified by timer code. * * Permissions: It is assumed that the clock_settime() function defined * for each clock will take care of permission checks. Some * clocks may be set able by any user (i.e. local process * clocks) others not. Currently the only set able clock we * have is CLOCK_REALTIME and its high res counter part, both of * which we beg off on and pass to do_sys_settimeofday(). */ static struct k_itimer *__lock_timer(timer_t timer_id, unsigned long *flags); #define lock_timer(tid, flags) \ ({ struct k_itimer *__timr; \ __cond_lock(&__timr->it_lock, __timr = __lock_timer(tid, flags)); \ __timr; \ }) static int hash(struct signal_struct *sig, unsigned int nr) { return hash_32(hash32_ptr(sig) ^ nr, HASH_BITS(posix_timers_hashtable)); } static struct k_itimer *__posix_timers_find(struct hlist_head *head, struct signal_struct *sig, timer_t id) { struct k_itimer *timer; hlist_for_each_entry_rcu(timer, head, t_hash) { if ((timer->it_signal == sig) && (timer->it_id == id)) return timer; } return NULL; } static struct k_itimer *posix_timer_by_id(timer_t id) { struct signal_struct *sig = current->signal; struct hlist_head *head = &posix_timers_hashtable[hash(sig, id)]; return __posix_timers_find(head, sig, id); } static int posix_timer_add(struct k_itimer *timer) { struct signal_struct *sig = current->signal; int first_free_id = sig->posix_timer_id; struct hlist_head *head; int ret = -ENOENT; do { spin_lock(&hash_lock); head = &posix_timers_hashtable[hash(sig, sig->posix_timer_id)]; if (!__posix_timers_find(head, sig, sig->posix_timer_id)) { hlist_add_head_rcu(&timer->t_hash, head); ret = sig->posix_timer_id; } if (++sig->posix_timer_id < 0) sig->posix_timer_id = 0; if ((sig->posix_timer_id == first_free_id) && (ret == -ENOENT)) /* Loop over all possible ids completed */ ret = -EAGAIN; spin_unlock(&hash_lock); } while (ret == -ENOENT); return ret; } static inline void unlock_timer(struct k_itimer *timr, unsigned long flags) { spin_unlock_irqrestore(&timr->it_lock, flags); } /* Get clock_realtime */ static int posix_clock_realtime_get(clockid_t which_clock, struct timespec64 *tp) { ktime_get_real_ts64(tp); return 0; } /* Set clock_realtime */ static int posix_clock_realtime_set(const clockid_t which_clock, const struct timespec64 *tp) { return do_sys_settimeofday64(tp, NULL); } static int posix_clock_realtime_adj(const clockid_t which_clock, struct timex *t) { return do_adjtimex(t); } /* * Get monotonic time for posix timers */ static int posix_ktime_get_ts(clockid_t which_clock, struct timespec64 *tp) { ktime_get_ts64(tp); return 0; } /* * Get monotonic-raw time for posix timers */ static int posix_get_monotonic_raw(clockid_t which_clock, struct timespec64 *tp) { getrawmonotonic64(tp); return 0; } static int posix_get_realtime_coarse(clockid_t which_clock, struct timespec64 *tp) { *tp = current_kernel_time64(); return 0; } static int posix_get_monotonic_coarse(clockid_t which_clock, struct timespec64 *tp) { *tp = get_monotonic_coarse64(); return 0; } static int posix_get_coarse_res(const clockid_t which_clock, struct timespec64 *tp) { *tp = ktime_to_timespec64(KTIME_LOW_RES); return 0; } static int posix_get_boottime(const clockid_t which_clock, struct timespec64 *tp) { get_monotonic_boottime64(tp); return 0; } static int posix_get_tai(clockid_t which_clock, struct timespec64 *tp) { timekeeping_clocktai64(tp); return 0; } static int posix_get_hrtimer_res(clockid_t which_clock, struct timespec64 *tp) { tp->tv_sec = 0; tp->tv_nsec = hrtimer_resolution; return 0; } /* * Initialize everything, well, just everything in Posix clocks/timers ;) */ static __init int init_posix_timers(void) { posix_timers_cache = kmem_cache_create("posix_timers_cache", sizeof (struct k_itimer), 0, SLAB_PANIC, NULL); return 0; } __initcall(init_posix_timers); static void common_hrtimer_rearm(struct k_itimer *timr) { struct hrtimer *timer = &timr->it.real.timer; if (!timr->it_interval) return; timr->it_overrun += (unsigned int) hrtimer_forward(timer, timer->base->get_time(), timr->it_interval); hrtimer_restart(timer); } /* * This function is exported for use by the signal deliver code. It is * called just prior to the info block being released and passes that * block to us. It's function is to update the overrun entry AND to * restart the timer. It should only be called if the timer is to be * restarted (i.e. we have flagged this in the sys_private entry of the * info block). * * To protect against the timer going away while the interrupt is queued, * we require that the it_requeue_pending flag be set. */ void posixtimer_rearm(struct siginfo *info) { struct k_itimer *timr; unsigned long flags; timr = lock_timer(info->si_tid, &flags); if (!timr) return; if (timr->it_requeue_pending == info->si_sys_private) { timr->kclock->timer_rearm(timr); timr->it_active = 1; timr->it_overrun_last = timr->it_overrun; timr->it_overrun = -1; ++timr->it_requeue_pending; info->si_overrun += timr->it_overrun_last; } unlock_timer(timr, flags); } int posix_timer_event(struct k_itimer *timr, int si_private) { struct task_struct *task; int shared, ret = -1; /* * FIXME: if ->sigq is queued we can race with * dequeue_signal()->posixtimer_rearm(). * * If dequeue_signal() sees the "right" value of * si_sys_private it calls posixtimer_rearm(). * We re-queue ->sigq and drop ->it_lock(). * posixtimer_rearm() locks the timer * and re-schedules it while ->sigq is pending. * Not really bad, but not that we want. */ timr->sigq->info.si_sys_private = si_private; rcu_read_lock(); task = pid_task(timr->it_pid, PIDTYPE_PID); if (task) { shared = !(timr->it_sigev_notify & SIGEV_THREAD_ID); ret = send_sigqueue(timr->sigq, task, shared); } rcu_read_unlock(); /* If we failed to send the signal the timer stops. */ return ret > 0; } /* * This function gets called when a POSIX.1b interval timer expires. It * is used as a callback from the kernel internal timer. The * run_timer_list code ALWAYS calls with interrupts on. * This code is for CLOCK_REALTIME* and CLOCK_MONOTONIC* timers. */ static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer) { struct k_itimer *timr; unsigned long flags; int si_private = 0; enum hrtimer_restart ret = HRTIMER_NORESTART; timr = container_of(timer, struct k_itimer, it.real.timer); spin_lock_irqsave(&timr->it_lock, flags); timr->it_active = 0; if (timr->it_interval != 0) si_private = ++timr->it_requeue_pending; if (posix_timer_event(timr, si_private)) { /* * signal was not sent because of sig_ignor * we will not get a call back to restart it AND * it should be restarted. */ if (timr->it_interval != 0) { ktime_t now = hrtimer_cb_get_time(timer); /* * FIXME: What we really want, is to stop this * timer completely and restart it in case the * SIG_IGN is removed. This is a non trivial * change which involves sighand locking * (sigh !), which we don't want to do late in * the release cycle. * * For now we just let timers with an interval * less than a jiffie expire every jiffie to * avoid softirq starvation in case of SIG_IGN * and a very small interval, which would put * the timer right back on the softirq pending * list. By moving now ahead of time we trick * hrtimer_forward() to expire the timer * later, while we still maintain the overrun * accuracy, but have some inconsistency in * the timer_gettime() case. This is at least * better than a starved softirq. A more * complex fix which solves also another related * inconsistency is already in the pipeline. */ #ifdef CONFIG_HIGH_RES_TIMERS { ktime_t kj = NSEC_PER_SEC / HZ; if (timr->it_interval < kj) now = ktime_add(now, kj); } #endif timr->it_overrun += (unsigned int) hrtimer_forward(timer, now, timr->it_interval); ret = HRTIMER_RESTART; ++timr->it_requeue_pending; timr->it_active = 1; } } unlock_timer(timr, flags); return ret; } static struct pid *good_sigevent(sigevent_t * event) { struct task_struct *rtn = current->group_leader; if ((event->sigev_notify & SIGEV_THREAD_ID ) && (!(rtn = find_task_by_vpid(event->sigev_notify_thread_id)) || !same_thread_group(rtn, current) || (event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_SIGNAL)) return NULL; if (((event->sigev_notify & ~SIGEV_THREAD_ID) != SIGEV_NONE) && ((event->sigev_signo <= 0) || (event->sigev_signo > SIGRTMAX))) return NULL; return task_pid(rtn); } static struct k_itimer * alloc_posix_timer(void) { struct k_itimer *tmr; tmr = kmem_cache_zalloc(posix_timers_cache, GFP_KERNEL); if (!tmr) return tmr; if (unlikely(!(tmr->sigq = sigqueue_alloc()))) { kmem_cache_free(posix_timers_cache, tmr); return NULL; } memset(&tmr->sigq->info, 0, sizeof(siginfo_t)); return tmr; } static void k_itimer_rcu_free(struct rcu_head *head) { struct k_itimer *tmr = container_of(head, struct k_itimer, it.rcu); kmem_cache_free(posix_timers_cache, tmr); } #define IT_ID_SET 1 #define IT_ID_NOT_SET 0 static void release_posix_timer(struct k_itimer *tmr, int it_id_set) { if (it_id_set) { unsigned long flags; spin_lock_irqsave(&hash_lock, flags); hlist_del_rcu(&tmr->t_hash); spin_unlock_irqrestore(&hash_lock, flags); } put_pid(tmr->it_pid); sigqueue_free(tmr->sigq); call_rcu(&tmr->it.rcu, k_itimer_rcu_free); } static int common_timer_create(struct k_itimer *new_timer) { hrtimer_init(&new_timer->it.real.timer, new_timer->it_clock, 0); return 0; } /* Create a POSIX.1b interval timer. */ static int do_timer_create(clockid_t which_clock, struct sigevent *event, timer_t __user *created_timer_id) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct k_itimer *new_timer; int error, new_timer_id; int it_id_set = IT_ID_NOT_SET; if (!kc) return -EINVAL; if (!kc->timer_create) return -EOPNOTSUPP; new_timer = alloc_posix_timer(); if (unlikely(!new_timer)) return -EAGAIN; spin_lock_init(&new_timer->it_lock); new_timer_id = posix_timer_add(new_timer); if (new_timer_id < 0) { error = new_timer_id; goto out; } it_id_set = IT_ID_SET; new_timer->it_id = (timer_t) new_timer_id; new_timer->it_clock = which_clock; new_timer->kclock = kc; new_timer->it_overrun = -1; if (event) { rcu_read_lock(); new_timer->it_pid = get_pid(good_sigevent(event)); rcu_read_unlock(); if (!new_timer->it_pid) { error = -EINVAL; goto out; } new_timer->it_sigev_notify = event->sigev_notify; new_timer->sigq->info.si_signo = event->sigev_signo; new_timer->sigq->info.si_value = event->sigev_value; } else { new_timer->it_sigev_notify = SIGEV_SIGNAL; new_timer->sigq->info.si_signo = SIGALRM; memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t)); new_timer->sigq->info.si_value.sival_int = new_timer->it_id; new_timer->it_pid = get_pid(task_tgid(current)); } new_timer->sigq->info.si_tid = new_timer->it_id; new_timer->sigq->info.si_code = SI_TIMER; if (copy_to_user(created_timer_id, &new_timer_id, sizeof (new_timer_id))) { error = -EFAULT; goto out; } error = kc->timer_create(new_timer); if (error) goto out; spin_lock_irq(&current->sighand->siglock); new_timer->it_signal = current->signal; list_add(&new_timer->list, &current->signal->posix_timers); spin_unlock_irq(&current->sighand->siglock); return 0; /* * In the case of the timer belonging to another task, after * the task is unlocked, the timer is owned by the other task * and may cease to exist at any time. Don't use or modify * new_timer after the unlock call. */ out: release_posix_timer(new_timer, it_id_set); return error; } SYSCALL_DEFINE3(timer_create, const clockid_t, which_clock, struct sigevent __user *, timer_event_spec, timer_t __user *, created_timer_id) { if (timer_event_spec) { sigevent_t event; if (copy_from_user(&event, timer_event_spec, sizeof (event))) return -EFAULT; return do_timer_create(which_clock, &event, created_timer_id); } return do_timer_create(which_clock, NULL, created_timer_id); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE3(timer_create, clockid_t, which_clock, struct compat_sigevent __user *, timer_event_spec, timer_t __user *, created_timer_id) { if (timer_event_spec) { sigevent_t event; if (get_compat_sigevent(&event, timer_event_spec)) return -EFAULT; return do_timer_create(which_clock, &event, created_timer_id); } return do_timer_create(which_clock, NULL, created_timer_id); } #endif /* * Locking issues: We need to protect the result of the id look up until * we get the timer locked down so it is not deleted under us. The * removal is done under the idr spinlock so we use that here to bridge * the find to the timer lock. To avoid a dead lock, the timer id MUST * be release with out holding the timer lock. */ static struct k_itimer *__lock_timer(timer_t timer_id, unsigned long *flags) { struct k_itimer *timr; /* * timer_t could be any type >= int and we want to make sure any * @timer_id outside positive int range fails lookup. */ if ((unsigned long long)timer_id > INT_MAX) return NULL; rcu_read_lock(); timr = posix_timer_by_id(timer_id); if (timr) { spin_lock_irqsave(&timr->it_lock, *flags); if (timr->it_signal == current->signal) { rcu_read_unlock(); return timr; } spin_unlock_irqrestore(&timr->it_lock, *flags); } rcu_read_unlock(); return NULL; } static ktime_t common_hrtimer_remaining(struct k_itimer *timr, ktime_t now) { struct hrtimer *timer = &timr->it.real.timer; return __hrtimer_expires_remaining_adjusted(timer, now); } static int common_hrtimer_forward(struct k_itimer *timr, ktime_t now) { struct hrtimer *timer = &timr->it.real.timer; return (int)hrtimer_forward(timer, now, timr->it_interval); } /* * Get the time remaining on a POSIX.1b interval timer. This function * is ALWAYS called with spin_lock_irq on the timer, thus it must not * mess with irq. * * We have a couple of messes to clean up here. First there is the case * of a timer that has a requeue pending. These timers should appear to * be in the timer list with an expiry as if we were to requeue them * now. * * The second issue is the SIGEV_NONE timer which may be active but is * not really ever put in the timer list (to save system resources). * This timer may be expired, and if so, we will do it here. Otherwise * it is the same as a requeue pending timer WRT to what we should * report. */ void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting) { const struct k_clock *kc = timr->kclock; ktime_t now, remaining, iv; struct timespec64 ts64; bool sig_none; sig_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE; iv = timr->it_interval; /* interval timer ? */ if (iv) { cur_setting->it_interval = ktime_to_timespec64(iv); } else if (!timr->it_active) { /* * SIGEV_NONE oneshot timers are never queued. Check them * below. */ if (!sig_none) return; } /* * The timespec64 based conversion is suboptimal, but it's not * worth to implement yet another callback. */ kc->clock_get(timr->it_clock, &ts64); now = timespec64_to_ktime(ts64); /* * When a requeue is pending or this is a SIGEV_NONE timer move the * expiry time forward by intervals, so expiry is > now. */ if (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none)) timr->it_overrun += kc->timer_forward(timr, now); remaining = kc->timer_remaining(timr, now); /* Return 0 only, when the timer is expired and not pending */ if (remaining <= 0) { /* * A single shot SIGEV_NONE timer must return 0, when * it is expired ! */ if (!sig_none) cur_setting->it_value.tv_nsec = 1; } else { cur_setting->it_value = ktime_to_timespec64(remaining); } } /* Get the time remaining on a POSIX.1b interval timer. */ static int do_timer_gettime(timer_t timer_id, struct itimerspec64 *setting) { struct k_itimer *timr; const struct k_clock *kc; unsigned long flags; int ret = 0; timr = lock_timer(timer_id, &flags); if (!timr) return -EINVAL; memset(setting, 0, sizeof(*setting)); kc = timr->kclock; if (WARN_ON_ONCE(!kc || !kc->timer_get)) ret = -EINVAL; else kc->timer_get(timr, setting); unlock_timer(timr, flags); return ret; } /* Get the time remaining on a POSIX.1b interval timer. */ SYSCALL_DEFINE2(timer_gettime, timer_t, timer_id, struct itimerspec __user *, setting) { struct itimerspec64 cur_setting; int ret = do_timer_gettime(timer_id, &cur_setting); if (!ret) { if (put_itimerspec64(&cur_setting, setting)) ret = -EFAULT; } return ret; } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE2(timer_gettime, timer_t, timer_id, struct compat_itimerspec __user *, setting) { struct itimerspec64 cur_setting; int ret = do_timer_gettime(timer_id, &cur_setting); if (!ret) { if (put_compat_itimerspec64(&cur_setting, setting)) ret = -EFAULT; } return ret; } #endif /* * Get the number of overruns of a POSIX.1b interval timer. This is to * be the overrun of the timer last delivered. At the same time we are * accumulating overruns on the next timer. The overrun is frozen when * the signal is delivered, either at the notify time (if the info block * is not queued) or at the actual delivery time (as we are informed by * the call back to posixtimer_rearm(). So all we need to do is * to pick up the frozen overrun. */ SYSCALL_DEFINE1(timer_getoverrun, timer_t, timer_id) { struct k_itimer *timr; int overrun; unsigned long flags; timr = lock_timer(timer_id, &flags); if (!timr) return -EINVAL; overrun = timr->it_overrun_last; unlock_timer(timr, flags); return overrun; } static void common_hrtimer_arm(struct k_itimer *timr, ktime_t expires, bool absolute, bool sigev_none) { struct hrtimer *timer = &timr->it.real.timer; enum hrtimer_mode mode; mode = absolute ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL; /* * Posix magic: Relative CLOCK_REALTIME timers are not affected by * clock modifications, so they become CLOCK_MONOTONIC based under the * hood. See hrtimer_init(). Update timr->kclock, so the generic * functions which use timr->kclock->clock_get() work. * * Note: it_clock stays unmodified, because the next timer_set() might * use ABSTIME, so it needs to switch back. */ if (timr->it_clock == CLOCK_REALTIME) timr->kclock = absolute ? &clock_realtime : &clock_monotonic; hrtimer_init(&timr->it.real.timer, timr->it_clock, mode); timr->it.real.timer.function = posix_timer_fn; if (!absolute) expires = ktime_add_safe(expires, timer->base->get_time()); hrtimer_set_expires(timer, expires); if (!sigev_none) hrtimer_start_expires(timer, HRTIMER_MODE_ABS); } static int common_hrtimer_try_to_cancel(struct k_itimer *timr) { return hrtimer_try_to_cancel(&timr->it.real.timer); } /* Set a POSIX.1b interval timer. */ int common_timer_set(struct k_itimer *timr, int flags, struct itimerspec64 *new_setting, struct itimerspec64 *old_setting) { const struct k_clock *kc = timr->kclock; bool sigev_none; ktime_t expires; if (old_setting) common_timer_get(timr, old_setting); /* Prevent rearming by clearing the interval */ timr->it_interval = 0; /* * Careful here. On SMP systems the timer expiry function could be * active and spinning on timr->it_lock. */ if (kc->timer_try_to_cancel(timr) < 0) return TIMER_RETRY; timr->it_active = 0; timr->it_requeue_pending = (timr->it_requeue_pending + 2) & ~REQUEUE_PENDING; timr->it_overrun_last = 0; /* Switch off the timer when it_value is zero */ if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec) return 0; timr->it_interval = timespec64_to_ktime(new_setting->it_interval); expires = timespec64_to_ktime(new_setting->it_value); sigev_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE; kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none); timr->it_active = !sigev_none; return 0; } static int do_timer_settime(timer_t timer_id, int flags, struct itimerspec64 *new_spec64, struct itimerspec64 *old_spec64) { const struct k_clock *kc; struct k_itimer *timr; unsigned long flag; int error = 0; if (!timespec64_valid(&new_spec64->it_interval) || !timespec64_valid(&new_spec64->it_value)) return -EINVAL; if (old_spec64) memset(old_spec64, 0, sizeof(*old_spec64)); retry: timr = lock_timer(timer_id, &flag); if (!timr) return -EINVAL; kc = timr->kclock; if (WARN_ON_ONCE(!kc || !kc->timer_set)) error = -EINVAL; else error = kc->timer_set(timr, flags, new_spec64, old_spec64); unlock_timer(timr, flag); if (error == TIMER_RETRY) { old_spec64 = NULL; // We already got the old time... goto retry; } return error; } /* Set a POSIX.1b interval timer */ SYSCALL_DEFINE4(timer_settime, timer_t, timer_id, int, flags, const struct itimerspec __user *, new_setting, struct itimerspec __user *, old_setting) { struct itimerspec64 new_spec, old_spec; struct itimerspec64 *rtn = old_setting ? &old_spec : NULL; int error = 0; if (!new_setting) return -EINVAL; if (get_itimerspec64(&new_spec, new_setting)) return -EFAULT; error = do_timer_settime(timer_id, flags, &new_spec, rtn); if (!error && old_setting) { if (put_itimerspec64(&old_spec, old_setting)) error = -EFAULT; } return error; } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE4(timer_settime, timer_t, timer_id, int, flags, struct compat_itimerspec __user *, new, struct compat_itimerspec __user *, old) { struct itimerspec64 new_spec, old_spec; struct itimerspec64 *rtn = old ? &old_spec : NULL; int error = 0; if (!new) return -EINVAL; if (get_compat_itimerspec64(&new_spec, new)) return -EFAULT; error = do_timer_settime(timer_id, flags, &new_spec, rtn); if (!error && old) { if (put_compat_itimerspec64(&old_spec, old)) error = -EFAULT; } return error; } #endif int common_timer_del(struct k_itimer *timer) { const struct k_clock *kc = timer->kclock; timer->it_interval = 0; if (kc->timer_try_to_cancel(timer) < 0) return TIMER_RETRY; timer->it_active = 0; return 0; } static inline int timer_delete_hook(struct k_itimer *timer) { const struct k_clock *kc = timer->kclock; if (WARN_ON_ONCE(!kc || !kc->timer_del)) return -EINVAL; return kc->timer_del(timer); } /* Delete a POSIX.1b interval timer. */ SYSCALL_DEFINE1(timer_delete, timer_t, timer_id) { struct k_itimer *timer; unsigned long flags; retry_delete: timer = lock_timer(timer_id, &flags); if (!timer) return -EINVAL; if (timer_delete_hook(timer) == TIMER_RETRY) { unlock_timer(timer, flags); goto retry_delete; } spin_lock(&current->sighand->siglock); list_del(&timer->list); spin_unlock(&current->sighand->siglock); /* * This keeps any tasks waiting on the spin lock from thinking * they got something (see the lock code above). */ timer->it_signal = NULL; unlock_timer(timer, flags); release_posix_timer(timer, IT_ID_SET); return 0; } /* * return timer owned by the process, used by exit_itimers */ static void itimer_delete(struct k_itimer *timer) { unsigned long flags; retry_delete: spin_lock_irqsave(&timer->it_lock, flags); if (timer_delete_hook(timer) == TIMER_RETRY) { unlock_timer(timer, flags); goto retry_delete; } list_del(&timer->list); /* * This keeps any tasks waiting on the spin lock from thinking * they got something (see the lock code above). */ timer->it_signal = NULL; unlock_timer(timer, flags); release_posix_timer(timer, IT_ID_SET); } /* * This is called by do_exit or de_thread, only when there are no more * references to the shared signal_struct. */ void exit_itimers(struct signal_struct *sig) { struct k_itimer *tmr; while (!list_empty(&sig->posix_timers)) { tmr = list_entry(sig->posix_timers.next, struct k_itimer, list); itimer_delete(tmr); } } SYSCALL_DEFINE2(clock_settime, const clockid_t, which_clock, const struct timespec __user *, tp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 new_tp; if (!kc || !kc->clock_set) return -EINVAL; if (get_timespec64(&new_tp, tp)) return -EFAULT; return kc->clock_set(which_clock, &new_tp); } SYSCALL_DEFINE2(clock_gettime, const clockid_t, which_clock, struct timespec __user *,tp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 kernel_tp; int error; if (!kc) return -EINVAL; error = kc->clock_get(which_clock, &kernel_tp); if (!error && put_timespec64(&kernel_tp, tp)) error = -EFAULT; return error; } SYSCALL_DEFINE2(clock_adjtime, const clockid_t, which_clock, struct timex __user *, utx) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timex ktx; int err; if (!kc) return -EINVAL; if (!kc->clock_adj) return -EOPNOTSUPP; if (copy_from_user(&ktx, utx, sizeof(ktx))) return -EFAULT; err = kc->clock_adj(which_clock, &ktx); if (err >= 0 && copy_to_user(utx, &ktx, sizeof(ktx))) return -EFAULT; return err; } SYSCALL_DEFINE2(clock_getres, const clockid_t, which_clock, struct timespec __user *, tp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 rtn_tp; int error; if (!kc) return -EINVAL; error = kc->clock_getres(which_clock, &rtn_tp); if (!error && tp && put_timespec64(&rtn_tp, tp)) error = -EFAULT; return error; } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE2(clock_settime, clockid_t, which_clock, struct compat_timespec __user *, tp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 ts; if (!kc || !kc->clock_set) return -EINVAL; if (compat_get_timespec64(&ts, tp)) return -EFAULT; return kc->clock_set(which_clock, &ts); } COMPAT_SYSCALL_DEFINE2(clock_gettime, clockid_t, which_clock, struct compat_timespec __user *, tp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 ts; int err; if (!kc) return -EINVAL; err = kc->clock_get(which_clock, &ts); if (!err && compat_put_timespec64(&ts, tp)) err = -EFAULT; return err; } COMPAT_SYSCALL_DEFINE2(clock_adjtime, clockid_t, which_clock, struct compat_timex __user *, utp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timex ktx; int err; if (!kc) return -EINVAL; if (!kc->clock_adj) return -EOPNOTSUPP; err = compat_get_timex(&ktx, utp); if (err) return err; err = kc->clock_adj(which_clock, &ktx); if (err >= 0) err = compat_put_timex(utp, &ktx); return err; } COMPAT_SYSCALL_DEFINE2(clock_getres, clockid_t, which_clock, struct compat_timespec __user *, tp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 ts; int err; if (!kc) return -EINVAL; err = kc->clock_getres(which_clock, &ts); if (!err && tp && compat_put_timespec64(&ts, tp)) return -EFAULT; return err; } #endif /* * nanosleep for monotonic and realtime clocks */ static int common_nsleep(const clockid_t which_clock, int flags, const struct timespec64 *rqtp) { return hrtimer_nanosleep(rqtp, flags & TIMER_ABSTIME ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL, which_clock); } SYSCALL_DEFINE4(clock_nanosleep, const clockid_t, which_clock, int, flags, const struct timespec __user *, rqtp, struct timespec __user *, rmtp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 t; if (!kc) return -EINVAL; if (!kc->nsleep) return -ENANOSLEEP_NOTSUP; if (get_timespec64(&t, rqtp)) return -EFAULT; if (!timespec64_valid(&t)) return -EINVAL; if (flags & TIMER_ABSTIME) rmtp = NULL; current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE; current->restart_block.nanosleep.rmtp = rmtp; return kc->nsleep(which_clock, flags, &t); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE4(clock_nanosleep, clockid_t, which_clock, int, flags, struct compat_timespec __user *, rqtp, struct compat_timespec __user *, rmtp) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct timespec64 t; if (!kc) return -EINVAL; if (!kc->nsleep) return -ENANOSLEEP_NOTSUP; if (compat_get_timespec64(&t, rqtp)) return -EFAULT; if (!timespec64_valid(&t)) return -EINVAL; if (flags & TIMER_ABSTIME) rmtp = NULL; current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE; current->restart_block.nanosleep.compat_rmtp = rmtp; return kc->nsleep(which_clock, flags, &t); } #endif static const struct k_clock clock_realtime = { .clock_getres = posix_get_hrtimer_res, .clock_get = posix_clock_realtime_get, .clock_set = posix_clock_realtime_set, .clock_adj = posix_clock_realtime_adj, .nsleep = common_nsleep, .timer_create = common_timer_create, .timer_set = common_timer_set, .timer_get = common_timer_get, .timer_del = common_timer_del, .timer_rearm = common_hrtimer_rearm, .timer_forward = common_hrtimer_forward, .timer_remaining = common_hrtimer_remaining, .timer_try_to_cancel = common_hrtimer_try_to_cancel, .timer_arm = common_hrtimer_arm, }; static const struct k_clock clock_monotonic = { .clock_getres = posix_get_hrtimer_res, .clock_get = posix_ktime_get_ts, .nsleep = common_nsleep, .timer_create = common_timer_create, .timer_set = common_timer_set, .timer_get = common_timer_get, .timer_del = common_timer_del, .timer_rearm = common_hrtimer_rearm, .timer_forward = common_hrtimer_forward, .timer_remaining = common_hrtimer_remaining, .timer_try_to_cancel = common_hrtimer_try_to_cancel, .timer_arm = common_hrtimer_arm, }; static const struct k_clock clock_monotonic_raw = { .clock_getres = posix_get_hrtimer_res, .clock_get = posix_get_monotonic_raw, }; static const struct k_clock clock_realtime_coarse = { .clock_getres = posix_get_coarse_res, .clock_get = posix_get_realtime_coarse, }; static const struct k_clock clock_monotonic_coarse = { .clock_getres = posix_get_coarse_res, .clock_get = posix_get_monotonic_coarse, }; static const struct k_clock clock_tai = { .clock_getres = posix_get_hrtimer_res, .clock_get = posix_get_tai, .nsleep = common_nsleep, .timer_create = common_timer_create, .timer_set = common_timer_set, .timer_get = common_timer_get, .timer_del = common_timer_del, .timer_rearm = common_hrtimer_rearm, .timer_forward = common_hrtimer_forward, .timer_remaining = common_hrtimer_remaining, .timer_try_to_cancel = common_hrtimer_try_to_cancel, .timer_arm = common_hrtimer_arm, }; static const struct k_clock clock_boottime = { .clock_getres = posix_get_hrtimer_res, .clock_get = posix_get_boottime, .nsleep = common_nsleep, .timer_create = common_timer_create, .timer_set = common_timer_set, .timer_get = common_timer_get, .timer_del = common_timer_del, .timer_rearm = common_hrtimer_rearm, .timer_forward = common_hrtimer_forward, .timer_remaining = common_hrtimer_remaining, .timer_try_to_cancel = common_hrtimer_try_to_cancel, .timer_arm = common_hrtimer_arm, }; static const struct k_clock * const posix_clocks[] = { [CLOCK_REALTIME] = &clock_realtime, [CLOCK_MONOTONIC] = &clock_monotonic, [CLOCK_PROCESS_CPUTIME_ID] = &clock_process, [CLOCK_THREAD_CPUTIME_ID] = &clock_thread, [CLOCK_MONOTONIC_RAW] = &clock_monotonic_raw, [CLOCK_REALTIME_COARSE] = &clock_realtime_coarse, [CLOCK_MONOTONIC_COARSE] = &clock_monotonic_coarse, [CLOCK_BOOTTIME] = &clock_boottime, [CLOCK_REALTIME_ALARM] = &alarm_clock, [CLOCK_BOOTTIME_ALARM] = &alarm_clock, [CLOCK_TAI] = &clock_tai, }; static const struct k_clock *clockid_to_kclock(const clockid_t id) { if (id < 0) return (id & CLOCKFD_MASK) == CLOCKFD ? &clock_posix_dynamic : &clock_posix_cpu; if (id >= ARRAY_SIZE(posix_clocks) || !posix_clocks[id]) return NULL; return posix_clocks[id]; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3032_0
crossvul-cpp_data_good_3328_2
/* Copyright (c) 2013. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This module implements a regular expressions engine based on Thompson's algorithm as described by Russ Cox in http://swtch.com/~rsc/regexp/regexp2.html. What the article names a "thread" has been named a "fiber" in this code, in order to avoid confusion with operating system threads. */ #include <assert.h> #include <string.h> #include <limits.h> #include <yara/limits.h> #include <yara/globals.h> #include <yara/utils.h> #include <yara/mem.h> #include <yara/re.h> #include <yara/error.h> #include <yara/threading.h> #include <yara/re_lexer.h> #include <yara/hex_lexer.h> // Maximum allowed split ID, also limiting the number of split instructions // allowed in a regular expression. This number can't be increased // over 255 without changing RE_SPLIT_ID_TYPE. #define RE_MAX_SPLIT_ID 128 // Maximum stack size for regexp evaluation #define RE_MAX_STACK 1024 // Maximum code size for a compiled regexp #define RE_MAX_CODE_SIZE 32768 // Maximum input size scanned by yr_re_exec #define RE_SCAN_LIMIT 4096 // Maximum number of fibers #define RE_MAX_FIBERS 1024 #define EMIT_BACKWARDS 0x01 #define EMIT_DONT_SET_FORWARDS_CODE 0x02 #define EMIT_DONT_SET_BACKWARDS_CODE 0x04 typedef struct _RE_REPEAT_ARGS { uint16_t min; uint16_t max; int32_t offset; } RE_REPEAT_ARGS; typedef struct _RE_REPEAT_ANY_ARGS { uint16_t min; uint16_t max; } RE_REPEAT_ANY_ARGS; typedef struct _RE_EMIT_CONTEXT { YR_ARENA* arena; RE_SPLIT_ID_TYPE next_split_id; } RE_EMIT_CONTEXT; typedef struct _RE_FIBER { uint8_t* ip; // instruction pointer int32_t sp; // stack pointer int32_t rc; // repeat counter uint16_t stack[RE_MAX_STACK]; struct _RE_FIBER* prev; struct _RE_FIBER* next; } RE_FIBER; typedef struct _RE_FIBER_LIST { RE_FIBER* head; RE_FIBER* tail; } RE_FIBER_LIST; typedef struct _RE_FIBER_POOL { int fiber_count; RE_FIBER_LIST fibers; } RE_FIBER_POOL; typedef struct _RE_THREAD_STORAGE { RE_FIBER_POOL fiber_pool; } RE_THREAD_STORAGE; YR_THREAD_STORAGE_KEY thread_storage_key = 0; #define CHAR_IN_CLASS(chr, cls) \ ((cls)[(chr) / 8] & 1 << ((chr) % 8)) int _yr_re_is_word_char( uint8_t* input, int character_size) { int result = ((isalnum(*input) || (*input) == '_')); if (character_size == 2) result = result && (*(input + 1) == 0); return result; } // // yr_re_initialize // // Should be called by main thread before any other // function from this module. // int yr_re_initialize(void) { return yr_thread_storage_create(&thread_storage_key); } // // yr_re_finalize // // Should be called by main thread after every other thread // stopped using functions from this module. // int yr_re_finalize(void) { yr_thread_storage_destroy(&thread_storage_key); thread_storage_key = 0; return ERROR_SUCCESS; } // // yr_re_finalize_thread // // Should be called by every thread using this module // before exiting. // int yr_re_finalize_thread(void) { RE_FIBER* fiber; RE_FIBER* next_fiber; RE_THREAD_STORAGE* storage; if (thread_storage_key != 0) storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value( &thread_storage_key); else return ERROR_SUCCESS; if (storage != NULL) { fiber = storage->fiber_pool.fibers.head; while (fiber != NULL) { next_fiber = fiber->next; yr_free(fiber); fiber = next_fiber; } yr_free(storage); } return yr_thread_storage_set_value(&thread_storage_key, NULL); } RE_NODE* yr_re_node_create( int type, RE_NODE* left, RE_NODE* right) { RE_NODE* result = (RE_NODE*) yr_malloc(sizeof(RE_NODE)); if (result != NULL) { result->type = type; result->left = left; result->right = right; result->greedy = TRUE; result->forward_code = NULL; result->backward_code = NULL; } return result; } void yr_re_node_destroy( RE_NODE* node) { if (node->left != NULL) yr_re_node_destroy(node->left); if (node->right != NULL) yr_re_node_destroy(node->right); if (node->type == RE_NODE_CLASS) yr_free(node->class_vector); yr_free(node); } int yr_re_ast_create( RE_AST** re_ast) { *re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST)); if (*re_ast == NULL) return ERROR_INSUFFICIENT_MEMORY; (*re_ast)->flags = 0; (*re_ast)->root_node = NULL; return ERROR_SUCCESS; } void yr_re_ast_destroy( RE_AST* re_ast) { if (re_ast->root_node != NULL) yr_re_node_destroy(re_ast->root_node); yr_free(re_ast); } // // yr_re_parse // // Parses a regexp but don't emit its code. A further call to // yr_re_emit_code is required to get the code. // int yr_re_parse( const char* re_string, RE_AST** re_ast, RE_ERROR* error) { return yr_parse_re_string(re_string, re_ast, error); } // // yr_re_parse_hex // // Parses a hex string but don't emit its code. A further call to // yr_re_emit_code is required to get the code. // int yr_re_parse_hex( const char* hex_string, RE_AST** re_ast, RE_ERROR* error) { return yr_parse_hex_string(hex_string, re_ast, error); } // // yr_re_compile // // Parses the regexp and emit its code to the provided code_arena. // int yr_re_compile( const char* re_string, int flags, YR_ARENA* code_arena, RE** re, RE_ERROR* error) { RE_AST* re_ast; RE _re; FAIL_ON_ERROR(yr_arena_reserve_memory( code_arena, sizeof(int64_t) + RE_MAX_CODE_SIZE)); FAIL_ON_ERROR(yr_re_parse(re_string, &re_ast, error)); _re.flags = flags; FAIL_ON_ERROR_WITH_CLEANUP( yr_arena_write_data( code_arena, &_re, sizeof(_re), (void**) re), yr_re_ast_destroy(re_ast)); FAIL_ON_ERROR_WITH_CLEANUP( yr_re_ast_emit_code(re_ast, code_arena, FALSE), yr_re_ast_destroy(re_ast)); yr_re_ast_destroy(re_ast); return ERROR_SUCCESS; } // // yr_re_match // // Verifies if the target string matches the pattern // // Args: // RE* re - A pointer to a compiled regexp // char* target - Target string // // Returns: // See return codes for yr_re_exec int yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), 0, re->flags | RE_FLAGS_SCAN, NULL, NULL); } // // yr_re_ast_extract_literal // // Verifies if the provided regular expression is just a literal string // like "abc", "12345", without any wildcard, operator, etc. In that case // returns the string as a SIZED_STRING, or returns NULL if otherwise. // // The caller is responsible for deallocating the returned SIZED_STRING by // calling yr_free. // SIZED_STRING* yr_re_ast_extract_literal( RE_AST* re_ast) { SIZED_STRING* string; RE_NODE* node = re_ast->root_node; int i, length = 0; char tmp; while (node != NULL) { length++; if (node->type == RE_NODE_LITERAL) break; if (node->type != RE_NODE_CONCAT) return NULL; if (node->right == NULL || node->right->type != RE_NODE_LITERAL) return NULL; node = node->left; } string = (SIZED_STRING*) yr_malloc(sizeof(SIZED_STRING) + length); if (string == NULL) return NULL; string->length = 0; node = re_ast->root_node; while (node->type == RE_NODE_CONCAT) { string->c_string[string->length++] = node->right->value; node = node->left; } string->c_string[string->length++] = node->value; // The string ends up reversed. Reverse it back to its original value. for (i = 0; i < length / 2; i++) { tmp = string->c_string[i]; string->c_string[i] = string->c_string[length - i - 1]; string->c_string[length - i - 1] = tmp; } return string; } int _yr_re_node_contains_dot_star( RE_NODE* re_node) { if (re_node->type == RE_NODE_STAR && re_node->left->type == RE_NODE_ANY) return TRUE; if (re_node->left != NULL && _yr_re_node_contains_dot_star(re_node->left)) return TRUE; if (re_node->right != NULL && _yr_re_node_contains_dot_star(re_node->right)) return TRUE; return FALSE; } int yr_re_ast_contains_dot_star( RE_AST* re_ast) { return _yr_re_node_contains_dot_star(re_ast->root_node); } // // yr_re_ast_split_at_chaining_point // // In some cases splitting a regular expression in two is more efficient that // having a single regular expression. This happens when the regular expression // contains a large repetition of any character, for example: /foo.{0,1000}bar/ // In this case the regexp is split in /foo/ and /bar/ where /bar/ is "chained" // to /foo/. This means that /foo/ and /bar/ are handled as individual regexps // and when both matches YARA verifies if the distance between the matches // complies with the {0,1000} restriction. // This function traverses the regexp's tree looking for nodes where the regxp // should be split. It expects a left-unbalanced tree where the right child of // a RE_NODE_CONCAT can't be another RE_NODE_CONCAT. A RE_NODE_CONCAT must be // always the left child of its parent if the parent is also a RE_NODE_CONCAT. // int yr_re_ast_split_at_chaining_point( RE_AST* re_ast, RE_AST** result_re_ast, RE_AST** remainder_re_ast, int32_t* min_gap, int32_t* max_gap) { RE_NODE* node = re_ast->root_node; RE_NODE* child = re_ast->root_node->left; RE_NODE* parent = NULL; int result; *result_re_ast = re_ast; *remainder_re_ast = NULL; *min_gap = 0; *max_gap = 0; while (child != NULL && child->type == RE_NODE_CONCAT) { if (child->right != NULL && child->right->type == RE_NODE_RANGE_ANY && child->right->greedy == FALSE && (child->right->start > STRING_CHAINING_THRESHOLD || child->right->end > STRING_CHAINING_THRESHOLD)) { result = yr_re_ast_create(remainder_re_ast); if (result != ERROR_SUCCESS) return result; (*remainder_re_ast)->root_node = child->left; (*remainder_re_ast)->flags = re_ast->flags; child->left = NULL; if (parent != NULL) parent->left = node->right; else (*result_re_ast)->root_node = node->right; node->right = NULL; *min_gap = child->right->start; *max_gap = child->right->end; yr_re_node_destroy(node); return ERROR_SUCCESS; } parent = node; node = child; child = child->left; } return ERROR_SUCCESS; } int _yr_emit_inst( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint8_t** instruction_addr, int* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); *code_size = sizeof(uint8_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_uint8( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint8_t argument, uint8_t** instruction_addr, uint8_t** argument_addr, int* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(uint8_t), (void**) argument_addr)); *code_size = 2 * sizeof(uint8_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_uint16( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint16_t argument, uint8_t** instruction_addr, uint16_t** argument_addr, int* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(uint16_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(uint16_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_uint32( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, uint32_t argument, uint8_t** instruction_addr, uint32_t** argument_addr, int* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(uint32_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(uint32_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_int16( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, int16_t argument, uint8_t** instruction_addr, int16_t** argument_addr, int* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(int16_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(int16_t); return ERROR_SUCCESS; } int _yr_emit_inst_arg_struct( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, void* structure, size_t structure_size, uint8_t** instruction_addr, void** argument_addr, int* code_size) { FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, structure, structure_size, (void**) argument_addr)); *code_size = sizeof(uint8_t) + structure_size; return ERROR_SUCCESS; } int _yr_emit_split( RE_EMIT_CONTEXT* emit_context, uint8_t opcode, int16_t argument, uint8_t** instruction_addr, int16_t** argument_addr, int* code_size) { assert(opcode == RE_OPCODE_SPLIT_A || opcode == RE_OPCODE_SPLIT_B); if (emit_context->next_split_id == RE_MAX_SPLIT_ID) return ERROR_REGULAR_EXPRESSION_TOO_COMPLEX; FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &opcode, sizeof(uint8_t), (void**) instruction_addr)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &emit_context->next_split_id, sizeof(RE_SPLIT_ID_TYPE), NULL)); emit_context->next_split_id++; FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, &argument, sizeof(int16_t), (void**) argument_addr)); *code_size = sizeof(uint8_t) + sizeof(RE_SPLIT_ID_TYPE) + sizeof(int16_t); return ERROR_SUCCESS; } int _yr_re_emit( RE_EMIT_CONTEXT* emit_context, RE_NODE* re_node, int flags, uint8_t** code_addr, int* code_size) { int branch_size; int split_size; int inst_size; int jmp_size; int emit_split; int emit_repeat; int emit_prolog; int emit_epilog; RE_REPEAT_ARGS repeat_args; RE_REPEAT_ARGS* repeat_start_args_addr; RE_REPEAT_ANY_ARGS repeat_any_args; RE_NODE* left; RE_NODE* right; int16_t* split_offset_addr = NULL; int16_t* jmp_offset_addr = NULL; uint8_t* instruction_addr = NULL; *code_size = 0; switch(re_node->type) { case RE_NODE_LITERAL: FAIL_ON_ERROR(_yr_emit_inst_arg_uint8( emit_context, RE_OPCODE_LITERAL, re_node->value, &instruction_addr, NULL, code_size)); break; case RE_NODE_MASKED_LITERAL: FAIL_ON_ERROR(_yr_emit_inst_arg_uint16( emit_context, RE_OPCODE_MASKED_LITERAL, re_node->mask << 8 | re_node->value, &instruction_addr, NULL, code_size)); break; case RE_NODE_WORD_CHAR: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_WORD_CHAR, &instruction_addr, code_size)); break; case RE_NODE_NON_WORD_CHAR: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_WORD_CHAR, &instruction_addr, code_size)); break; case RE_NODE_WORD_BOUNDARY: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_WORD_BOUNDARY, &instruction_addr, code_size)); break; case RE_NODE_NON_WORD_BOUNDARY: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_WORD_BOUNDARY, &instruction_addr, code_size)); break; case RE_NODE_SPACE: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_SPACE, &instruction_addr, code_size)); break; case RE_NODE_NON_SPACE: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_SPACE, &instruction_addr, code_size)); break; case RE_NODE_DIGIT: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_DIGIT, &instruction_addr, code_size)); break; case RE_NODE_NON_DIGIT: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_NON_DIGIT, &instruction_addr, code_size)); break; case RE_NODE_ANY: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_ANY, &instruction_addr, code_size)); break; case RE_NODE_CLASS: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_CLASS, &instruction_addr, code_size)); FAIL_ON_ERROR(yr_arena_write_data( emit_context->arena, re_node->class_vector, 32, NULL)); *code_size += 32; break; case RE_NODE_ANCHOR_START: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_MATCH_AT_START, &instruction_addr, code_size)); break; case RE_NODE_ANCHOR_END: FAIL_ON_ERROR(_yr_emit_inst( emit_context, RE_OPCODE_MATCH_AT_END, &instruction_addr, code_size)); break; case RE_NODE_CONCAT: if (flags & EMIT_BACKWARDS) { left = re_node->right; right = re_node->left; } else { left = re_node->left; right = re_node->right; } FAIL_ON_ERROR(_yr_re_emit( emit_context, left, flags, &instruction_addr, &branch_size)); *code_size += branch_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, right, flags, NULL, &branch_size)); *code_size += branch_size; break; case RE_NODE_PLUS: // Code for e+ looks like: // // L1: code for e // split L1, L2 // L2: FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, &instruction_addr, &branch_size)); *code_size += branch_size; FAIL_ON_ERROR(_yr_emit_split( emit_context, re_node->greedy ? RE_OPCODE_SPLIT_B : RE_OPCODE_SPLIT_A, -branch_size, NULL, &split_offset_addr, &split_size)); *code_size += split_size; break; case RE_NODE_STAR: // Code for e* looks like: // // L1: split L1, L2 // code for e // jmp L1 // L2: FAIL_ON_ERROR(_yr_emit_split( emit_context, re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B, 0, &instruction_addr, &split_offset_addr, &split_size)); *code_size += split_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, NULL, &branch_size)); *code_size += branch_size; // Emit jump with offset set to 0. FAIL_ON_ERROR(_yr_emit_inst_arg_int16( emit_context, RE_OPCODE_JUMP, -(branch_size + split_size), NULL, &jmp_offset_addr, &jmp_size)); *code_size += jmp_size; // Update split offset. *split_offset_addr = split_size + branch_size + jmp_size; break; case RE_NODE_ALT: // Code for e1|e2 looks like: // // split L1, L2 // L1: code for e1 // jmp L3 // L2: code for e2 // L3: // Emit a split instruction with offset set to 0 temporarily. Offset // will be updated after we know the size of the code generated for // the left node (e1). FAIL_ON_ERROR(_yr_emit_split( emit_context, RE_OPCODE_SPLIT_A, 0, &instruction_addr, &split_offset_addr, &split_size)); *code_size += split_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, NULL, &branch_size)); *code_size += branch_size; // Emit jump with offset set to 0. FAIL_ON_ERROR(_yr_emit_inst_arg_int16( emit_context, RE_OPCODE_JUMP, 0, NULL, &jmp_offset_addr, &jmp_size)); *code_size += jmp_size; // Update split offset. *split_offset_addr = split_size + branch_size + jmp_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->right, flags, NULL, &branch_size)); *code_size += branch_size; // Update offset for jmp instruction. *jmp_offset_addr = branch_size + jmp_size; break; case RE_NODE_RANGE_ANY: repeat_any_args.min = re_node->start; repeat_any_args.max = re_node->end; FAIL_ON_ERROR(_yr_emit_inst_arg_struct( emit_context, re_node->greedy ? RE_OPCODE_REPEAT_ANY_GREEDY : RE_OPCODE_REPEAT_ANY_UNGREEDY, &repeat_any_args, sizeof(repeat_any_args), &instruction_addr, NULL, &inst_size)); *code_size += inst_size; break; case RE_NODE_RANGE: // Code for e{n,m} looks like: // // code for e --- prolog // repeat_start n, m, L1 --+ // L0: code for e | repeat // repeat_end n, m, L0 --+ // L1: split L2, L3 --- split // L2: code for e --- epilog // L3: // // Not all sections (prolog, repeat, split and epilog) are generated in all // cases, it depends on the values of n and m. The following table shows // which sections are generated for the first few values of n and m. // // n,m prolog repeat split epilog // (min,max) // --------------------------------------- // 0,0 - - - - // 0,1 - - X X // 0,2 - 0,1 X X // 0,3 - 0,2 X X // 0,M - 0,M-1 X X // // 1,1 X - - - // 1,2 X - X X // 1,3 X 0,1 X X // 1,4 X 1,2 X X // 1,M X 1,M-2 X X // // 2,2 X - - X // 2,3 X 1,1 X X // 2,4 X 1,2 X X // 2,M X 1,M-2 X X // // 3,3 X 1,1 - X // 3,4 X 2,2 X X // 3,M X 2,M-1 X X // // The code can't consists simply in the repeat section, the prolog and // epilog are required because we can't have atoms pointing to code inside // the repeat loop. Atoms' forwards_code will point to code in the prolog // and backwards_code will point to code in the epilog (or in prolog if // epilog wasn't generated, like in n=1,m=1) emit_prolog = re_node->start > 0; emit_repeat = re_node->end > re_node->start + 1 || re_node->end > 2; emit_split = re_node->end > re_node->start; emit_epilog = re_node->end > re_node->start || re_node->end > 1; if (emit_prolog) { FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags, &instruction_addr, &branch_size)); *code_size += branch_size; } if (emit_repeat) { repeat_args.min = re_node->start; repeat_args.max = re_node->end; if (emit_prolog) { repeat_args.max--; repeat_args.min--; } if (emit_split) repeat_args.max--; else repeat_args.min--; repeat_args.offset = 0; FAIL_ON_ERROR(_yr_emit_inst_arg_struct( emit_context, re_node->greedy ? RE_OPCODE_REPEAT_START_GREEDY : RE_OPCODE_REPEAT_START_UNGREEDY, &repeat_args, sizeof(repeat_args), emit_prolog ? NULL : &instruction_addr, (void**) &repeat_start_args_addr, &inst_size)); *code_size += inst_size; FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, flags | EMIT_DONT_SET_FORWARDS_CODE | EMIT_DONT_SET_BACKWARDS_CODE, NULL, &branch_size)); *code_size += branch_size; repeat_start_args_addr->offset = 2 * inst_size + branch_size; repeat_args.offset = -branch_size; FAIL_ON_ERROR(_yr_emit_inst_arg_struct( emit_context, re_node->greedy ? RE_OPCODE_REPEAT_END_GREEDY : RE_OPCODE_REPEAT_END_UNGREEDY, &repeat_args, sizeof(repeat_args), NULL, NULL, &inst_size)); *code_size += inst_size; } if (emit_split) { FAIL_ON_ERROR(_yr_emit_split( emit_context, re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B, 0, NULL, &split_offset_addr, &split_size)); *code_size += split_size; } if (emit_epilog) { FAIL_ON_ERROR(_yr_re_emit( emit_context, re_node->left, emit_prolog ? flags | EMIT_DONT_SET_FORWARDS_CODE : flags, emit_prolog || emit_repeat ? NULL : &instruction_addr, &branch_size)); *code_size += branch_size; } if (emit_split) *split_offset_addr = split_size + branch_size; break; } if (flags & EMIT_BACKWARDS) { if (!(flags & EMIT_DONT_SET_BACKWARDS_CODE)) re_node->backward_code = instruction_addr + *code_size; } else { if (!(flags & EMIT_DONT_SET_FORWARDS_CODE)) re_node->forward_code = instruction_addr; } if (code_addr != NULL) *code_addr = instruction_addr; return ERROR_SUCCESS; } int yr_re_ast_emit_code( RE_AST* re_ast, YR_ARENA* arena, int backwards_code) { RE_EMIT_CONTEXT emit_context; int code_size; int total_size; // Ensure that we have enough contiguous memory space in the arena to // contain the regular expression code. The code can't span over multiple // non-contiguous pages. FAIL_ON_ERROR(yr_arena_reserve_memory(arena, RE_MAX_CODE_SIZE)); // Emit code for matching the regular expressions forwards. total_size = 0; emit_context.arena = arena; emit_context.next_split_id = 0; FAIL_ON_ERROR(_yr_re_emit( &emit_context, re_ast->root_node, backwards_code ? EMIT_BACKWARDS : 0, NULL, &code_size)); total_size += code_size; FAIL_ON_ERROR(_yr_emit_inst( &emit_context, RE_OPCODE_MATCH, NULL, &code_size)); total_size += code_size; if (total_size > RE_MAX_CODE_SIZE) return ERROR_REGULAR_EXPRESSION_TOO_LARGE; return ERROR_SUCCESS; } int _yr_re_alloc_storage( RE_THREAD_STORAGE** storage) { *storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value( &thread_storage_key); if (*storage == NULL) { *storage = (RE_THREAD_STORAGE*) yr_malloc(sizeof(RE_THREAD_STORAGE)); if (*storage == NULL) return ERROR_INSUFFICIENT_MEMORY; (*storage)->fiber_pool.fiber_count = 0; (*storage)->fiber_pool.fibers.head = NULL; (*storage)->fiber_pool.fibers.tail = NULL; FAIL_ON_ERROR( yr_thread_storage_set_value(&thread_storage_key, *storage)); } return ERROR_SUCCESS; } int _yr_re_fiber_create( RE_FIBER_POOL* fiber_pool, RE_FIBER** new_fiber) { RE_FIBER* fiber; if (fiber_pool->fibers.head != NULL) { fiber = fiber_pool->fibers.head; fiber_pool->fibers.head = fiber->next; if (fiber_pool->fibers.tail == fiber) fiber_pool->fibers.tail = NULL; } else { if (fiber_pool->fiber_count == RE_MAX_FIBERS) return ERROR_TOO_MANY_RE_FIBERS; fiber = (RE_FIBER*) yr_malloc(sizeof(RE_FIBER)); if (fiber == NULL) return ERROR_INSUFFICIENT_MEMORY; fiber_pool->fiber_count++; } fiber->ip = NULL; fiber->sp = -1; fiber->rc = -1; fiber->next = NULL; fiber->prev = NULL; *new_fiber = fiber; return ERROR_SUCCESS; } // // _yr_re_fiber_append // // Appends 'fiber' to 'fiber_list' // void _yr_re_fiber_append( RE_FIBER_LIST* fiber_list, RE_FIBER* fiber) { assert(fiber->prev == NULL); assert(fiber->next == NULL); fiber->prev = fiber_list->tail; if (fiber_list->tail != NULL) fiber_list->tail->next = fiber; fiber_list->tail = fiber; if (fiber_list->head == NULL) fiber_list->head = fiber; assert(fiber_list->tail->next == NULL); assert(fiber_list->head->prev == NULL); } // // _yr_re_fiber_exists // // Verifies if a fiber with the same properties (ip, rc, sp, and stack values) // than 'target_fiber' exists in 'fiber_list'. The list is iterated from // the start until 'last_fiber' (inclusive). Fibers past 'last_fiber' are not // taken into account. // int _yr_re_fiber_exists( RE_FIBER_LIST* fiber_list, RE_FIBER* target_fiber, RE_FIBER* last_fiber) { RE_FIBER* fiber = fiber_list->head; int equal_stacks; int i; if (last_fiber == NULL) return FALSE; while (fiber != last_fiber->next) { if (fiber->ip == target_fiber->ip && fiber->sp == target_fiber->sp && fiber->rc == target_fiber->rc) { equal_stacks = TRUE; for (i = 0; i <= fiber->sp; i++) { if (fiber->stack[i] != target_fiber->stack[i]) { equal_stacks = FALSE; break; } } if (equal_stacks) return TRUE; } fiber = fiber->next; } return FALSE; } // // _yr_re_fiber_split // // Clones a fiber in fiber_list and inserts the cloned fiber just after. // the original one. If fiber_list is: // // f1 -> f2 -> f3 -> f4 // // Splitting f2 will result in: // // f1 -> f2 -> cloned f2 -> f3 -> f4 // int _yr_re_fiber_split( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber, RE_FIBER** new_fiber) { int32_t i; FAIL_ON_ERROR(_yr_re_fiber_create(fiber_pool, new_fiber)); (*new_fiber)->sp = fiber->sp; (*new_fiber)->ip = fiber->ip; (*new_fiber)->rc = fiber->rc; for (i = 0; i <= fiber->sp; i++) (*new_fiber)->stack[i] = fiber->stack[i]; (*new_fiber)->next = fiber->next; (*new_fiber)->prev = fiber; if (fiber->next != NULL) fiber->next->prev = *new_fiber; fiber->next = *new_fiber; if (fiber_list->tail == fiber) fiber_list->tail = *new_fiber; assert(fiber_list->tail->next == NULL); assert(fiber_list->head->prev == NULL); return ERROR_SUCCESS; } // // _yr_re_fiber_kill // // Kills a given fiber by removing it from the fiber list and putting it // in the fiber pool. // RE_FIBER* _yr_re_fiber_kill( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber) { RE_FIBER* next_fiber = fiber->next; if (fiber->prev != NULL) fiber->prev->next = next_fiber; if (next_fiber != NULL) next_fiber->prev = fiber->prev; if (fiber_pool->fibers.tail != NULL) fiber_pool->fibers.tail->next = fiber; if (fiber_list->tail == fiber) fiber_list->tail = fiber->prev; if (fiber_list->head == fiber) fiber_list->head = next_fiber; fiber->next = NULL; fiber->prev = fiber_pool->fibers.tail; fiber_pool->fibers.tail = fiber; if (fiber_pool->fibers.head == NULL) fiber_pool->fibers.head = fiber; return next_fiber; } // // _yr_re_fiber_kill_tail // // Kills all fibers from the given one up to the end of the fiber list. // void _yr_re_fiber_kill_tail( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber) { RE_FIBER* prev_fiber = fiber->prev; if (prev_fiber != NULL) prev_fiber->next = NULL; fiber->prev = fiber_pool->fibers.tail; if (fiber_pool->fibers.tail != NULL) fiber_pool->fibers.tail->next = fiber; fiber_pool->fibers.tail = fiber_list->tail; fiber_list->tail = prev_fiber; if (fiber_list->head == fiber) fiber_list->head = NULL; if (fiber_pool->fibers.head == NULL) fiber_pool->fibers.head = fiber; } // // _yr_re_fiber_kill_tail // // Kills all fibers in the fiber list. // void _yr_re_fiber_kill_all( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool) { if (fiber_list->head != NULL) _yr_re_fiber_kill_tail(fiber_list, fiber_pool, fiber_list->head); } // // _yr_re_fiber_sync // // Executes a fiber until reaching an "matching" instruction. A "matching" // instruction is one that actually reads a byte from the input and performs // some matching. If the fiber reaches a split instruction, the new fiber is // also synced. // int _yr_re_fiber_sync( RE_FIBER_LIST* fiber_list, RE_FIBER_POOL* fiber_pool, RE_FIBER* fiber_to_sync) { // A array for keeping track of which split instructions has been already // executed. Each split instruction within a regexp has an associated ID // between 0 and RE_MAX_SPLIT_ID. Keeping track of executed splits is // required to avoid infinite loops in regexps like (a*)* or (a|)* RE_SPLIT_ID_TYPE splits_executed[RE_MAX_SPLIT_ID]; RE_SPLIT_ID_TYPE splits_executed_count = 0; RE_SPLIT_ID_TYPE split_id, splits_executed_idx; int split_already_executed; RE_REPEAT_ARGS* repeat_args; RE_REPEAT_ANY_ARGS* repeat_any_args; RE_FIBER* fiber; RE_FIBER* last; RE_FIBER* prev; RE_FIBER* next; RE_FIBER* branch_a; RE_FIBER* branch_b; fiber = fiber_to_sync; prev = fiber_to_sync->prev; last = fiber_to_sync->next; while(fiber != last) { uint8_t opcode = *fiber->ip; switch(opcode) { case RE_OPCODE_SPLIT_A: case RE_OPCODE_SPLIT_B: split_id = *(RE_SPLIT_ID_TYPE*)(fiber->ip + 1); split_already_executed = FALSE; for (splits_executed_idx = 0; splits_executed_idx < splits_executed_count; splits_executed_idx++) { if (split_id == splits_executed[splits_executed_idx]) { split_already_executed = TRUE; break; } } if (split_already_executed) { fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber); } else { branch_a = fiber; FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); // With RE_OPCODE_SPLIT_A the current fiber continues at the next // instruction in the stream (branch A), while the newly created // fiber starts at the address indicated by the instruction (branch B) // RE_OPCODE_SPLIT_B has the opposite behavior. if (opcode == RE_OPCODE_SPLIT_B) yr_swap(branch_a, branch_b, RE_FIBER*); // Branch A continues at the next instruction branch_a->ip += (sizeof(RE_SPLIT_ID_TYPE) + 3); // Branch B adds the offset encoded in the opcode to its instruction // pointer. branch_b->ip += *(int16_t*)( branch_b->ip + 1 // opcode size + sizeof(RE_SPLIT_ID_TYPE)); splits_executed[splits_executed_count] = split_id; splits_executed_count++; } break; case RE_OPCODE_REPEAT_START_GREEDY: case RE_OPCODE_REPEAT_START_UNGREEDY: repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1); assert(repeat_args->max > 0); branch_a = fiber; if (repeat_args->min == 0) { FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); if (opcode == RE_OPCODE_REPEAT_START_UNGREEDY) yr_swap(branch_a, branch_b, RE_FIBER*); branch_b->ip += repeat_args->offset; } branch_a->stack[++branch_a->sp] = 0; branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS)); break; case RE_OPCODE_REPEAT_END_GREEDY: case RE_OPCODE_REPEAT_END_UNGREEDY: repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1); fiber->stack[fiber->sp]++; if (fiber->stack[fiber->sp] < repeat_args->min) { fiber->ip += repeat_args->offset; break; } branch_a = fiber; if (fiber->stack[fiber->sp] < repeat_args->max) { FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); if (opcode == RE_OPCODE_REPEAT_END_GREEDY) yr_swap(branch_a, branch_b, RE_FIBER*); branch_a->sp--; branch_b->ip += repeat_args->offset; } branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS)); break; case RE_OPCODE_REPEAT_ANY_GREEDY: case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(fiber->ip + 1); // If repetition counter (rc) is -1 it means that we are reaching this // instruction from the previous one in the instructions stream. In // this case let's initialize the counter to 0 and start looping. if (fiber->rc == -1) fiber->rc = 0; if (fiber->rc < repeat_any_args->min) { // Increase repetition counter and continue with next fiber. The // instruction pointer for this fiber is not incremented yet, this // fiber spins in this same instruction until reaching the minimum // number of repetitions. fiber->rc++; fiber = fiber->next; } else if (fiber->rc < repeat_any_args->max) { // Once the minimum number of repetitions are matched one fiber // remains spinning in this instruction until reaching the maximum // number of repetitions while new fibers are created. New fibers // start executing at the next instruction. next = fiber->next; branch_a = fiber; FAIL_ON_ERROR(_yr_re_fiber_split( fiber_list, fiber_pool, branch_a, &branch_b)); if (opcode == RE_OPCODE_REPEAT_ANY_UNGREEDY) yr_swap(branch_a, branch_b, RE_FIBER*); branch_a->rc++; branch_b->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS)); branch_b->rc = -1; _yr_re_fiber_sync(fiber_list, fiber_pool, branch_b); fiber = next; } else { // When the maximum number of repetitions is reached the fiber keeps // executing at the next instruction. The repetition counter is set // to -1 indicating that we are not spinning in a repeat instruction // anymore. fiber->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS)); fiber->rc = -1; } break; case RE_OPCODE_JUMP: fiber->ip += *(int16_t*)(fiber->ip + 1); break; default: if (_yr_re_fiber_exists(fiber_list, fiber, prev)) fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber); else fiber = fiber->next; } } return ERROR_SUCCESS; } // // yr_re_exec // // Executes a regular expression. The specified regular expression will try to // match the data starting at the address specified by "input". The "input" // pointer can point to any address inside a memory buffer. Arguments // "input_forwards_size" and "input_backwards_size" indicate how many bytes // can be accesible starting at "input" and going forwards and backwards // respectively. // // <--- input_backwards_size -->|<----------- input_forwards_size --------> // |-------- memory buffer -----------------------------------------------| // ^ // input // // Args: // uint8_t* re_code - Regexp code be executed // uint8_t* input - Pointer to input data // size_t input_forwards_size - Number of accessible bytes starting at // "input" and going forwards. // size_t input_backwards_size - Number of accessible bytes starting at // "input" and going backwards // int flags - Flags: // RE_FLAGS_SCAN // RE_FLAGS_BACKWARDS // RE_FLAGS_EXHAUSTIVE // RE_FLAGS_WIDE // RE_FLAGS_NO_CASE // RE_FLAGS_DOT_ALL // RE_MATCH_CALLBACK_FUNC callback - Callback function // void* callback_args - Callback argument // // Returns: // Integer indicating the number of matching bytes, including 0 when // matching an empty regexp. Negative values indicate: // -1 No match // -2 Not enough memory // -3 Too many matches // -4 Too many fibers // -5 Unknown fatal error int yr_re_exec( uint8_t* re_code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args) { uint8_t* ip; uint8_t* input; uint8_t mask; uint8_t value; RE_FIBER_LIST fibers; RE_THREAD_STORAGE* storage; RE_FIBER* fiber; RE_FIBER* next_fiber; int error; int bytes_matched; int max_bytes_matched; int match; int character_size; int input_incr; int kill; int action; int result = -1; #define ACTION_NONE 0 #define ACTION_CONTINUE 1 #define ACTION_KILL 2 #define ACTION_KILL_TAIL 3 #define prolog { \ if ((bytes_matched >= max_bytes_matched) || \ (character_size == 2 && *(input + 1) != 0)) \ { \ action = ACTION_KILL; \ break; \ } \ } #define fail_if_error(e) { \ switch (e) { \ case ERROR_INSUFFICIENT_MEMORY: \ return -2; \ case ERROR_TOO_MANY_RE_FIBERS: \ return -4; \ } \ } if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS) return -2; if (flags & RE_FLAGS_WIDE) character_size = 2; else character_size = 1; input = input_data; input_incr = character_size; if (flags & RE_FLAGS_BACKWARDS) { max_bytes_matched = (int) yr_min(input_backwards_size, RE_SCAN_LIMIT); input -= character_size; input_incr = -input_incr; } else { max_bytes_matched = (int) yr_min(input_forwards_size, RE_SCAN_LIMIT); } // Round down max_bytes_matched to a multiple of character_size, this way if // character_size is 2 and max_bytes_matched is odd we are ignoring the // extra byte which can't match anyways. max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size; bytes_matched = 0; error = _yr_re_fiber_create(&storage->fiber_pool, &fiber); fail_if_error(error); fiber->ip = re_code; fibers.head = fiber; fibers.tail = fiber; error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); while (fibers.head != NULL) { fiber = fibers.head; while(fiber != NULL) { ip = fiber->ip; action = ACTION_NONE; switch(*ip) { case RE_OPCODE_ANY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_REPEAT_ANY_GREEDY: case RE_OPCODE_REPEAT_ANY_UNGREEDY: prolog; match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A); action = match ? ACTION_NONE : ACTION_KILL; // The instruction pointer is not incremented here. The current fiber // spins in this instruction until reaching the required number of // repetitions. The code controlling the number of repetitions is in // _yr_re_fiber_sync. break; case RE_OPCODE_LITERAL: prolog; if (flags & RE_FLAGS_NO_CASE) match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)]; else match = (*input == *(ip + 1)); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 2; break; case RE_OPCODE_MASKED_LITERAL: prolog; value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; // We don't need to take into account the case-insensitive // case because this opcode is only used with hex strings, // which can't be case-insensitive. match = ((*input & mask) == value); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 3; break; case RE_OPCODE_CLASS: prolog; match = CHAR_IN_CLASS(*input, ip + 1); if (!match && (flags & RE_FLAGS_NO_CASE)) match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 33; break; case RE_OPCODE_WORD_CHAR: prolog; match = _yr_re_is_word_char(input, character_size); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_WORD_CHAR: prolog; match = !_yr_re_is_word_char(input, character_size); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_SPACE: case RE_OPCODE_NON_SPACE: prolog; switch(*input) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': match = TRUE; break; default: match = FALSE; } if (*ip == RE_OPCODE_NON_SPACE) match = !match; action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_DIGIT: prolog; match = isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_NON_DIGIT: prolog; match = !isdigit(*input); action = match ? ACTION_NONE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_WORD_BOUNDARY: case RE_OPCODE_NON_WORD_BOUNDARY: if (bytes_matched == 0 && input_backwards_size < character_size) { match = TRUE; } else if (bytes_matched >= max_bytes_matched) { match = TRUE; } else { assert(input < input_data + input_forwards_size); assert(input >= input_data - input_backwards_size); assert(input - input_incr < input_data + input_forwards_size); assert(input - input_incr >= input_data - input_backwards_size); match = _yr_re_is_word_char(input, character_size) != \ _yr_re_is_word_char(input - input_incr, character_size); } if (*ip == RE_OPCODE_NON_WORD_BOUNDARY) match = !match; action = match ? ACTION_CONTINUE : ACTION_KILL; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_START: if (flags & RE_FLAGS_BACKWARDS) kill = input_backwards_size > (size_t) bytes_matched; else kill = input_backwards_size > 0 || (bytes_matched != 0); action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH_AT_END: kill = flags & RE_FLAGS_BACKWARDS || input_forwards_size > (size_t) bytes_matched; action = kill ? ACTION_KILL : ACTION_CONTINUE; fiber->ip += 1; break; case RE_OPCODE_MATCH: result = bytes_matched; if (flags & RE_FLAGS_EXHAUSTIVE) { if (callback != NULL) { int cb_result; if (flags & RE_FLAGS_BACKWARDS) cb_result = callback( input + character_size, bytes_matched, flags, callback_args); else cb_result = callback( input_data, bytes_matched, flags, callback_args); switch(cb_result) { case ERROR_INSUFFICIENT_MEMORY: return -2; case ERROR_TOO_MANY_MATCHES: return -3; default: if (cb_result != ERROR_SUCCESS) return -4; } } action = ACTION_KILL; } else { action = ACTION_KILL_TAIL; } break; default: assert(FALSE); } switch(action) { case ACTION_KILL: fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber); break; case ACTION_KILL_TAIL: _yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber); fiber = NULL; break; case ACTION_CONTINUE: error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); break; default: next_fiber = fiber->next; error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); fiber = next_fiber; } } input += input_incr; bytes_matched += character_size; if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched) { error = _yr_re_fiber_create(&storage->fiber_pool, &fiber); fail_if_error(error); fiber->ip = re_code; _yr_re_fiber_append(&fibers, fiber); error = _yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber); fail_if_error(error); } } return result; } int yr_re_fast_exec( uint8_t* code, uint8_t* input_data, size_t input_forwards_size, size_t input_backwards_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args) { RE_REPEAT_ANY_ARGS* repeat_any_args; uint8_t* code_stack[MAX_FAST_RE_STACK]; uint8_t* input_stack[MAX_FAST_RE_STACK]; int matches_stack[MAX_FAST_RE_STACK]; uint8_t* ip = code; uint8_t* input = input_data; uint8_t* next_input; uint8_t* next_opcode; uint8_t mask; uint8_t value; int i; int stop; int input_incr; int sp = 0; int bytes_matched; int max_bytes_matched; max_bytes_matched = flags & RE_FLAGS_BACKWARDS ? input_backwards_size : input_forwards_size; input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1; if (flags & RE_FLAGS_BACKWARDS) input--; code_stack[sp] = code; input_stack[sp] = input; matches_stack[sp] = 0; sp++; while (sp > 0) { sp--; ip = code_stack[sp]; input = input_stack[sp]; bytes_matched = matches_stack[sp]; stop = FALSE; while(!stop) { if (*ip == RE_OPCODE_MATCH) { if (flags & RE_FLAGS_EXHAUSTIVE) { int cb_result = callback( flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data, bytes_matched, flags, callback_args); switch(cb_result) { case ERROR_INSUFFICIENT_MEMORY: return -2; case ERROR_TOO_MANY_MATCHES: return -3; default: if (cb_result != ERROR_SUCCESS) return -4; } break; } else { return bytes_matched; } } if (bytes_matched >= max_bytes_matched) break; switch(*ip) { case RE_OPCODE_LITERAL: if (*input == *(ip + 1)) { bytes_matched++; input += input_incr; ip += 2; } else { stop = TRUE; } break; case RE_OPCODE_MASKED_LITERAL: value = *(int16_t*)(ip + 1) & 0xFF; mask = *(int16_t*)(ip + 1) >> 8; if ((*input & mask) == value) { bytes_matched++; input += input_incr; ip += 3; } else { stop = TRUE; } break; case RE_OPCODE_ANY: bytes_matched++; input += input_incr; ip += 1; break; case RE_OPCODE_REPEAT_ANY_UNGREEDY: repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1); next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS); for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++) { next_input = input + i * input_incr; if (bytes_matched + i >= max_bytes_matched) break; if ( *(next_opcode) != RE_OPCODE_LITERAL || (*(next_opcode) == RE_OPCODE_LITERAL && *(next_opcode + 1) == *next_input)) { if (sp >= MAX_FAST_RE_STACK) return -4; code_stack[sp] = next_opcode; input_stack[sp] = next_input; matches_stack[sp] = bytes_matched + i; sp++; } } input += input_incr * repeat_any_args->min; bytes_matched += repeat_any_args->min; ip = next_opcode; break; default: assert(FALSE); } } } return -1; } void _yr_re_print_node( RE_NODE* re_node) { int i; if (re_node == NULL) return; switch(re_node->type) { case RE_NODE_ALT: printf("Alt("); _yr_re_print_node(re_node->left); printf(", "); _yr_re_print_node(re_node->right); printf(")"); break; case RE_NODE_CONCAT: printf("Cat("); _yr_re_print_node(re_node->left); printf(", "); _yr_re_print_node(re_node->right); printf(")"); break; case RE_NODE_STAR: printf("Star("); _yr_re_print_node(re_node->left); printf(")"); break; case RE_NODE_PLUS: printf("Plus("); _yr_re_print_node(re_node->left); printf(")"); break; case RE_NODE_LITERAL: printf("Lit(%02X)", re_node->value); break; case RE_NODE_MASKED_LITERAL: printf("MaskedLit(%02X,%02X)", re_node->value, re_node->mask); break; case RE_NODE_WORD_CHAR: printf("WordChar"); break; case RE_NODE_NON_WORD_CHAR: printf("NonWordChar"); break; case RE_NODE_SPACE: printf("Space"); break; case RE_NODE_NON_SPACE: printf("NonSpace"); break; case RE_NODE_DIGIT: printf("Digit"); break; case RE_NODE_NON_DIGIT: printf("NonDigit"); break; case RE_NODE_ANY: printf("Any"); break; case RE_NODE_RANGE: printf("Range(%d-%d, ", re_node->start, re_node->end); _yr_re_print_node(re_node->left); printf(")"); break; case RE_NODE_CLASS: printf("Class("); for (i = 0; i < 256; i++) if (CHAR_IN_CLASS(i, re_node->class_vector)) printf("%02X,", i); printf(")"); break; default: printf("???"); break; } } void yr_re_print( RE_AST* re_ast) { _yr_re_print_node(re_ast->root_node); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3328_2
crossvul-cpp_data_good_3870_0
/* * The Python Imaging Library. * $Id$ * * decoder for PCX image data. * * history: * 95-09-14 fl Created * * Copyright (c) Fredrik Lundh 1995. * Copyright (c) Secret Labs AB 1997. * * See the README file for information on usage and redistribution. */ #include "Imaging.h" int ImagingPcxDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 n; UINT8* ptr; if ((state->xsize * state->bits + 7) / 8 > state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr = buf; for (;;) { if (bytes < 1) return ptr - buf; if ((*ptr & 0xC0) == 0xC0) { /* Run */ if (bytes < 2) return ptr - buf; n = ptr[0] & 0x3F; while (n > 0) { if (state->x >= state->bytes) { state->errcode = IMAGING_CODEC_OVERRUN; break; } state->buffer[state->x++] = ptr[1]; n--; } ptr += 2; bytes -= 2; } else { /* Literal */ state->buffer[state->x++] = ptr[0]; ptr++; bytes--; } if (state->x >= state->bytes) { if (state->bytes % state->xsize && state->bytes > state->xsize) { int bands = state->bytes / state->xsize; int stride = state->bytes / bands; int i; for (i=1; i< bands; i++) { // note -- skipping first band memmove(&state->buffer[i*state->xsize], &state->buffer[i*stride], state->xsize); } } /* Got a full line, unpack it */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->x = 0; if (++state->y >= state->ysize) { /* End of file (errcode = 0) */ return -1; } } } }
./CrossVul/dataset_final_sorted/CWE-125/c/good_3870_0
crossvul-cpp_data_bad_5009_1
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_apps_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "openjpeg.h" #include "convert.h" typedef struct { OPJ_UINT16 bfType; /* 'BM' for Bitmap (19776) */ OPJ_UINT32 bfSize; /* Size of the file */ OPJ_UINT16 bfReserved1; /* Reserved : 0 */ OPJ_UINT16 bfReserved2; /* Reserved : 0 */ OPJ_UINT32 bfOffBits; /* Offset */ } OPJ_BITMAPFILEHEADER; typedef struct { OPJ_UINT32 biSize; /* Size of the structure in bytes */ OPJ_UINT32 biWidth; /* Width of the image in pixels */ OPJ_UINT32 biHeight; /* Heigth of the image in pixels */ OPJ_UINT16 biPlanes; /* 1 */ OPJ_UINT16 biBitCount; /* Number of color bits by pixels */ OPJ_UINT32 biCompression; /* Type of encoding 0: none 1: RLE8 2: RLE4 */ OPJ_UINT32 biSizeImage; /* Size of the image in bytes */ OPJ_UINT32 biXpelsPerMeter; /* Horizontal (X) resolution in pixels/meter */ OPJ_UINT32 biYpelsPerMeter; /* Vertical (Y) resolution in pixels/meter */ OPJ_UINT32 biClrUsed; /* Number of color used in the image (0: ALL) */ OPJ_UINT32 biClrImportant; /* Number of important color (0: ALL) */ OPJ_UINT32 biRedMask; /* Red channel bit mask */ OPJ_UINT32 biGreenMask; /* Green channel bit mask */ OPJ_UINT32 biBlueMask; /* Blue channel bit mask */ OPJ_UINT32 biAlphaMask; /* Alpha channel bit mask */ OPJ_UINT32 biColorSpaceType; /* Color space type */ OPJ_UINT8 biColorSpaceEP[36]; /* Color space end points */ OPJ_UINT32 biRedGamma; /* Red channel gamma */ OPJ_UINT32 biGreenGamma; /* Green channel gamma */ OPJ_UINT32 biBlueGamma; /* Blue channel gamma */ OPJ_UINT32 biIntent; /* Intent */ OPJ_UINT32 biIccProfileData; /* ICC profile data */ OPJ_UINT32 biIccProfileSize; /* ICC profile size */ OPJ_UINT32 biReserved; /* Reserved */ } OPJ_BITMAPINFOHEADER; static void opj_applyLUT8u_8u32s_C1R( OPJ_UINT8 const* pSrc, OPJ_INT32 srcStride, OPJ_INT32* pDst, OPJ_INT32 dstStride, OPJ_UINT8 const* pLUT, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 y; for (y = height; y != 0U; --y) { OPJ_UINT32 x; for(x = 0; x < width; x++) { pDst[x] = (OPJ_INT32)pLUT[pSrc[x]]; } pSrc += srcStride; pDst += dstStride; } } static void opj_applyLUT8u_8u32s_C1P3R( OPJ_UINT8 const* pSrc, OPJ_INT32 srcStride, OPJ_INT32* const* pDst, OPJ_INT32 const* pDstStride, OPJ_UINT8 const* const* pLUT, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 y; OPJ_INT32* pR = pDst[0]; OPJ_INT32* pG = pDst[1]; OPJ_INT32* pB = pDst[2]; OPJ_UINT8 const* pLUT_R = pLUT[0]; OPJ_UINT8 const* pLUT_G = pLUT[1]; OPJ_UINT8 const* pLUT_B = pLUT[2]; for (y = height; y != 0U; --y) { OPJ_UINT32 x; for(x = 0; x < width; x++) { OPJ_UINT8 idx = pSrc[x]; pR[x] = (OPJ_INT32)pLUT_R[idx]; pG[x] = (OPJ_INT32)pLUT_G[idx]; pB[x] = (OPJ_INT32)pLUT_B[idx]; } pSrc += srcStride; pR += pDstStride[0]; pG += pDstStride[1]; pB += pDstStride[2]; } } static void bmp24toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; width = image->comps[0].w; height = image->comps[0].h; index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { image->comps[0].data[index] = (OPJ_INT32)pSrc[3*x+2]; /* R */ image->comps[1].data[index] = (OPJ_INT32)pSrc[3*x+1]; /* G */ image->comps[2].data[index] = (OPJ_INT32)pSrc[3*x+0]; /* B */ index++; } pSrc -= stride; } } static void bmp_mask_get_shift_and_prec(OPJ_UINT32 mask, OPJ_UINT32* shift, OPJ_UINT32* prec) { OPJ_UINT32 l_shift, l_prec; l_shift = l_prec = 0U; if (mask != 0U) { while ((mask & 1U) == 0U) { mask >>= 1; l_shift++; } while (mask & 1U) { mask >>= 1; l_prec++; } } *shift = l_shift; *prec = l_prec; } static void bmpmask32toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask, OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; OPJ_BOOL hasAlpha; OPJ_UINT32 redShift, redPrec; OPJ_UINT32 greenShift, greenPrec; OPJ_UINT32 blueShift, bluePrec; OPJ_UINT32 alphaShift, alphaPrec; width = image->comps[0].w; height = image->comps[0].h; hasAlpha = image->numcomps > 3U; bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec); bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec); bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec); bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec); image->comps[0].bpp = redPrec; image->comps[0].prec = redPrec; image->comps[1].bpp = greenPrec; image->comps[1].prec = greenPrec; image->comps[2].bpp = bluePrec; image->comps[2].prec = bluePrec; if (hasAlpha) { image->comps[3].bpp = alphaPrec; image->comps[3].prec = alphaPrec; } index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { OPJ_UINT32 value = 0U; value |= ((OPJ_UINT32)pSrc[4*x+0]) << 0; value |= ((OPJ_UINT32)pSrc[4*x+1]) << 8; value |= ((OPJ_UINT32)pSrc[4*x+2]) << 16; value |= ((OPJ_UINT32)pSrc[4*x+3]) << 24; image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >> redShift); /* R */ image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >> greenShift); /* G */ image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >> blueShift); /* B */ if (hasAlpha) { image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >> alphaShift); /* A */ } index++; } pSrc -= stride; } } static void bmpmask16toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT32 redMask, OPJ_UINT32 greenMask, OPJ_UINT32 blueMask, OPJ_UINT32 alphaMask) { int index; OPJ_UINT32 width, height; OPJ_UINT32 x, y; const OPJ_UINT8 *pSrc = NULL; OPJ_BOOL hasAlpha; OPJ_UINT32 redShift, redPrec; OPJ_UINT32 greenShift, greenPrec; OPJ_UINT32 blueShift, bluePrec; OPJ_UINT32 alphaShift, alphaPrec; width = image->comps[0].w; height = image->comps[0].h; hasAlpha = image->numcomps > 3U; bmp_mask_get_shift_and_prec(redMask, &redShift, &redPrec); bmp_mask_get_shift_and_prec(greenMask, &greenShift, &greenPrec); bmp_mask_get_shift_and_prec(blueMask, &blueShift, &bluePrec); bmp_mask_get_shift_and_prec(alphaMask, &alphaShift, &alphaPrec); image->comps[0].bpp = redPrec; image->comps[0].prec = redPrec; image->comps[1].bpp = greenPrec; image->comps[1].prec = greenPrec; image->comps[2].bpp = bluePrec; image->comps[2].prec = bluePrec; if (hasAlpha) { image->comps[3].bpp = alphaPrec; image->comps[3].prec = alphaPrec; } index = 0; pSrc = pData + (height - 1U) * stride; for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { OPJ_UINT32 value = 0U; value |= ((OPJ_UINT32)pSrc[2*x+0]) << 0; value |= ((OPJ_UINT32)pSrc[2*x+1]) << 8; image->comps[0].data[index] = (OPJ_INT32)((value & redMask) >> redShift); /* R */ image->comps[1].data[index] = (OPJ_INT32)((value & greenMask) >> greenShift); /* G */ image->comps[2].data[index] = (OPJ_INT32)((value & blueMask) >> blueShift); /* B */ if (hasAlpha) { image->comps[3].data[index] = (OPJ_INT32)((value & alphaMask) >> alphaShift); /* A */ } index++; } pSrc -= stride; } } static opj_image_t* bmp8toimage(const OPJ_UINT8* pData, OPJ_UINT32 stride, opj_image_t* image, OPJ_UINT8 const* const* pLUT) { OPJ_UINT32 width, height; const OPJ_UINT8 *pSrc = NULL; width = image->comps[0].w; height = image->comps[0].h; pSrc = pData + (height - 1U) * stride; if (image->numcomps == 1U) { opj_applyLUT8u_8u32s_C1R(pSrc, -(OPJ_INT32)stride, image->comps[0].data, (OPJ_INT32)width, pLUT[0], width, height); } else { OPJ_INT32* pDst[3]; OPJ_INT32 pDstStride[3]; pDst[0] = image->comps[0].data; pDst[1] = image->comps[1].data; pDst[2] = image->comps[2].data; pDstStride[0] = (OPJ_INT32)width; pDstStride[1] = (OPJ_INT32)width; pDstStride[2] = (OPJ_INT32)width; opj_applyLUT8u_8u32s_C1P3R(pSrc, -(OPJ_INT32)stride, pDst, pDstStride, pLUT, width, height); } return image; } static OPJ_BOOL bmp_read_file_header(FILE* IN, OPJ_BITMAPFILEHEADER* header) { header->bfType = (OPJ_UINT16)getc(IN); header->bfType |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if (header->bfType != 19778) { fprintf(stderr,"Error, not a BMP file!\n"); return OPJ_FALSE; } /* FILE HEADER */ /* ------------- */ header->bfSize = (OPJ_UINT32)getc(IN); header->bfSize |= (OPJ_UINT32)getc(IN) << 8; header->bfSize |= (OPJ_UINT32)getc(IN) << 16; header->bfSize |= (OPJ_UINT32)getc(IN) << 24; header->bfReserved1 = (OPJ_UINT16)getc(IN); header->bfReserved1 |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->bfReserved2 = (OPJ_UINT16)getc(IN); header->bfReserved2 |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->bfOffBits = (OPJ_UINT32)getc(IN); header->bfOffBits |= (OPJ_UINT32)getc(IN) << 8; header->bfOffBits |= (OPJ_UINT32)getc(IN) << 16; header->bfOffBits |= (OPJ_UINT32)getc(IN) << 24; return OPJ_TRUE; } static OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header) { memset(header, 0, sizeof(*header)); /* INFO HEADER */ /* ------------- */ header->biSize = (OPJ_UINT32)getc(IN); header->biSize |= (OPJ_UINT32)getc(IN) << 8; header->biSize |= (OPJ_UINT32)getc(IN) << 16; header->biSize |= (OPJ_UINT32)getc(IN) << 24; switch (header->biSize) { case 12U: /* BITMAPCOREHEADER */ case 40U: /* BITMAPINFOHEADER */ case 52U: /* BITMAPV2INFOHEADER */ case 56U: /* BITMAPV3INFOHEADER */ case 108U: /* BITMAPV4HEADER */ case 124U: /* BITMAPV5HEADER */ break; default: fprintf(stderr,"Error, unknown BMP header size %d\n", header->biSize); return OPJ_FALSE; } header->biWidth = (OPJ_UINT32)getc(IN); header->biWidth |= (OPJ_UINT32)getc(IN) << 8; header->biWidth |= (OPJ_UINT32)getc(IN) << 16; header->biWidth |= (OPJ_UINT32)getc(IN) << 24; header->biHeight = (OPJ_UINT32)getc(IN); header->biHeight |= (OPJ_UINT32)getc(IN) << 8; header->biHeight |= (OPJ_UINT32)getc(IN) << 16; header->biHeight |= (OPJ_UINT32)getc(IN) << 24; header->biPlanes = (OPJ_UINT16)getc(IN); header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->biBitCount = (OPJ_UINT16)getc(IN); header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if(header->biSize >= 40U) { header->biCompression = (OPJ_UINT32)getc(IN); header->biCompression |= (OPJ_UINT32)getc(IN) << 8; header->biCompression |= (OPJ_UINT32)getc(IN) << 16; header->biCompression |= (OPJ_UINT32)getc(IN) << 24; header->biSizeImage = (OPJ_UINT32)getc(IN); header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24; header->biXpelsPerMeter = (OPJ_UINT32)getc(IN); header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biYpelsPerMeter = (OPJ_UINT32)getc(IN); header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biClrUsed = (OPJ_UINT32)getc(IN); header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24; header->biClrImportant = (OPJ_UINT32)getc(IN); header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24; } if(header->biSize >= 56U) { header->biRedMask = (OPJ_UINT32)getc(IN); header->biRedMask |= (OPJ_UINT32)getc(IN) << 8; header->biRedMask |= (OPJ_UINT32)getc(IN) << 16; header->biRedMask |= (OPJ_UINT32)getc(IN) << 24; header->biGreenMask = (OPJ_UINT32)getc(IN); header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24; header->biBlueMask = (OPJ_UINT32)getc(IN); header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24; header->biAlphaMask = (OPJ_UINT32)getc(IN); header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24; } if(header->biSize >= 108U) { header->biColorSpaceType = (OPJ_UINT32)getc(IN); header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24; if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP), IN) != sizeof(header->biColorSpaceEP)) { fprintf(stderr,"Error, can't read BMP header\n"); return OPJ_FALSE; } header->biRedGamma = (OPJ_UINT32)getc(IN); header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24; header->biGreenGamma = (OPJ_UINT32)getc(IN); header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24; header->biBlueGamma = (OPJ_UINT32)getc(IN); header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24; } if(header->biSize >= 124U) { header->biIntent = (OPJ_UINT32)getc(IN); header->biIntent |= (OPJ_UINT32)getc(IN) << 8; header->biIntent |= (OPJ_UINT32)getc(IN) << 16; header->biIntent |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileData = (OPJ_UINT32)getc(IN); header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileSize = (OPJ_UINT32)getc(IN); header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24; header->biReserved = (OPJ_UINT32)getc(IN); header->biReserved |= (OPJ_UINT32)getc(IN) << 8; header->biReserved |= (OPJ_UINT32)getc(IN) << 16; header->biReserved |= (OPJ_UINT32)getc(IN) << 24; } return OPJ_TRUE; } static OPJ_BOOL bmp_read_raw_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_ARG_NOT_USED(width); if ( fread(pData, sizeof(OPJ_UINT8), stride * height, IN) != (stride * height) ) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while (y < height) { int c = getc(IN); if (c) { int j; OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = c1; } } else { c = getc(IN); if (c == 0x00) { /* EOL */ x = 0; ++y; pix = pData + y * stride + x; } else if (c == 0x01) { /* EOP */ break; } else if (c == 0x02) { /* MOVE by dxdy */ c = getc(IN); x += (OPJ_UINT32)c; c = getc(IN); y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else /* 03 .. 255 */ { int j; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); *pix = c1; } if ((OPJ_UINT32)c & 1U) { /* skip padding byte */ getc(IN); } } } }/* while() */ return OPJ_TRUE; } static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData, OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height) { OPJ_UINT32 x, y; OPJ_UINT8 *pix; const OPJ_UINT8 *beyond; beyond = pData + stride * height; pix = pData; x = y = 0U; while(y < height) { int c = getc(IN); if(c == EOF) break; if(c) {/* encoded mode */ int j; OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN); for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { *pix = (OPJ_UINT8)((j&1) ? (c1 & 0x0fU) : ((c1>>4)&0x0fU)); } } else { /* absolute mode */ c = getc(IN); if(c == EOF) break; if(c == 0x00) { /* EOL */ x = 0; y++; pix = pData + y * stride; } else if(c == 0x01) { /* EOP */ break; } else if(c == 0x02) { /* MOVE by dxdy */ c = getc(IN); x += (OPJ_UINT32)c; c = getc(IN); y += (OPJ_UINT32)c; pix = pData + y * stride + x; } else { /* 03 .. 255 : absolute mode */ int j; OPJ_UINT8 c1 = 0U; for (j = 0; (j < c) && (x < width) && ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) { if((j&1) == 0) { c1 = (OPJ_UINT8)getc(IN); } *pix = (OPJ_UINT8)((j&1) ? (c1 & 0x0fU) : ((c1>>4)&0x0fU)); } if(((c&3) == 1) || ((c&3) == 2)) { /* skip padding byte */ getc(IN); } } } } /* while(y < height) */ return OPJ_TRUE; } opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters) { opj_image_cmptparm_t cmptparm[4]; /* maximum of 4 components */ OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256]; OPJ_UINT8 const* pLUT[3]; opj_image_t * image = NULL; FILE *IN; OPJ_BITMAPFILEHEADER File_h; OPJ_BITMAPINFOHEADER Info_h; OPJ_UINT32 i, palette_len, numcmpts = 1U; OPJ_BOOL l_result = OPJ_FALSE; OPJ_UINT8* pData = NULL; OPJ_UINT32 stride; pLUT[0] = lut_R; pLUT[1] = lut_G; pLUT[2] = lut_B; IN = fopen(filename, "rb"); if (!IN) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return NULL; } if (!bmp_read_file_header(IN, &File_h)) { fclose(IN); return NULL; } if (!bmp_read_info_header(IN, &Info_h)) { fclose(IN); return NULL; } /* Load palette */ if (Info_h.biBitCount <= 8U) { memset(&lut_R[0], 0, sizeof(lut_R)); memset(&lut_G[0], 0, sizeof(lut_G)); memset(&lut_B[0], 0, sizeof(lut_B)); palette_len = Info_h.biClrUsed; if((palette_len == 0U) && (Info_h.biBitCount <= 8U)) { palette_len = (1U << Info_h.biBitCount); } if (palette_len > 256U) { palette_len = 256U; } if (palette_len > 0U) { OPJ_UINT8 has_color = 0U; for (i = 0U; i < palette_len; i++) { lut_B[i] = (OPJ_UINT8)getc(IN); lut_G[i] = (OPJ_UINT8)getc(IN); lut_R[i] = (OPJ_UINT8)getc(IN); (void)getc(IN); /* padding */ has_color |= (lut_B[i] ^ lut_G[i]) | (lut_G[i] ^ lut_R[i]); } if(has_color) { numcmpts = 3U; } } } else { numcmpts = 3U; if ((Info_h.biCompression == 3) && (Info_h.biAlphaMask != 0U)) { numcmpts++; } } stride = ((Info_h.biWidth * Info_h.biBitCount + 31U) / 32U) * 4U; /* rows are aligned on 32bits */ if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /* RLE 4 gets decoded as 8 bits data for now... */ stride = ((Info_h.biWidth * 8U + 31U) / 32U) * 4U; } pData = (OPJ_UINT8 *) calloc(1, stride * Info_h.biHeight * sizeof(OPJ_UINT8)); if (pData == NULL) { fclose(IN); return NULL; } /* Place the cursor at the beginning of the image information */ fseek(IN, 0, SEEK_SET); fseek(IN, (long)File_h.bfOffBits, SEEK_SET); switch (Info_h.biCompression) { case 0: case 3: /* read raw data */ l_result = bmp_read_raw_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 1: /* read rle8 data */ l_result = bmp_read_rle8_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; case 2: /* read rle4 data */ l_result = bmp_read_rle4_data(IN, pData, stride, Info_h.biWidth, Info_h.biHeight); break; default: fprintf(stderr, "Unsupported BMP compression\n"); l_result = OPJ_FALSE; break; } if (!l_result) { free(pData); fclose(IN); return NULL; } /* create the image */ memset(&cmptparm[0], 0, sizeof(cmptparm)); for(i = 0; i < 4U; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)parameters->subsampling_dy; cmptparm[i].w = Info_h.biWidth; cmptparm[i].h = Info_h.biHeight; } image = opj_image_create(numcmpts, &cmptparm[0], (numcmpts == 1U) ? OPJ_CLRSPC_GRAY : OPJ_CLRSPC_SRGB); if(!image) { fclose(IN); free(pData); return NULL; } if (numcmpts == 4U) { image->comps[3].alpha = 1; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = image->x0 + (Info_h.biWidth - 1U) * (OPJ_UINT32)parameters->subsampling_dx + 1U; image->y1 = image->y0 + (Info_h.biHeight - 1U) * (OPJ_UINT32)parameters->subsampling_dy + 1U; /* Read the data */ if (Info_h.biBitCount == 24 && Info_h.biCompression == 0) { /*RGB */ bmp24toimage(pData, stride, image); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 0) { /* RGB 8bpp Indexed */ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 8 && Info_h.biCompression == 1) { /*RLE8*/ bmp8toimage(pData, stride, image, pLUT); } else if (Info_h.biBitCount == 4 && Info_h.biCompression == 2) { /*RLE4*/ bmp8toimage(pData, stride, image, pLUT); /* RLE 4 gets decoded as 8 bits data for now */ } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 0) { /* RGBX */ bmpmask32toimage(pData, stride, image, 0x00FF0000U, 0x0000FF00U, 0x000000FFU, 0x00000000U); } else if (Info_h.biBitCount == 32 && Info_h.biCompression == 3) { /* bitmask */ bmpmask32toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 0) { /* RGBX */ bmpmask16toimage(pData, stride, image, 0x7C00U, 0x03E0U, 0x001FU, 0x0000U); } else if (Info_h.biBitCount == 16 && Info_h.biCompression == 3) { /* bitmask */ if ((Info_h.biRedMask == 0U) && (Info_h.biGreenMask == 0U) && (Info_h.biBlueMask == 0U)) { Info_h.biRedMask = 0xF800U; Info_h.biGreenMask = 0x07E0U; Info_h.biBlueMask = 0x001FU; } bmpmask16toimage(pData, stride, image, Info_h.biRedMask, Info_h.biGreenMask, Info_h.biBlueMask, Info_h.biAlphaMask); } else { opj_image_destroy(image); image = NULL; fprintf(stderr, "Other system than 24 bits/pixels or 8 bits (no RLE coding) is not yet implemented [%d]\n", Info_h.biBitCount); } free(pData); fclose(IN); return image; } int imagetobmp(opj_image_t * image, const char *outfile) { int w, h; int i, pad; FILE *fdest = NULL; int adjustR, adjustG, adjustB; if (image->comps[0].prec < 8) { fprintf(stderr, "Unsupported number of components: %d\n", image->comps[0].prec); return 1; } if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx && image->comps[1].dx == image->comps[2].dx && image->comps[0].dy == image->comps[1].dy && image->comps[1].dy == image->comps[2].dy && image->comps[0].prec == image->comps[1].prec && image->comps[1].prec == image->comps[2].prec) { /* -->> -->> -->> -->> 24 bits color <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (3 * h * w + 3 * h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); } else adjustR = 0; if (image->comps[1].prec > 8) { adjustG = (int)image->comps[1].prec - 8; printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec); } else adjustG = 0; if (image->comps[2].prec > 8) { adjustB = (int)image->comps[2].prec - 8; printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec); } else adjustB = 0; for (i = 0; i < w * h; i++) { OPJ_UINT8 rc, gc, bc; int r, g, b; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; rc = (OPJ_UINT8)r; g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); g = ((g >> adjustG)+((g >> (adjustG-1))%2)); if(g > 255) g = 255; else if(g < 0) g = 0; gc = (OPJ_UINT8)g; b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); b = ((b >> adjustB)+((b >> (adjustB-1))%2)); if(b > 255) b = 255; else if(b < 0) b = 0; bc = (OPJ_UINT8)b; fprintf(fdest, "%c%c%c", bc, gc, rc); if ((i + 1) % w == 0) { for (pad = ((3 * w) % 4) ? (4 - (3 * w) % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } else { /* Gray-scale */ /* -->> -->> -->> -->> 8 bits non code (Gray scale) <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + 54 + 1024 + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, ((54 + 1024) >> 16) & 0xff, ((54 + 1024) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); }else adjustR = 0; for (i = 0; i < 256; i++) { fprintf(fdest, "%c%c%c%c", i, i, i, 0); } for (i = 0; i < w * h; i++) { int r; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; fprintf(fdest, "%c", (OPJ_UINT8)r); if ((i + 1) % w == 0) { for ((pad = w % 4) ? (4 - w % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } return 0; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5009_1
crossvul-cpp_data_bad_3190_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3190_1
crossvul-cpp_data_bad_486_1
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Bitmap decompression routines Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 1999-2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* three separate function for speed when decompressing the bitmaps when modifying one function make the change in the others jay.sorg@gmail.com */ /* indent is confused by this file */ /* *INDENT-OFF* */ #include "rdesktop.h" #define CVAL(p) (*(p++)) #ifdef NEED_ALIGN #ifdef L_ENDIAN #define CVAL2(p, v) { v = (*(p++)); v |= (*(p++)) << 8; } #else #define CVAL2(p, v) { v = (*(p++)) << 8; v |= (*(p++)); } #endif /* L_ENDIAN */ #else #define CVAL2(p, v) { v = (*((uint16*)p)); p += 2; } #endif /* NEED_ALIGN */ #define UNROLL8(exp) { exp exp exp exp exp exp exp exp } #define REPEAT(statement) \ { \ while((count & ~0x7) && ((x+8) < width)) \ UNROLL8( statement; count--; x++; ); \ \ while((count > 0) && (x < width)) \ { \ statement; \ count--; \ x++; \ } \ } #define MASK_UPDATE() \ { \ mixmask <<= 1; \ if (mixmask == 0) \ { \ mask = fom_mask ? fom_mask : CVAL(input); \ mixmask = 1; \ } \ } /* 1 byte bitmap decompress */ static RD_BOOL bitmap_decompress1(uint8 * output, int width, int height, uint8 * input, int size) { uint8 *end = input + size; uint8 *prevline = NULL, *line = NULL; int opcode, count, offset, isfillormix, x = width; int lastopcode = -1, insertmix = False, bicolour = False; uint8 code; uint8 colour1 = 0, colour2 = 0; uint8 mixmask, mask = 0; uint8 mix = 0xff; int fom_mask = 0; while (input < end) { fom_mask = 0; code = CVAL(input); opcode = code >> 4; /* Handle different opcode forms */ switch (opcode) { case 0xc: case 0xd: case 0xe: opcode -= 6; count = code & 0xf; offset = 16; break; case 0xf: opcode = code & 0xf; if (opcode < 9) { count = CVAL(input); count |= CVAL(input) << 8; } else { count = (opcode < 0xb) ? 8 : 1; } offset = 0; break; default: opcode >>= 1; count = code & 0x1f; offset = 32; break; } /* Handle strange cases for counts */ if (offset != 0) { isfillormix = ((opcode == 2) || (opcode == 7)); if (count == 0) { if (isfillormix) count = CVAL(input) + 1; else count = CVAL(input) + offset; } else if (isfillormix) { count <<= 3; } } /* Read preliminary data */ switch (opcode) { case 0: /* Fill */ if ((lastopcode == opcode) && !((x == width) && (prevline == NULL))) insertmix = True; break; case 8: /* Bicolour */ colour1 = CVAL(input); colour2 = CVAL(input); break; case 3: /* Colour */ colour2 = CVAL(input); break; case 6: /* SetMix/Mix */ case 7: /* SetMix/FillOrMix */ mix = CVAL(input); opcode -= 5; break; case 9: /* FillOrMix_1 */ mask = 0x03; opcode = 0x02; fom_mask = 3; break; case 0x0a: /* FillOrMix_2 */ mask = 0x05; opcode = 0x02; fom_mask = 5; break; } lastopcode = opcode; mixmask = 0; /* Output body */ while (count > 0) { if (x >= width) { if (height <= 0) return False; x = 0; height--; prevline = line; line = output + height * width; } switch (opcode) { case 0: /* Fill */ if (insertmix) { if (prevline == NULL) line[x] = mix; else line[x] = prevline[x] ^ mix; insertmix = False; count--; x++; } if (prevline == NULL) { REPEAT(line[x] = 0) } else { REPEAT(line[x] = prevline[x]) } break; case 1: /* Mix */ if (prevline == NULL) { REPEAT(line[x] = mix) } else { REPEAT(line[x] = prevline[x] ^ mix) } break; case 2: /* Fill or Mix */ if (prevline == NULL) { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = mix; else line[x] = 0; ) } else { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = prevline[x] ^ mix; else line[x] = prevline[x]; ) } break; case 3: /* Colour */ REPEAT(line[x] = colour2) break; case 4: /* Copy */ REPEAT(line[x] = CVAL(input)) break; case 8: /* Bicolour */ REPEAT ( if (bicolour) { line[x] = colour2; bicolour = False; } else { line[x] = colour1; bicolour = True; count++; } ) break; case 0xd: /* White */ REPEAT(line[x] = 0xff) break; case 0xe: /* Black */ REPEAT(line[x] = 0) break; default: logger(Core, Warning, "bitmap_decompress(), unhandled bitmap opcode 0x%x", opcode); return False; } } } return True; } /* 2 byte bitmap decompress */ static RD_BOOL bitmap_decompress2(uint8 * output, int width, int height, uint8 * input, int size) { uint8 *end = input + size; uint16 *prevline = NULL, *line = NULL; int opcode, count, offset, isfillormix, x = width; int lastopcode = -1, insertmix = False, bicolour = False; uint8 code; uint16 colour1 = 0, colour2 = 0; uint8 mixmask, mask = 0; uint16 mix = 0xffff; int fom_mask = 0; while (input < end) { fom_mask = 0; code = CVAL(input); opcode = code >> 4; /* Handle different opcode forms */ switch (opcode) { case 0xc: case 0xd: case 0xe: opcode -= 6; count = code & 0xf; offset = 16; break; case 0xf: opcode = code & 0xf; if (opcode < 9) { count = CVAL(input); count |= CVAL(input) << 8; } else { count = (opcode < 0xb) ? 8 : 1; } offset = 0; break; default: opcode >>= 1; count = code & 0x1f; offset = 32; break; } /* Handle strange cases for counts */ if (offset != 0) { isfillormix = ((opcode == 2) || (opcode == 7)); if (count == 0) { if (isfillormix) count = CVAL(input) + 1; else count = CVAL(input) + offset; } else if (isfillormix) { count <<= 3; } } /* Read preliminary data */ switch (opcode) { case 0: /* Fill */ if ((lastopcode == opcode) && !((x == width) && (prevline == NULL))) insertmix = True; break; case 8: /* Bicolour */ CVAL2(input, colour1); CVAL2(input, colour2); break; case 3: /* Colour */ CVAL2(input, colour2); break; case 6: /* SetMix/Mix */ case 7: /* SetMix/FillOrMix */ CVAL2(input, mix); opcode -= 5; break; case 9: /* FillOrMix_1 */ mask = 0x03; opcode = 0x02; fom_mask = 3; break; case 0x0a: /* FillOrMix_2 */ mask = 0x05; opcode = 0x02; fom_mask = 5; break; } lastopcode = opcode; mixmask = 0; /* Output body */ while (count > 0) { if (x >= width) { if (height <= 0) return False; x = 0; height--; prevline = line; line = ((uint16 *) output) + height * width; } switch (opcode) { case 0: /* Fill */ if (insertmix) { if (prevline == NULL) line[x] = mix; else line[x] = prevline[x] ^ mix; insertmix = False; count--; x++; } if (prevline == NULL) { REPEAT(line[x] = 0) } else { REPEAT(line[x] = prevline[x]) } break; case 1: /* Mix */ if (prevline == NULL) { REPEAT(line[x] = mix) } else { REPEAT(line[x] = prevline[x] ^ mix) } break; case 2: /* Fill or Mix */ if (prevline == NULL) { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = mix; else line[x] = 0; ) } else { REPEAT ( MASK_UPDATE(); if (mask & mixmask) line[x] = prevline[x] ^ mix; else line[x] = prevline[x]; ) } break; case 3: /* Colour */ REPEAT(line[x] = colour2) break; case 4: /* Copy */ REPEAT(CVAL2(input, line[x])) break; case 8: /* Bicolour */ REPEAT ( if (bicolour) { line[x] = colour2; bicolour = False; } else { line[x] = colour1; bicolour = True; count++; } ) break; case 0xd: /* White */ REPEAT(line[x] = 0xffff) break; case 0xe: /* Black */ REPEAT(line[x] = 0) break; default: logger(Core, Warning, "bitmap_decompress2(), unhandled bitmap opcode 0x%x", opcode); return False; } } } return True; } /* 3 byte bitmap decompress */ static RD_BOOL bitmap_decompress3(uint8 * output, int width, int height, uint8 * input, int size) { uint8 *end = input + size; uint8 *prevline = NULL, *line = NULL; int opcode, count, offset, isfillormix, x = width; int lastopcode = -1, insertmix = False, bicolour = False; uint8 code; uint8 colour1[3] = {0, 0, 0}, colour2[3] = {0, 0, 0}; uint8 mixmask, mask = 0; uint8 mix[3] = {0xff, 0xff, 0xff}; int fom_mask = 0; while (input < end) { fom_mask = 0; code = CVAL(input); opcode = code >> 4; /* Handle different opcode forms */ switch (opcode) { case 0xc: case 0xd: case 0xe: opcode -= 6; count = code & 0xf; offset = 16; break; case 0xf: opcode = code & 0xf; if (opcode < 9) { count = CVAL(input); count |= CVAL(input) << 8; } else { count = (opcode < 0xb) ? 8 : 1; } offset = 0; break; default: opcode >>= 1; count = code & 0x1f; offset = 32; break; } /* Handle strange cases for counts */ if (offset != 0) { isfillormix = ((opcode == 2) || (opcode == 7)); if (count == 0) { if (isfillormix) count = CVAL(input) + 1; else count = CVAL(input) + offset; } else if (isfillormix) { count <<= 3; } } /* Read preliminary data */ switch (opcode) { case 0: /* Fill */ if ((lastopcode == opcode) && !((x == width) && (prevline == NULL))) insertmix = True; break; case 8: /* Bicolour */ colour1[0] = CVAL(input); colour1[1] = CVAL(input); colour1[2] = CVAL(input); colour2[0] = CVAL(input); colour2[1] = CVAL(input); colour2[2] = CVAL(input); break; case 3: /* Colour */ colour2[0] = CVAL(input); colour2[1] = CVAL(input); colour2[2] = CVAL(input); break; case 6: /* SetMix/Mix */ case 7: /* SetMix/FillOrMix */ mix[0] = CVAL(input); mix[1] = CVAL(input); mix[2] = CVAL(input); opcode -= 5; break; case 9: /* FillOrMix_1 */ mask = 0x03; opcode = 0x02; fom_mask = 3; break; case 0x0a: /* FillOrMix_2 */ mask = 0x05; opcode = 0x02; fom_mask = 5; break; } lastopcode = opcode; mixmask = 0; /* Output body */ while (count > 0) { if (x >= width) { if (height <= 0) return False; x = 0; height--; prevline = line; line = output + height * (width * 3); } switch (opcode) { case 0: /* Fill */ if (insertmix) { if (prevline == NULL) { line[x * 3] = mix[0]; line[x * 3 + 1] = mix[1]; line[x * 3 + 2] = mix[2]; } else { line[x * 3] = prevline[x * 3] ^ mix[0]; line[x * 3 + 1] = prevline[x * 3 + 1] ^ mix[1]; line[x * 3 + 2] = prevline[x * 3 + 2] ^ mix[2]; } insertmix = False; count--; x++; } if (prevline == NULL) { REPEAT ( line[x * 3] = 0; line[x * 3 + 1] = 0; line[x * 3 + 2] = 0; ) } else { REPEAT ( line[x * 3] = prevline[x * 3]; line[x * 3 + 1] = prevline[x * 3 + 1]; line[x * 3 + 2] = prevline[x * 3 + 2]; ) } break; case 1: /* Mix */ if (prevline == NULL) { REPEAT ( line[x * 3] = mix[0]; line[x * 3 + 1] = mix[1]; line[x * 3 + 2] = mix[2]; ) } else { REPEAT ( line[x * 3] = prevline[x * 3] ^ mix[0]; line[x * 3 + 1] = prevline[x * 3 + 1] ^ mix[1]; line[x * 3 + 2] = prevline[x * 3 + 2] ^ mix[2]; ) } break; case 2: /* Fill or Mix */ if (prevline == NULL) { REPEAT ( MASK_UPDATE(); if (mask & mixmask) { line[x * 3] = mix[0]; line[x * 3 + 1] = mix[1]; line[x * 3 + 2] = mix[2]; } else { line[x * 3] = 0; line[x * 3 + 1] = 0; line[x * 3 + 2] = 0; } ) } else { REPEAT ( MASK_UPDATE(); if (mask & mixmask) { line[x * 3] = prevline[x * 3] ^ mix [0]; line[x * 3 + 1] = prevline[x * 3 + 1] ^ mix [1]; line[x * 3 + 2] = prevline[x * 3 + 2] ^ mix [2]; } else { line[x * 3] = prevline[x * 3]; line[x * 3 + 1] = prevline[x * 3 + 1]; line[x * 3 + 2] = prevline[x * 3 + 2]; } ) } break; case 3: /* Colour */ REPEAT ( line[x * 3] = colour2 [0]; line[x * 3 + 1] = colour2 [1]; line[x * 3 + 2] = colour2 [2]; ) break; case 4: /* Copy */ REPEAT ( line[x * 3] = CVAL(input); line[x * 3 + 1] = CVAL(input); line[x * 3 + 2] = CVAL(input); ) break; case 8: /* Bicolour */ REPEAT ( if (bicolour) { line[x * 3] = colour2[0]; line[x * 3 + 1] = colour2[1]; line[x * 3 + 2] = colour2[2]; bicolour = False; } else { line[x * 3] = colour1[0]; line[x * 3 + 1] = colour1[1]; line[x * 3 + 2] = colour1[2]; bicolour = True; count++; } ) break; case 0xd: /* White */ REPEAT ( line[x * 3] = 0xff; line[x * 3 + 1] = 0xff; line[x * 3 + 2] = 0xff; ) break; case 0xe: /* Black */ REPEAT ( line[x * 3] = 0; line[x * 3 + 1] = 0; line[x * 3 + 2] = 0; ) break; default: logger(Core, Warning, "bitmap_decompress3(), unhandled bitmap opcode 0x%x", opcode); return False; } } } return True; } /* decompress a colour plane */ static int process_plane(uint8 * in, int width, int height, uint8 * out, int size) { UNUSED(size); int indexw; int indexh; int code; int collen; int replen; int color; int x; int revcode; uint8 * last_line; uint8 * this_line; uint8 * org_in; uint8 * org_out; org_in = in; org_out = out; last_line = 0; indexh = 0; while (indexh < height) { out = (org_out + width * height * 4) - ((indexh + 1) * width * 4); color = 0; this_line = out; indexw = 0; if (last_line == 0) { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (collen > 0) { color = CVAL(in); *out = color; out += 4; indexw++; collen--; } while (replen > 0) { *out = color; out += 4; indexw++; replen--; } } } else { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (collen > 0) { x = CVAL(in); if (x & 1) { x = x >> 1; x = x + 1; color = -x; } else { x = x >> 1; color = x; } x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; collen--; } while (replen > 0) { x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; replen--; } } } indexh++; last_line = this_line; } return (int) (in - org_in); } /* 4 byte bitmap decompress */ static RD_BOOL bitmap_decompress4(uint8 * output, int width, int height, uint8 * input, int size) { int code; int bytes_pro; int total_pro; code = CVAL(input); if (code != 0x10) { return False; } total_pro = 1; bytes_pro = process_plane(input, width, height, output + 3, size - total_pro); total_pro += bytes_pro; input += bytes_pro; bytes_pro = process_plane(input, width, height, output + 2, size - total_pro); total_pro += bytes_pro; input += bytes_pro; bytes_pro = process_plane(input, width, height, output + 1, size - total_pro); total_pro += bytes_pro; input += bytes_pro; bytes_pro = process_plane(input, width, height, output + 0, size - total_pro); total_pro += bytes_pro; return size == total_pro; } /* main decompress function */ RD_BOOL bitmap_decompress(uint8 * output, int width, int height, uint8 * input, int size, int Bpp) { RD_BOOL rv = False; switch (Bpp) { case 1: rv = bitmap_decompress1(output, width, height, input, size); break; case 2: rv = bitmap_decompress2(output, width, height, input, size); break; case 3: rv = bitmap_decompress3(output, width, height, input, size); break; case 4: rv = bitmap_decompress4(output, width, height, input, size); break; default: logger(Core, Debug, "bitmap_decompress(), unhandled BPP %d", Bpp); break; } return rv; } /* *INDENT-ON* */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_486_1
crossvul-cpp_data_bad_141_0
/* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */ #if 0 http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set #endif #include <string.h> #include <r_types.h> #include <r_util.h> #include <r_lib.h> #include <r_asm.h> #include <r_anal.h> static RDESContext desctx; typedef struct _cpu_const_tag { const char *const key; ut8 type; ut32 value; ut8 size; } CPU_CONST; #define CPU_CONST_NONE 0 #define CPU_CONST_PARAM 1 #define CPU_CONST_REG 2 typedef struct _cpu_model_tag { const char *const model; int pc; char *inherit; struct _cpu_model_tag *inherit_cpu_p; CPU_CONST *consts[10]; } CPU_MODEL; typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu); typedef struct _opcodes_tag_ { const char *const name; int mask; int selector; inst_handler_t handler; int cycles; int size; ut64 type; } OPCODE_DESC; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu); #define CPU_MODEL_DECL(model, pc, consts) \ { \ model, \ pc, \ consts \ } #define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits)))) #define CPU_PC_MASK(cpu) MASK((cpu)->pc) #define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0)) #define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu) #define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T } #define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK } #define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu) #define INST_INVALID { *fail = 1; return; } #define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } } #define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__) #define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s)) // Following IO definitions are valid for: // ATmega8 // ATmega88 CPU_CONST cpu_reg_common[] = { { "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) }, { "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) }, { "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) }, { "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_common[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = { { "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_memsize_xmega128a4u[] = { { "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) }, { "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) }, { "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_5_bits[] = { { "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_CONST cpu_pagesize_7_bits[] = { { "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) }, { NULL, 0, 0, 0 }, }; CPU_MODEL cpu_models[] = { { .model = "ATmega640", .pc = 15, .consts = { cpu_reg_common, cpu_memsize_m640_m1280m_m1281_m2560_m2561, cpu_pagesize_7_bits, NULL }, }, { .model = "ATxmega128a4u", .pc = 17, .consts = { cpu_reg_common, cpu_memsize_xmega128a4u, cpu_pagesize_7_bits, NULL } }, { .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" }, { .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" }, { .model = "ATmega88", .pc = 8, .inherit = "ATmega8" }, // CPU_MODEL_DECL ("ATmega168", 13, 512, 512), // last model is the default AVR - ATmega8 forever! { .model = "ATmega8", .pc = 13, .consts = { cpu_reg_common, cpu_memsize_common, cpu_pagesize_5_bits, NULL } }, }; static CPU_MODEL *get_cpu_model(char *model); static CPU_MODEL *__get_cpu_model_recursive(char *model) { CPU_MODEL *cpu = NULL; for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) { if (!strcasecmp (model, cpu->model)) { break; } } // fix inheritance tree if (cpu->inherit && !cpu->inherit_cpu_p) { cpu->inherit_cpu_p = get_cpu_model (cpu->inherit); if (!cpu->inherit_cpu_p) { eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit); } } return cpu; } static CPU_MODEL *get_cpu_model(char *model) { static CPU_MODEL *cpu = NULL; // cached value? if (cpu && !strcasecmp (model, cpu->model)) return cpu; // do the real search cpu = __get_cpu_model_recursive (model); return cpu; } static ut32 const_get_value(CPU_CONST *c) { return c ? MASK (c->size * 8) & c->value : 0; } static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem->key; citem++) { if (!strcmp (c, citem->key) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_name (cpu->inherit_cpu_p, type, c); eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c); return NULL; } static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) { char *t = r_anal_esil_pop (esil); if (!t || !r_anal_esil_get_parm (esil, t, v)) { free (t); return false; } free (t); return true; } static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) { CPU_CONST **clist, *citem; for (clist = cpu->consts; *clist; clist++) { for (citem = *clist; citem && citem->key; citem++) { if (citem->value == (MASK (citem->size * 8) & v) && (type == CPU_CONST_NONE || type == citem->type)) { return citem; } } } if (cpu->inherit_cpu_p) return const_by_value (cpu->inherit_cpu_p, type, v); return NULL; } static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) { RStrBuf *r = r_strbuf_new (""); CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port); if (c != NULL) { r_strbuf_set (r, c->key); if (write) { r_strbuf_append (r, ",="); } } else { r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : ""); } return r; } static void __generic_bitop_flags(RAnalOp *op) { ESIL_A ("0,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S } static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) { if (ireg) { // preincrement index register if (prepostdec < 0) { ESIL_A ("1,%c,-,%c,=,", ireg, ireg); } // set register index address ESIL_A ("%c,", ireg); // add offset if (offset != 0) { ESIL_A ("%d,+,", offset); } } else { ESIL_A ("%d,", offset); } if (use_ramp) { ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd'); } // set SRAM base address ESIL_A ("_%s,+,", mem); // read/write from SRAM ESIL_A ("%s[1],", st ? "=" : ""); // postincrement index register if (ireg && prepostdec > 0) { ESIL_A ("1,%c,+,%c,=,", ireg, ireg); } } static void __generic_pop(RAnalOp *op, int sz) { if (sz > 1) { ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1) ESIL_A ("[%d],", sz); // read value ESIL_A ("%d,sp,+=,", sz); // sp += item_size } else { ESIL_A ("1,sp,+=," // increment stack pointer "sp,_ram,+,[1],"); // load SRAM[sp] } } static void __generic_push(RAnalOp *op, int sz) { ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp) if (sz > 1) { ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz' } ESIL_A ("=[%d],", sz); // store value in stack ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer } static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) { __generic_add_update_flags(op, 'r', d, 'r', r); } static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) { RStrBuf *d_strbuf, *rk_strbuf; char *d, *rk; d_strbuf = r_strbuf_new (NULL); rk_strbuf = r_strbuf_new (NULL); r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d); r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk); d = r_strbuf_get(d_strbuf); rk = r_strbuf_get(rk_strbuf); ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H "%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&," "%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&," "|,|,hf,=,", d, rk, rk, d); ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V "" "0,RPICK,0x80,&,!," "&," "%s,0x80,&,!," "%s,0x80,&,!,!," "&," "" "0,RPICK,0x80,&,!,!," "&," "|,vf,=,", d, rk, d, rk); ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N if (carry) ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z else ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C "%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&," "%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&," "|,|,cf,=,", d, rk, rk, d); ESIL_A ("vf,nf,^,sf,=,"); // S r_strbuf_free (d_strbuf); r_strbuf_free (rk_strbuf); } static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) { __generic_sub_update_flags(op, 'r', d, 'r', r, carry); } static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) { __generic_sub_update_flags(op, 'r', d, 'k', k, carry); } INST_HANDLER (adc) { // ADC Rd, Rr // ROL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (add) { // ADD Rd, Rr // LSL Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr __generic_add_update_flags_rr(op, d, r); // FLAGS ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr // FLAGS: ESIL_A ("r%d,0x80,&,!," // V "0,RPICK,0x8000,&,!,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!,!," // C "0,RPICK,0x8000,&,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (and) { // AND Rd, Rr // TST Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (andi) { // ANDI Rd, K // CBR Rd, K (= ANDI Rd, 1-K) if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f); op->val = k; ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (asr) { // ASR Rd if (len < 2) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7 ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (bclr) { // BCLR s // CLC // CLH // CLI // CLN // CLR // CLS // CLT // CLV // CLZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s); } INST_HANDLER (bld) { // BLD Rd, b if (len < 2) { return; } int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf); int b = buf[0] & 0x7; ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0 ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b } INST_HANDLER (brbx) { // BRBC s, k // BRBS s, k // BRBC/S 0: BRCC BRCS // BRSH BRLO // BRBC/S 1: BREQ BRNE // BRBC/S 2: BRPL BRMI // BRBC/S 3: BRVC BRVS // BRBC/S 4: BRGE BRLT // BRBC/S 5: BRHC BRHS // BRBC/S 6: BRTC BRTS // BRBC/S 7: BRID BRIE int s = buf[0] & 0x7; op->jump = op->addr + ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2)) | (buf[1] & 0x2 ? ~((int) 0x7f) : 0)) + 2; op->fail = op->addr + op->size; op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s) ESIL_A (buf[1] & 0x4 ? "!," // BRBC => branch if cleared : "!,!,"); // BRBS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (break) { // BREAK ESIL_A ("BREAK"); } INST_HANDLER (bset) { // BSET s // SEC // SEH // SEI // SEN // SER // SES // SET // SEV // SEZ int s = (buf[0] >> 4) & 0x7; ESIL_A ("%d,1,<<,sreg,|=,", s); } INST_HANDLER (bst) { // BST Rd, b if (len < 2) { return; } ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r buf[0] & 0x7); // b } INST_HANDLER (call) { // CALL k if (len < 4) { return; } op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->fail = op->addr + op->size; op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // AT*mega optimizes one cycle } ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (cbi) { // CBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->family = R_ANAL_OP_FAMILY_IO; op->type2 = 1; op->val = a; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (com) { // COM Rd int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd // FLAGS: ESIL_A ("0,cf,=,"); // C __generic_bitop_flags (op); // ...rest... } INST_HANDLER (cp) { // CP Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) } INST_HANDLER (cpc) { // CPC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10); int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) } INST_HANDLER (cpi) { // CPI Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); ESIL_A ("%d,r%d,-,", k, d); // Rd - k __generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry) } INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to true, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (dec) { // DEC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("-1,r%d,+,", d); // --Rd // FLAGS: ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (des) { // DES k if (desctx.round < 16) { //DES op->type = R_ANAL_OP_TYPE_CRYPTO; op->cycles = 1; //redo this r_strbuf_setf (&op->esil, "%d,des", desctx.round); } } INST_HANDLER (eijmp) { // EIJMP ut64 z, eind; // read z and eind for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = ((eind << 16) + z) << 1; // jump ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,"); // cycles op->cycles = 2; } INST_HANDLER (eicall) { // EICALL // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard EIJMP INST_CALL (eijmp); // fix cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4; } INST_HANDLER (elpm) { // ELPM // ELPM Rd // ELPM Rd, Z+ int d = ((buf[1] & 0xfe) == 0x90) ? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd : 0; // R0 ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z ESIL_A ("r%d,=,", d); // Rd = [1] if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) { ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z) } } INST_HANDLER (eor) { // EOR Rd, Rr // CLR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr __generic_bitop_flags (op); // up flags ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (fmul) { // FMUL Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmuls) { // FMULS Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (fmulsu) { // FMULSU Rd, Rr int d = ((buf[0] >> 4) & 0x7) + 16; int r = (buf[0] & 0x7) + 16; ESIL_A ("1,"); ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("r%d", r); // unsigned Rr ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1 ESIL_A ("0xffff,&,"); // prevent overflow ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (ijmp) { // IJMP k ut64 z; // read z for calculating jump address on runtime r_anal_esil_reg_read (anal->esil, "z", &z, NULL); // real target address may change during execution, so this value will // be changing all the time op->jump = z << 1; op->cycles = 2; ESIL_A ("1,z,<<,pc,=,"); // jump! } INST_HANDLER (icall) { // ICALL k // push pc in stack ESIL_A ("pc,"); // esil is already pointing to // next instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack // do a standard IJMP INST_CALL (ijmp); // fix cycles if (!STR_BEGINS (cpu->model, "ATxmega")) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (in) { // IN Rd, A int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_src = __generic_io_dest (a, 0, cpu); op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r); r_strbuf_free (io_src); } INST_HANDLER (inc) { // INC Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("1,r%d,+,", d); // ++Rd // FLAGS: ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (jmp) { // JMP k op->jump = (buf[2] << 1) | (buf[3] << 9) | (buf[1] & 0x01) << 23 | (buf[0] & 0x01) << 17 | (buf[0] & 0xf0) << 14; op->cycles = 3; ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! } INST_HANDLER (lac) { // LAC Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (las) { // LAS Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,|,", d); // 0: (Z) | Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (lat) { // LAT Z, Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); // read memory from RAMPZ:Z __generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z) ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd ESIL_A ("DUP,r%d,=,", d); // Rd = [0] __generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM } INST_HANDLER (ld) { // LD Rd, X // LD Rd, X+ // LD Rd, -X // read memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post incremented : 0, // no increment 0, // offset always 0 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[0] & 0x3) == 0 ? 2 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z // LD Rd, Y+ LD Rd, Z+ // LD Rd, -Y LD Rd, -Z // LD Rd, Y+q LD Rd, Z+q // calculate offset (this value only has sense in some opcodes, // but we are optimistic and we calculate it always) int offset = (buf[1] & 0x20) | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7); // read memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? offset : 0, // offset or not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // cycles op->cycles = (buf[1] & 0x10) == 0 ? (!offset ? 1 : 3) // LDD : (buf[0] & 0x3) == 0 ? 1 // LD Rd, X : (buf[0] & 0x3) == 1 ? 2 // LD Rd, X+ : 3; // LD Rd, -X if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // AT*mega optimizes 1 cycle! op->cycles--; } } INST_HANDLER (ldi) { // LDI Rd, K int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4); int d = ((buf[0] >> 4) & 0xf) + 16; op->val = k; ESIL_A ("0x%x,r%d,=,", k, d); } INST_HANDLER (lds) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; // load value from RAMPD:k __generic_ld_st (op, "ram", 0, 1, 0, k, 0); ESIL_A ("r%d,=,", d); } INST_HANDLER (sts) { // STS k, Rr int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; ESIL_A ("r%d,", r); __generic_ld_st (op, "ram", 0, 1, 0, k, 1); op->cycles = 2; } #if 0 INST_HANDLER (lds16) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x30) | ((buf[1] << 4) & 0x40) | (~(buf[1] << 4) & 0x80); op->ptr = k; // load value from @k __generic_ld_st (op, "ram", 0, 0, 0, k, 0); ESIL_A ("r%d,=,", d); } #endif INST_HANDLER (lpm) { // LPM // LPM Rd, Z // LPM Rd, Z+ ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]); // read program memory __generic_ld_st ( op, "prog", 'z', // index register Y/Z 1, // use RAMP* registers (ins & 0xfe0f) == 0x9005 ? 1 // post incremented : 0, // no increment 0, // not offset 0); // load operation (!st) // load register ESIL_A ("r%d,=,", (ins == 0x95c8) ? 0 // LPM (r0) : ((buf[0] >> 4) & 0xf) // LPM Rd | ((buf[1] & 0x1) << 4)); } INST_HANDLER (lsr) { // LSR Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1) ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0 ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("nf,vf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = R } INST_HANDLER (mov) { // MOV Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,=,", r, d); } INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr int d = (buf[0] & 0xf0) >> 3; int r = (buf[0] & 0x0f) << 1; ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1); } INST_HANDLER (mul) { // MUL Rd, Rr int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f); int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f); ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1 ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (muls) { // MULS Rd, Rr int d = (buf[0] >> 4 & 0x0f) + 16; int r = (buf[0] & 0x0f) + 16; ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (mulsu) { // MULSU Rd, Rr int d = (buf[0] >> 4 & 0x07) + 16; int r = (buf[0] & 0x07) + 16; ESIL_A ("r%d,", r); // unsigned Rr ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd ESIL_A ("*,"); // 0: (Rd*Rr) ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0) ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0) ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15 ESIL_A ("DUP,!,zf,=,"); // Z = !R } INST_HANDLER (neg) { // NEG Rd int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd) ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N ESIL_A ("DUP,!,zf,=,"); // Z ESIL_A ("DUP,!,!,cf,=,"); // C ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (nop) { // NOP ESIL_A (",,"); } INST_HANDLER (or) { // OR Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (ori) { // ORI Rd, K // SBR Rd, K int d = ((buf[0] >> 4) & 0xf) + 16; int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4); op->val = k; ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k) ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("0,vf,=,"); // V ESIL_A ("nf,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (out) { // OUT A, Rr int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4); int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3); RStrBuf *io_dst = __generic_io_dest (a, 1, cpu); op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst)); r_strbuf_free (io_dst); } INST_HANDLER (pop) { // POP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); __generic_pop (op, 1); ESIL_A ("r%d,=,", d); // store in Rd } INST_HANDLER (push) { // PUSH Rr int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("r%d,", r); // load Rr __generic_push (op, 1); // push it into stack // cycles op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 1 // AT*mega optimizes one cycle : 2; } INST_HANDLER (rcall) { // RCALL k // target address op->jump = (op->addr + (((((buf[1] & 0xf) << 8) | buf[0]) << 1) | (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0))) + 2) & CPU_PC_MASK (cpu); op->fail = op->addr + op->size; // esil ESIL_A ("pc,"); // esil already points to next // instruction (@ret) __generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump! // cycles if (!strncasecmp (cpu->model, "ATtiny", 6)) { op->cycles = 4; // ATtiny is always slow } else { // PC size decides required runtime! op->cycles = cpu->pc <= 16 ? 3 : 4; if (!STR_BEGINS (cpu->model, "ATxmega")) { op->cycles--; // ATxmega optimizes one cycle } } } INST_HANDLER (ret) { // RET op->eob = true; // esil __generic_pop (op, CPU_PC_SIZE (cpu)); ESIL_A ("pc,=,"); // jump! // cycles if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit op->cycles++; // (i.e. a 22-bit bus), add one extra cycle } } INST_HANDLER (reti) { // RETI //XXX: There are not privileged instructions in ATMEL/AVR op->family = R_ANAL_OP_FAMILY_PRIV; // first perform a standard 'ret' INST_CALL (ret); // RETI: The I-bit is cleared by hardware after an interrupt // has occurred, and is set by the RETI instruction to enable // subsequent interrupts ESIL_A ("1,if,=,"); } INST_HANDLER (rjmp) { // RJMP k op->jump = (op->addr #ifdef _MSC_VER #pragma message ("anal_avr.c: WARNING: Probably broken on windows") + ((((( buf[1] & 0xf) << 9) | (buf[0] << 1))) | (buf[1] & 0x8 ? ~(0x1fff) : 0)) #else + ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1))) | (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0)) #endif + 2) & CPU_PC_MASK (cpu); ESIL_A ("%"PFMT64d",pc,=,", op->jump); } INST_HANDLER (ror) { // ROR Rd int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10); ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7) ESIL_A ("r%d,1,&,cf,=,", d); // C ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N ESIL_A ("nf,cf,^,vf,=,"); // V ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d,=,", d); // Rd = result } INST_HANDLER (sbc) { // SBC Rd, Rr int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C) __generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbci) { // SBCI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sub) { // SUB Rd, Rr int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4); int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3); ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k) __generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (subi) { // SUBI Rd, k int d = ((buf[0] >> 4) & 0xf) + 16; int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf); op->val = k; ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k) __generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry) ESIL_A ("r%d,=,", d); // Rd = Result } INST_HANDLER (sbi) { // SBI A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RStrBuf *io_port; op->type2 = 1; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port); r_strbuf_free (io_port); // write result to port a io_port = __generic_io_dest (a, 1, cpu); ESIL_A ("%s,", r_strbuf_get (io_port)); r_strbuf_free (io_port); } INST_HANDLER (sbix) { // SBIC A, b // SBIS A, b int a = (buf[0] >> 3) & 0x1f; int b = buf[0] & 0x07; RAnalOp next_op; RStrBuf *io_port; op->type2 = 0; op->val = a; op->family = R_ANAL_OP_FAMILY_IO; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. // read port a and clear bit b io_port = __generic_io_dest (a, 0, cpu); ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBIC => branch if 0 : "!,!,"); // SBIS => branch if 1 ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp r_strbuf_free (io_port); } INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K int d = ((buf[0] & 0x30) >> 3) + 24; int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30); op->val = k; ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr) ESIL_A ("r%d,0x80,&,!,!," // V "0,RPICK,0x8000,&,!," "&,vf,=,", d + 1); ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N ESIL_A ("0,RPICK,!,zf,=,"); // Z ESIL_A ("r%d,0x80,&,!," // C "0,RPICK,0x8000,&,!,!," "&,cf,=,", d + 1); ESIL_A ("vf,nf,^,sf,=,"); // S ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result } INST_HANDLER (sbrx) { // SBRC Rr, b // SBRS Rr, b int b = buf[0] & 0x7; int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4); RAnalOp next_op; // calculate next instruction size (call recursively avr_op_analyze) // and free next_op's esil string (we dont need it now) avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; // cycles op->cycles = 1; // XXX: This is a bug, because depends on eval state, // so it cannot be really be known until this // instruction is executed by the ESIL interpreter!!! // In case of evaluating to false, this instruction // needs 2/3 cycles, elsewhere it needs only 1 cycle. ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b) ESIL_A ((buf[1] & 0xe) == 0xc ? "!," // SBRC => branch if cleared : "!,!,"); // SBRS => branch if set ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp } INST_HANDLER (sleep) { // SLEEP ESIL_A ("BREAK"); } INST_HANDLER (spm) { // SPM Z+ ut64 spmcsr; // read SPM Control Register (SPMCR) r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL); // clear SPMCSR ESIL_A ("0x7c,spmcsr,&=,"); // decide action depending on the old value of SPMCSR switch (spmcsr & 0x7f) { case 0x03: // PAGE ERASE // invoke SPM_CLEAR_PAGE (erases target page writing // the 0xff value ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_ERASE,"); // do magic break; case 0x01: // FILL TEMPORARY BUFFER ESIL_A ("r1,r0,"); // push data ESIL_A ("z,"); // push target address ESIL_A ("SPM_PAGE_FILL,"); // do magic break; case 0x05: // WRITE PAGE ESIL_A ("16,rampz,<<,z,+,"); // push target address ESIL_A ("SPM_PAGE_WRITE,"); // do magic break; default: eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n", (unsigned int) spmcsr); } op->cycles = 1; // This is truly false. Datasheets do not publish how // many cycles this instruction uses in all its // operation modes and I am pretty sure that this value // can vary substantially from one MCU type to another. // So... one cycle is fine. } INST_HANDLER (st) { // ST X, Rr // ST X+, Rr // ST -X, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", 'x', // use index register X 0, // no use RAMP* registers (buf[0] & 0xf) == 0xe ? -1 // pre decremented : (buf[0] & 0xf) == 0xd ? 1 // post increment : 0, // no increment 0, // offset always 0 1); // store operation (st) // // cycles // op->cycles = buf[0] & 0x3 == 0 // ? 2 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (std) { // ST Y, Rr ST Z, Rr // ST Y+, Rr ST Z+, Rr // ST -Y, Rr ST -Z, Rr // ST Y+q, Rr ST Z+q, Rr // load register ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf)); // write in memory __generic_ld_st ( op, "ram", buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z 0, // no use RAMP* registers !(buf[1] & 0x10) ? 0 // no increment : buf[0] & 0x1 ? 1 // post incremented : -1, // pre decremented !(buf[1] & 0x10) ? (buf[1] & 0x20) // offset | ((buf[1] & 0xc) << 1) | (buf[0] & 0x7) : 0, // no offset 1); // load operation (!st) // // cycles // op->cycles = // buf[1] & 0x1 == 0 // ? !(offset ? 1 : 3) // LDD // : buf[0] & 0x3 == 0 // ? 1 // LD Rd, X // : buf[0] & 0x3 == 1 // ? 2 // LD Rd, X+ // : 3; // LD Rd, -X // if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) { // // AT*mega optimizes 1 cycle! // op->cycles--; // } } INST_HANDLER (swap) { // SWAP Rd int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf); ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf ESIL_A ("|,", d); // S[0] | S[1] ESIL_A ("r%d,=,", d); // Rd = result } OPCODE_DESC opcodes[] = { // op mask select cycles size type INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ... INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+ INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+ INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+ INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+ INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A //INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr INST_LAST }; static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; if (len < 2) { return NULL; } ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; // initialize op struct memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); // process opcode for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; // copy default cycles/size values op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; // op->fail = addr + op->size; op->addr = addr; // start void esil expression r_strbuf_setf (&op->esil, ""); // handle opcode opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { // eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr); opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); // remove trailing coma (COMETE LA COMA) t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } // ignore reserved opcodes (if they have not been caught by the previous loop) if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: // An unknown or invalid option has appeared. // -- Throw pokeball! op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; // launch esil trap (for communicating upper layers about this weird // and stinky situation r_strbuf_set (&op->esil, "1,$"); return NULL; } static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) { CPU_MODEL *cpu; ut64 offset; // init op if (!op) { return 2; } // select cpu info cpu = get_cpu_model (anal->cpu); // set memory layout registers if (anal->esil) { offset = 0; r_anal_esil_reg_write (anal->esil, "_prog", offset); offset += (1 << cpu->pc); r_anal_esil_reg_write (anal->esil, "_io", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start")); r_anal_esil_reg_write (anal->esil, "_sram", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size")); r_anal_esil_reg_write (anal->esil, "_eeprom", offset); offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size")); r_anal_esil_reg_write (anal->esil, "_page", offset); } // process opcode avr_op_analyze (anal, op, addr, buf, len, cpu); return op->size; } static int avr_custom_des (RAnalEsil *esil) { ut64 key, encrypt, text,des_round; ut32 key_lo, key_hi, buf_lo, buf_hi; if (!esil || !esil->anal || !esil->anal->reg) { return false; } if (!__esil_pop_argument (esil, &des_round)) { return false; } r_anal_esil_reg_read (esil, "hf", &encrypt, NULL); r_anal_esil_reg_read (esil, "deskey", &key, NULL); r_anal_esil_reg_read (esil, "text", &text, NULL); key_lo = key & UT32_MAX; key_hi = key >> 32; buf_lo = text & UT32_MAX; buf_hi = text >> 32; if (des_round != desctx.round) { desctx.round = des_round; } if (!desctx.round) { int i; //generating all round keys r_des_permute_key (&key_lo, &key_hi); for (i = 0; i < 16; i++) { r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi); } r_des_permute_block0 (&buf_lo, &buf_hi); } if (encrypt) { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]); } else { r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]); } if (desctx.round == 15) { r_des_permute_block1 (&buf_hi, &buf_lo); desctx.round = 0; } else { desctx.round++; } r_anal_esil_reg_write (esil, "text", text); return true; } // ESIL operation SPM_PAGE_ERASE static int avr_custom_spm_page_erase(RAnalEsil *esil) { CPU_MODEL *cpu; ut8 c; ut64 addr, page_size_bits, i; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument(esil, &addr)) { return false; } // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align base address to page_size_bits addr &= ~(MASK (page_size_bits)); // perform erase //eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); c = 0xff; for (i = 0; i < (1ULL << page_size_bits); i++) { r_anal_esil_mem_write ( esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1); } return true; } // ESIL operation SPM_PAGE_FILL static int avr_custom_spm_page_fill(RAnalEsil *esil) { CPU_MODEL *cpu; ut64 addr, page_size_bits, i; ut8 r0, r1; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address, r0, r1 if (!__esil_pop_argument(esil, &addr)) { return false; } if (!__esil_pop_argument (esil, &i)) { return false; } r0 = i; if (!__esil_pop_argument (esil, &i)) { return false; } r1 = i; // get details about current MCU and fix input address cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); // align and crop base address addr &= (MASK (page_size_bits) ^ 1); // perform write to temporary page //eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr); r_anal_esil_mem_write (esil, addr++, &r0, 1); r_anal_esil_mem_write (esil, addr++, &r1, 1); return true; } // ESIL operation SPM_PAGE_WRITE static int avr_custom_spm_page_write(RAnalEsil *esil) { CPU_MODEL *cpu; char *t = NULL; ut64 addr, page_size_bits, tmp_page; // sanity check if (!esil || !esil->anal || !esil->anal->reg) { return false; } // get target address if (!__esil_pop_argument (esil, &addr)) { return false; } // get details about current MCU and fix input address and base address // of the internal temporary page cpu = get_cpu_model (esil->anal->cpu); page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size")); r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL); // align base address to page_size_bits addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu)); // perform writing //eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr); if (!(t = malloc (1 << page_size_bits))) { eprintf ("Cannot alloc a buffer for copying the temporary page.\n"); return false; } r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits); r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits); return true; } static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) { CPU_MODEL *cpu; if (!esil || !esil->anal) { return 0; } // select cpu info cpu = get_cpu_model (esil->anal->cpu); // crop registers and force certain values if (!strcmp (name, "pc")) { *val &= CPU_PC_MASK (cpu); } else if (!strcmp (name, "pcl")) { if (cpu->pc < 8) { *val &= MASK (8); } } else if (!strcmp (name, "pch")) { *val = cpu->pc > 8 ? *val & MASK (cpu->pc - 8) : 0; } return 0; } static int esil_avr_init(RAnalEsil *esil) { if (!esil) { return false; } desctx.round = 0; r_anal_esil_set_op (esil, "des", avr_custom_des); r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase); r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill); r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write); esil->cb.hook_reg_write = esil_avr_hook_reg_write; return true; } static int esil_avr_fini(RAnalEsil *esil) { return true; } static int set_reg_profile(RAnal *anal) { const char *p = "=PC pcl\n" "=SP sp\n" // explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html // and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file "=A0 r25\n" "=A1 r24\n" "=A2 r23\n" "=A3 r22\n" "=R0 r24\n" #if 0 PC: 16- or 22-bit program counter SP: 8- or 16-bit stack pointer SREG: 8-bit status register RAMPX, RAMPY, RAMPZ, RAMPD and EIND: #endif // 8bit registers x 32 "gpr r0 .8 0 0\n" "gpr r1 .8 1 0\n" "gpr r2 .8 2 0\n" "gpr r3 .8 3 0\n" "gpr r4 .8 4 0\n" "gpr r5 .8 5 0\n" "gpr r6 .8 6 0\n" "gpr r7 .8 7 0\n" "gpr text .64 0 0\n" "gpr r8 .8 8 0\n" "gpr r9 .8 9 0\n" "gpr r10 .8 10 0\n" "gpr r11 .8 11 0\n" "gpr r12 .8 12 0\n" "gpr r13 .8 13 0\n" "gpr r14 .8 14 0\n" "gpr r15 .8 15 0\n" "gpr deskey .64 8 0\n" "gpr r16 .8 16 0\n" "gpr r17 .8 17 0\n" "gpr r18 .8 18 0\n" "gpr r19 .8 19 0\n" "gpr r20 .8 20 0\n" "gpr r21 .8 21 0\n" "gpr r22 .8 22 0\n" "gpr r23 .8 23 0\n" "gpr r24 .8 24 0\n" "gpr r25 .8 25 0\n" "gpr r26 .8 26 0\n" "gpr r27 .8 27 0\n" "gpr r28 .8 28 0\n" "gpr r29 .8 29 0\n" "gpr r30 .8 30 0\n" "gpr r31 .8 31 0\n" // 16 bit overlapped registers for 16 bit math "gpr r17:r16 .16 16 0\n" "gpr r19:r18 .16 18 0\n" "gpr r21:r20 .16 20 0\n" "gpr r23:r22 .16 22 0\n" "gpr r25:r24 .16 24 0\n" "gpr r27:r26 .16 26 0\n" "gpr r29:r28 .16 28 0\n" "gpr r31:r30 .16 30 0\n" // 16 bit overlapped registers for memory addressing "gpr x .16 26 0\n" "gpr y .16 28 0\n" "gpr z .16 30 0\n" // program counter // NOTE: program counter size in AVR depends on the CPU model. It seems that // the PC may range from 16 bits to 22 bits. "gpr pc .32 32 0\n" "gpr pcl .16 32 0\n" "gpr pch .16 34 0\n" // special purpose registers "gpr sp .16 36 0\n" "gpr spl .8 36 0\n" "gpr sph .8 37 0\n" // status bit register (SREG) "gpr sreg .8 38 0\n" "gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts. "gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero. "gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result. "gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow. "gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison. "gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic. "gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit. "gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled. // 8bit segment registers to be added to X, Y, Z to get 24bit offsets "gpr rampx .8 39 0\n" "gpr rampy .8 40 0\n" "gpr rampz .8 41 0\n" "gpr rampd .8 42 0\n" "gpr eind .8 43 0\n" // memory mapping emulator registers // _prog // the program flash. It has its own address space. // _ram // _io // start of the data addres space. It is the same address of IO, // because IO is the first memory space addressable in the AVR. // _sram // start of the SRAM (this offset depends on IO size, and it is // inside the _ram address space) // _eeprom // this is another address space, outside ram and flash // _page // this is the temporary page used by the SPM instruction. This // memory is not directly addressable and it is used internally by // the CPU when autoflashing. "gpr _prog .32 44 0\n" "gpr _page .32 48 0\n" "gpr _eeprom .32 52 0\n" "gpr _ram .32 56 0\n" "gpr _io .32 56 0\n" "gpr _sram .32 60 0\n" // other important MCU registers // spmcsr/spmcr // Store Program Memory Control and Status Register (SPMCSR) "gpr spmcsr .8 64 0\n" ; return r_reg_set_profile_string (anal->reg, p); } static int archinfo(RAnal *anal, int q) { if (q == R_ANAL_ARCHINFO_ALIGN) return 2; if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE) return 4; if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE) return 2; return 2; // XXX } static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) { RAnalOp *op = NULL; ut8 *ret = NULL; int idx; if (!(op = r_anal_op_new ())) { return NULL; } if (!(ret = malloc (size))) { r_anal_op_free (op); return NULL; } memset (ret, 0xff, size); CPU_MODEL *cpu = get_cpu_model (anal->cpu); for (idx = 0; idx + 1 < size; idx += op->size) { OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu); if (op->size < 1) { break; } if (!opcode_desc) { // invalid instruction continue; } // the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching // (things like memory offsets or jump addresses) if (op->size == 4) { ret[idx + 2] = 0; ret[idx + 3] = 0; } if (op->ptr != UT64_MAX || op->jump != UT64_MAX) { ret[idx] = opcode_desc->mask; ret[idx + 1] = opcode_desc->mask >> 8; } } r_anal_op_free (op); return ret; } RAnalPlugin r_anal_plugin_avr = { .name = "avr", .desc = "AVR code analysis plugin", .license = "LGPL3", .arch = "avr", .esil = true, .archinfo = archinfo, .bits = 8 | 16, // 24 big regs conflicts .op = &avr_op, .set_reg_profile = &set_reg_profile, .esil_init = esil_avr_init, .esil_fini = esil_avr_fini, .anal_mask = anal_mask_avr, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_ANAL, .data = &r_anal_plugin_avr, .version = R2_VERSION }; #endif
./CrossVul/dataset_final_sorted/CWE-125/c/bad_141_0
crossvul-cpp_data_bad_4857_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Directory Read Support Routines. */ /* Suggested pending improvements: * - add a field 'ignore' to the TIFFDirEntry structure, to flag status, * eliminating current use of the IGNORE value, and therefore eliminating * current irrational behaviour on tags with tag id code 0 * - add a field 'field_info' to the TIFFDirEntry structure, and set that with * the pointer to the appropriate TIFFField structure early on in * TIFFReadDirectory, so as to eliminate current possibly repetitive lookup. */ #include "tiffiop.h" #define IGNORE 0 /* tag placeholder used below */ #define FAILED_FII ((uint32) -1) #ifdef HAVE_IEEEFP # define TIFFCvtIEEEFloatToNative(tif, n, fp) # define TIFFCvtIEEEDoubleToNative(tif, n, dp) #else extern void TIFFCvtIEEEFloatToNative(TIFF*, uint32, float*); extern void TIFFCvtIEEEDoubleToNative(TIFF*, uint32, double*); #endif enum TIFFReadDirEntryErr { TIFFReadDirEntryErrOk = 0, TIFFReadDirEntryErrCount = 1, TIFFReadDirEntryErrType = 2, TIFFReadDirEntryErrIo = 3, TIFFReadDirEntryErrRange = 4, TIFFReadDirEntryErrPsdif = 5, TIFFReadDirEntryErrSizesan = 6, TIFFReadDirEntryErrAlloc = 7, }; static enum TIFFReadDirEntryErr TIFFReadDirEntryByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryFloat(TIFF* tif, TIFFDirEntry* direntry, float* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryDouble(TIFF* tif, TIFFDirEntry* direntry, double* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8(TIFF* tif, TIFFDirEntry* direntry, uint64* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryArray(TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize, void** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryByteArray(TIFF* tif, TIFFDirEntry* direntry, uint8** value); static enum TIFFReadDirEntryErr TIFFReadDirEntrySbyteArray(TIFF* tif, TIFFDirEntry* direntry, int8** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryShortArray(TIFF* tif, TIFFDirEntry* direntry, uint16** value); static enum TIFFReadDirEntryErr TIFFReadDirEntrySshortArray(TIFF* tif, TIFFDirEntry* direntry, int16** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryLongArray(TIFF* tif, TIFFDirEntry* direntry, uint32** value); static enum TIFFReadDirEntryErr TIFFReadDirEntrySlongArray(TIFF* tif, TIFFDirEntry* direntry, int32** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value); static enum TIFFReadDirEntryErr TIFFReadDirEntrySlong8Array(TIFF* tif, TIFFDirEntry* direntry, int64** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryFloatArray(TIFF* tif, TIFFDirEntry* direntry, float** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryDoubleArray(TIFF* tif, TIFFDirEntry* direntry, double** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value); static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value); #if 0 static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleDouble(TIFF* tif, TIFFDirEntry* direntry, double* value); #endif static void TIFFReadDirEntryCheckedByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value); static void TIFFReadDirEntryCheckedSbyte(TIFF* tif, TIFFDirEntry* direntry, int8* value); static void TIFFReadDirEntryCheckedShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value); static void TIFFReadDirEntryCheckedSshort(TIFF* tif, TIFFDirEntry* direntry, int16* value); static void TIFFReadDirEntryCheckedLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value); static void TIFFReadDirEntryCheckedSlong(TIFF* tif, TIFFDirEntry* direntry, int32* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSlong8(TIFF* tif, TIFFDirEntry* direntry, int64* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedRational(TIFF* tif, TIFFDirEntry* direntry, double* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSrational(TIFF* tif, TIFFDirEntry* direntry, double* value); static void TIFFReadDirEntryCheckedFloat(TIFF* tif, TIFFDirEntry* direntry, float* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedDouble(TIFF* tif, TIFFDirEntry* direntry, double* value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSbyte(int8 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteShort(uint16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSshort(int16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong(uint32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong(int32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong8(uint64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong8(int64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteByte(uint8 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteShort(uint16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSshort(int16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong(uint32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong(int32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong8(uint64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong8(int64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSbyte(int8 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSshort(int16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong(uint32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong(int32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong8(uint64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong8(int64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortShort(uint16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong(uint32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong(int32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong8(uint64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong8(int64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSbyte(int8 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSshort(int16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong(int32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongLong8(uint64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong8(int64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongLong(uint32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongLong8(uint64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongSlong8(int64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Sbyte(int8 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Sshort(int16 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Slong(int32 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Slong8(int64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlong8Long8(uint64 value); static enum TIFFReadDirEntryErr TIFFReadDirEntryData(TIFF* tif, uint64 offset, tmsize_t size, void* dest); static void TIFFReadDirEntryOutputErr(TIFF* tif, enum TIFFReadDirEntryErr err, const char* module, const char* tagname, int recover); static void TIFFReadDirectoryCheckOrder(TIFF* tif, TIFFDirEntry* dir, uint16 dircount); static TIFFDirEntry* TIFFReadDirectoryFindEntry(TIFF* tif, TIFFDirEntry* dir, uint16 dircount, uint16 tagid); static void TIFFReadDirectoryFindFieldInfo(TIFF* tif, uint16 tagid, uint32* fii); static int EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount); static void MissingRequired(TIFF*, const char*); static int TIFFCheckDirOffset(TIFF* tif, uint64 diroff); static int CheckDirCount(TIFF*, TIFFDirEntry*, uint32); static uint16 TIFFFetchDirectory(TIFF* tif, uint64 diroff, TIFFDirEntry** pdir, uint64* nextdiroff); static int TIFFFetchNormalTag(TIFF*, TIFFDirEntry*, int recover); static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, uint32 nstrips, uint64** lpp); static int TIFFFetchSubjectDistance(TIFF*, TIFFDirEntry*); static void ChopUpSingleUncompressedStrip(TIFF*); static uint64 TIFFReadUInt64(const uint8 *value); static int _TIFFFillStrilesInternal( TIFF *tif, int loadStripByteCount ); typedef union _UInt64Aligned_t { double d; uint64 l; uint32 i[2]; uint16 s[4]; uint8 c[8]; } UInt64Aligned_t; /* Unaligned safe copy of a uint64 value from an octet array. */ static uint64 TIFFReadUInt64(const uint8 *value) { UInt64Aligned_t result; result.c[0]=value[0]; result.c[1]=value[1]; result.c[2]=value[2]; result.c[3]=value[3]; result.c[4]=value[4]; result.c[5]=value[5]; result.c[6]=value[6]; result.c[7]=value[7]; return result.l; } static enum TIFFReadDirEntryErr TIFFReadDirEntryByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value) { enum TIFFReadDirEntryErr err; if (direntry->tdir_count!=1) return(TIFFReadDirEntryErrCount); switch (direntry->tdir_type) { case TIFF_BYTE: TIFFReadDirEntryCheckedByte(tif,direntry,value); return(TIFFReadDirEntryErrOk); case TIFF_SBYTE: { int8 m; TIFFReadDirEntryCheckedSbyte(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeByteSbyte(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint8)m; return(TIFFReadDirEntryErrOk); } case TIFF_SHORT: { uint16 m; TIFFReadDirEntryCheckedShort(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeByteShort(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint8)m; return(TIFFReadDirEntryErrOk); } case TIFF_SSHORT: { int16 m; TIFFReadDirEntryCheckedSshort(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeByteSshort(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint8)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG: { uint32 m; TIFFReadDirEntryCheckedLong(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeByteLong(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint8)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG: { int32 m; TIFFReadDirEntryCheckedSlong(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeByteSlong(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint8)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG8: { uint64 m; err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); err=TIFFReadDirEntryCheckRangeByteLong8(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint8)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG8: { int64 m; err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); err=TIFFReadDirEntryCheckRangeByteSlong8(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint8)m; return(TIFFReadDirEntryErrOk); } default: return(TIFFReadDirEntryErrType); } } static enum TIFFReadDirEntryErr TIFFReadDirEntryShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value) { enum TIFFReadDirEntryErr err; if (direntry->tdir_count!=1) return(TIFFReadDirEntryErrCount); switch (direntry->tdir_type) { case TIFF_BYTE: { uint8 m; TIFFReadDirEntryCheckedByte(tif,direntry,&m); *value=(uint16)m; return(TIFFReadDirEntryErrOk); } case TIFF_SBYTE: { int8 m; TIFFReadDirEntryCheckedSbyte(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeShortSbyte(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint16)m; return(TIFFReadDirEntryErrOk); } case TIFF_SHORT: TIFFReadDirEntryCheckedShort(tif,direntry,value); return(TIFFReadDirEntryErrOk); case TIFF_SSHORT: { int16 m; TIFFReadDirEntryCheckedSshort(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeShortSshort(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint16)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG: { uint32 m; TIFFReadDirEntryCheckedLong(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeShortLong(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint16)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG: { int32 m; TIFFReadDirEntryCheckedSlong(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeShortSlong(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint16)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG8: { uint64 m; err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); err=TIFFReadDirEntryCheckRangeShortLong8(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint16)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG8: { int64 m; err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); err=TIFFReadDirEntryCheckRangeShortSlong8(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint16)m; return(TIFFReadDirEntryErrOk); } default: return(TIFFReadDirEntryErrType); } } static enum TIFFReadDirEntryErr TIFFReadDirEntryLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value) { enum TIFFReadDirEntryErr err; if (direntry->tdir_count!=1) return(TIFFReadDirEntryErrCount); switch (direntry->tdir_type) { case TIFF_BYTE: { uint8 m; TIFFReadDirEntryCheckedByte(tif,direntry,&m); *value=(uint32)m; return(TIFFReadDirEntryErrOk); } case TIFF_SBYTE: { int8 m; TIFFReadDirEntryCheckedSbyte(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeLongSbyte(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint32)m; return(TIFFReadDirEntryErrOk); } case TIFF_SHORT: { uint16 m; TIFFReadDirEntryCheckedShort(tif,direntry,&m); *value=(uint32)m; return(TIFFReadDirEntryErrOk); } case TIFF_SSHORT: { int16 m; TIFFReadDirEntryCheckedSshort(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeLongSshort(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint32)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG: TIFFReadDirEntryCheckedLong(tif,direntry,value); return(TIFFReadDirEntryErrOk); case TIFF_SLONG: { int32 m; TIFFReadDirEntryCheckedSlong(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeLongSlong(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint32)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG8: { uint64 m; err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); err=TIFFReadDirEntryCheckRangeLongLong8(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint32)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG8: { int64 m; err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); err=TIFFReadDirEntryCheckRangeLongSlong8(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint32)m; return(TIFFReadDirEntryErrOk); } default: return(TIFFReadDirEntryErrType); } } static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value) { enum TIFFReadDirEntryErr err; if (direntry->tdir_count!=1) return(TIFFReadDirEntryErrCount); switch (direntry->tdir_type) { case TIFF_BYTE: { uint8 m; TIFFReadDirEntryCheckedByte(tif,direntry,&m); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } case TIFF_SBYTE: { int8 m; TIFFReadDirEntryCheckedSbyte(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeLong8Sbyte(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } case TIFF_SHORT: { uint16 m; TIFFReadDirEntryCheckedShort(tif,direntry,&m); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } case TIFF_SSHORT: { int16 m; TIFFReadDirEntryCheckedSshort(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeLong8Sshort(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG: { uint32 m; TIFFReadDirEntryCheckedLong(tif,direntry,&m); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG: { int32 m; TIFFReadDirEntryCheckedSlong(tif,direntry,&m); err=TIFFReadDirEntryCheckRangeLong8Slong(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG8: err=TIFFReadDirEntryCheckedLong8(tif,direntry,value); return(err); case TIFF_SLONG8: { int64 m; err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); err=TIFFReadDirEntryCheckRangeLong8Slong8(m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } default: return(TIFFReadDirEntryErrType); } } static enum TIFFReadDirEntryErr TIFFReadDirEntryFloat(TIFF* tif, TIFFDirEntry* direntry, float* value) { enum TIFFReadDirEntryErr err; if (direntry->tdir_count!=1) return(TIFFReadDirEntryErrCount); switch (direntry->tdir_type) { case TIFF_BYTE: { uint8 m; TIFFReadDirEntryCheckedByte(tif,direntry,&m); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_SBYTE: { int8 m; TIFFReadDirEntryCheckedSbyte(tif,direntry,&m); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_SHORT: { uint16 m; TIFFReadDirEntryCheckedShort(tif,direntry,&m); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_SSHORT: { int16 m; TIFFReadDirEntryCheckedSshort(tif,direntry,&m); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG: { uint32 m; TIFFReadDirEntryCheckedLong(tif,direntry,&m); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG: { int32 m; TIFFReadDirEntryCheckedSlong(tif,direntry,&m); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG8: { uint64 m; err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); #if defined(__WIN32__) && (_MSC_VER < 1500) /* * XXX: MSVC 6.0 does not support conversion * of 64-bit integers into floating point * values. */ *value = _TIFFUInt64ToFloat(m); #else *value=(float)m; #endif return(TIFFReadDirEntryErrOk); } case TIFF_SLONG8: { int64 m; err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_RATIONAL: { double m; err=TIFFReadDirEntryCheckedRational(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_SRATIONAL: { double m; err=TIFFReadDirEntryCheckedSrational(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(float)m; return(TIFFReadDirEntryErrOk); } case TIFF_FLOAT: TIFFReadDirEntryCheckedFloat(tif,direntry,value); return(TIFFReadDirEntryErrOk); case TIFF_DOUBLE: { double m; err=TIFFReadDirEntryCheckedDouble(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(float)m; return(TIFFReadDirEntryErrOk); } default: return(TIFFReadDirEntryErrType); } } static enum TIFFReadDirEntryErr TIFFReadDirEntryDouble(TIFF* tif, TIFFDirEntry* direntry, double* value) { enum TIFFReadDirEntryErr err; if (direntry->tdir_count!=1) return(TIFFReadDirEntryErrCount); switch (direntry->tdir_type) { case TIFF_BYTE: { uint8 m; TIFFReadDirEntryCheckedByte(tif,direntry,&m); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_SBYTE: { int8 m; TIFFReadDirEntryCheckedSbyte(tif,direntry,&m); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_SHORT: { uint16 m; TIFFReadDirEntryCheckedShort(tif,direntry,&m); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_SSHORT: { int16 m; TIFFReadDirEntryCheckedSshort(tif,direntry,&m); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG: { uint32 m; TIFFReadDirEntryCheckedLong(tif,direntry,&m); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG: { int32 m; TIFFReadDirEntryCheckedSlong(tif,direntry,&m); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG8: { uint64 m; err=TIFFReadDirEntryCheckedLong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); #if defined(__WIN32__) && (_MSC_VER < 1500) /* * XXX: MSVC 6.0 does not support conversion * of 64-bit integers into floating point * values. */ *value = _TIFFUInt64ToDouble(m); #else *value = (double)m; #endif return(TIFFReadDirEntryErrOk); } case TIFF_SLONG8: { int64 m; err=TIFFReadDirEntryCheckedSlong8(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_RATIONAL: err=TIFFReadDirEntryCheckedRational(tif,direntry,value); return(err); case TIFF_SRATIONAL: err=TIFFReadDirEntryCheckedSrational(tif,direntry,value); return(err); case TIFF_FLOAT: { float m; TIFFReadDirEntryCheckedFloat(tif,direntry,&m); *value=(double)m; return(TIFFReadDirEntryErrOk); } case TIFF_DOUBLE: err=TIFFReadDirEntryCheckedDouble(tif,direntry,value); return(err); default: return(TIFFReadDirEntryErrType); } } static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8(TIFF* tif, TIFFDirEntry* direntry, uint64* value) { enum TIFFReadDirEntryErr err; if (direntry->tdir_count!=1) return(TIFFReadDirEntryErrCount); switch (direntry->tdir_type) { case TIFF_LONG: case TIFF_IFD: { uint32 m; TIFFReadDirEntryCheckedLong(tif,direntry,&m); *value=(uint64)m; return(TIFFReadDirEntryErrOk); } case TIFF_LONG8: case TIFF_IFD8: err=TIFFReadDirEntryCheckedLong8(tif,direntry,value); return(err); default: return(TIFFReadDirEntryErrType); } } static enum TIFFReadDirEntryErr TIFFReadDirEntryArray(TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize, void** value) { int typesize; uint32 datasize; void* data; typesize=TIFFDataWidth(direntry->tdir_type); if ((direntry->tdir_count==0)||(typesize==0)) { *value=0; return(TIFFReadDirEntryErrOk); } (void) desttypesize; /* * As a sanity check, make sure we have no more than a 2GB tag array * in either the current data type or the dest data type. This also * avoids problems with overflow of tmsize_t on 32bit systems. */ if ((uint64)(2147483647/typesize)<direntry->tdir_count) return(TIFFReadDirEntryErrSizesan); if ((uint64)(2147483647/desttypesize)<direntry->tdir_count) return(TIFFReadDirEntryErrSizesan); *count=(uint32)direntry->tdir_count; datasize=(*count)*typesize; assert((tmsize_t)datasize>0); data=_TIFFCheckMalloc(tif, *count, typesize, "ReadDirEntryArray"); if (data==0) return(TIFFReadDirEntryErrAlloc); if (!(tif->tif_flags&TIFF_BIGTIFF)) { if (datasize<=4) _TIFFmemcpy(data,&direntry->tdir_offset,datasize); else { enum TIFFReadDirEntryErr err; uint32 offset = direntry->tdir_offset.toff_long; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&offset); err=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } } } else { if (datasize<=8) _TIFFmemcpy(data,&direntry->tdir_offset,datasize); else { enum TIFFReadDirEntryErr err; uint64 offset = direntry->tdir_offset.toff_long8; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(&offset); err=TIFFReadDirEntryData(tif,offset,(tmsize_t)datasize,data); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } } } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryByteArray(TIFF* tif, TIFFDirEntry* direntry, uint8** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; uint8* data; switch (direntry->tdir_type) { case TIFF_ASCII: case TIFF_UNDEFINED: case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,1,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_ASCII: case TIFF_UNDEFINED: case TIFF_BYTE: *value=(uint8*)origdata; return(TIFFReadDirEntryErrOk); case TIFF_SBYTE: { int8* m; uint32 n; m=(int8*)origdata; for (n=0; n<count; n++) { err=TIFFReadDirEntryCheckRangeByteSbyte(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(uint8*)origdata; return(TIFFReadDirEntryErrOk); } } data=(uint8*)_TIFFmalloc(count); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_SHORT: { uint16* ma; uint8* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); err=TIFFReadDirEntryCheckRangeByteShort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; uint8* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); err=TIFFReadDirEntryCheckRangeByteSshort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_LONG: { uint32* ma; uint8* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); err=TIFFReadDirEntryCheckRangeByteLong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_SLONG: { int32* ma; uint8* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); err=TIFFReadDirEntryCheckRangeByteSlong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; uint8* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); err=TIFFReadDirEntryCheckRangeByteLong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; case TIFF_SLONG8: { int64* ma; uint8* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); err=TIFFReadDirEntryCheckRangeByteSlong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint8)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntrySbyteArray(TIFF* tif, TIFFDirEntry* direntry, int8** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; int8* data; switch (direntry->tdir_type) { case TIFF_UNDEFINED: case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,1,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_UNDEFINED: case TIFF_BYTE: { uint8* m; uint32 n; m=(uint8*)origdata; for (n=0; n<count; n++) { err=TIFFReadDirEntryCheckRangeSbyteByte(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(int8*)origdata; return(TIFFReadDirEntryErrOk); } case TIFF_SBYTE: *value=(int8*)origdata; return(TIFFReadDirEntryErrOk); } data=(int8*)_TIFFmalloc(count); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_SHORT: { uint16* ma; int8* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); err=TIFFReadDirEntryCheckRangeSbyteShort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int8)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; int8* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); err=TIFFReadDirEntryCheckRangeSbyteSshort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int8)(*ma++); } } break; case TIFF_LONG: { uint32* ma; int8* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); err=TIFFReadDirEntryCheckRangeSbyteLong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int8)(*ma++); } } break; case TIFF_SLONG: { int32* ma; int8* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); err=TIFFReadDirEntryCheckRangeSbyteSlong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int8)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; int8* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); err=TIFFReadDirEntryCheckRangeSbyteLong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int8)(*ma++); } } break; case TIFF_SLONG8: { int64* ma; int8* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); err=TIFFReadDirEntryCheckRangeSbyteSlong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int8)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryShortArray(TIFF* tif, TIFFDirEntry* direntry, uint16** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; uint16* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,2,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_SHORT: *value=(uint16*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfShort(*value,count); return(TIFFReadDirEntryErrOk); case TIFF_SSHORT: { int16* m; uint32 n; m=(int16*)origdata; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)m); err=TIFFReadDirEntryCheckRangeShortSshort(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(uint16*)origdata; return(TIFFReadDirEntryErrOk); } } data=(uint16*)_TIFFmalloc(count*2); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; uint16* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(uint16)(*ma++); } break; case TIFF_SBYTE: { int8* ma; uint16* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) { err=TIFFReadDirEntryCheckRangeShortSbyte(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint16)(*ma++); } } break; case TIFF_LONG: { uint32* ma; uint16* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); err=TIFFReadDirEntryCheckRangeShortLong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint16)(*ma++); } } break; case TIFF_SLONG: { int32* ma; uint16* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); err=TIFFReadDirEntryCheckRangeShortSlong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint16)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; uint16* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); err=TIFFReadDirEntryCheckRangeShortLong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint16)(*ma++); } } break; case TIFF_SLONG8: { int64* ma; uint16* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); err=TIFFReadDirEntryCheckRangeShortSlong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint16)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntrySshortArray(TIFF* tif, TIFFDirEntry* direntry, int16** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; int16* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,2,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_SHORT: { uint16* m; uint32 n; m=(uint16*)origdata; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(m); err=TIFFReadDirEntryCheckRangeSshortShort(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(int16*)origdata; return(TIFFReadDirEntryErrOk); } case TIFF_SSHORT: *value=(int16*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfShort((uint16*)(*value),count); return(TIFFReadDirEntryErrOk); } data=(int16*)_TIFFmalloc(count*2); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; int16* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(int16)(*ma++); } break; case TIFF_SBYTE: { int8* ma; int16* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(int16)(*ma++); } break; case TIFF_LONG: { uint32* ma; int16* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); err=TIFFReadDirEntryCheckRangeSshortLong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int16)(*ma++); } } break; case TIFF_SLONG: { int32* ma; int16* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); err=TIFFReadDirEntryCheckRangeSshortSlong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int16)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; int16* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); err=TIFFReadDirEntryCheckRangeSshortLong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int16)(*ma++); } } break; case TIFF_SLONG8: { int64* ma; int16* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); err=TIFFReadDirEntryCheckRangeSshortSlong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int16)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryLongArray(TIFF* tif, TIFFDirEntry* direntry, uint32** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; uint32* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_LONG: *value=(uint32*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(*value,count); return(TIFFReadDirEntryErrOk); case TIFF_SLONG: { int32* m; uint32 n; m=(int32*)origdata; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)m); err=TIFFReadDirEntryCheckRangeLongSlong(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(uint32*)origdata; return(TIFFReadDirEntryErrOk); } } data=(uint32*)_TIFFmalloc(count*4); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; uint32* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(uint32)(*ma++); } break; case TIFF_SBYTE: { int8* ma; uint32* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) { err=TIFFReadDirEntryCheckRangeLongSbyte(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint32)(*ma++); } } break; case TIFF_SHORT: { uint16* ma; uint32* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(uint32)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; uint32* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); err=TIFFReadDirEntryCheckRangeLongSshort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint32)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; uint32* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); err=TIFFReadDirEntryCheckRangeLongLong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint32)(*ma++); } } break; case TIFF_SLONG8: { int64* ma; uint32* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); err=TIFFReadDirEntryCheckRangeLongSlong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint32)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntrySlongArray(TIFF* tif, TIFFDirEntry* direntry, int32** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; int32* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_LONG: { uint32* m; uint32 n; m=(uint32*)origdata; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)m); err=TIFFReadDirEntryCheckRangeSlongLong(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(int32*)origdata; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG: *value=(int32*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)(*value),count); return(TIFFReadDirEntryErrOk); } data=(int32*)_TIFFmalloc(count*4); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; int32* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(int32)(*ma++); } break; case TIFF_SBYTE: { int8* ma; int32* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(int32)(*ma++); } break; case TIFF_SHORT: { uint16* ma; int32* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(int32)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; int32* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); *mb++=(int32)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; int32* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); err=TIFFReadDirEntryCheckRangeSlongLong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int32)(*ma++); } } break; case TIFF_SLONG8: { int64* ma; int32* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); err=TIFFReadDirEntryCheckRangeSlongSlong8(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(int32)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryLong8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; uint64* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_LONG8: *value=(uint64*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8(*value,count); return(TIFFReadDirEntryErrOk); case TIFF_SLONG8: { int64* m; uint32 n; m=(int64*)origdata; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)m); err=TIFFReadDirEntryCheckRangeLong8Slong8(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(uint64*)origdata; return(TIFFReadDirEntryErrOk); } } data=(uint64*)_TIFFmalloc(count*8); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; uint64* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(uint64)(*ma++); } break; case TIFF_SBYTE: { int8* ma; uint64* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) { err=TIFFReadDirEntryCheckRangeLong8Sbyte(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint64)(*ma++); } } break; case TIFF_SHORT: { uint16* ma; uint64* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(uint64)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; uint64* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); err=TIFFReadDirEntryCheckRangeLong8Sshort(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint64)(*ma++); } } break; case TIFF_LONG: { uint32* ma; uint64* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); *mb++=(uint64)(*ma++); } } break; case TIFF_SLONG: { int32* ma; uint64* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); err=TIFFReadDirEntryCheckRangeLong8Slong(*ma); if (err!=TIFFReadDirEntryErrOk) break; *mb++=(uint64)(*ma++); } } break; } _TIFFfree(origdata); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(data); return(err); } *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntrySlong8Array(TIFF* tif, TIFFDirEntry* direntry, int64** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; int64* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_LONG8: { uint64* m; uint32 n; m=(uint64*)origdata; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(m); err=TIFFReadDirEntryCheckRangeSlong8Long8(*m); if (err!=TIFFReadDirEntryErrOk) { _TIFFfree(origdata); return(err); } m++; } *value=(int64*)origdata; return(TIFFReadDirEntryErrOk); } case TIFF_SLONG8: *value=(int64*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8((uint64*)(*value),count); return(TIFFReadDirEntryErrOk); } data=(int64*)_TIFFmalloc(count*8); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; int64* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(int64)(*ma++); } break; case TIFF_SBYTE: { int8* ma; int64* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(int64)(*ma++); } break; case TIFF_SHORT: { uint16* ma; int64* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(int64)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; int64* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); *mb++=(int64)(*ma++); } } break; case TIFF_LONG: { uint32* ma; int64* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); *mb++=(int64)(*ma++); } } break; case TIFF_SLONG: { int32* ma; int64* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); *mb++=(int64)(*ma++); } } break; } _TIFFfree(origdata); *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryFloatArray(TIFF* tif, TIFFDirEntry* direntry, float** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; float* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: case TIFF_DOUBLE: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_FLOAT: if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)origdata,count); TIFFCvtIEEEDoubleToNative(tif,count,(float*)origdata); *value=(float*)origdata; return(TIFFReadDirEntryErrOk); } data=(float*)_TIFFmalloc(count*sizeof(float)); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; float* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(float)(*ma++); } break; case TIFF_SBYTE: { int8* ma; float* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(float)(*ma++); } break; case TIFF_SHORT: { uint16* ma; float* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(float)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; float* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); *mb++=(float)(*ma++); } } break; case TIFF_LONG: { uint32* ma; float* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); *mb++=(float)(*ma++); } } break; case TIFF_SLONG: { int32* ma; float* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); *mb++=(float)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; float* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); #if defined(__WIN32__) && (_MSC_VER < 1500) /* * XXX: MSVC 6.0 does not support * conversion of 64-bit integers into * floating point values. */ *mb++ = _TIFFUInt64ToFloat(*ma++); #else *mb++ = (float)(*ma++); #endif } } break; case TIFF_SLONG8: { int64* ma; float* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); *mb++=(float)(*ma++); } } break; case TIFF_RATIONAL: { uint32* ma; uint32 maa; uint32 mab; float* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); maa=*ma++; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); mab=*ma++; if (mab==0) *mb++=0.0; else *mb++=(float)maa/(float)mab; } } break; case TIFF_SRATIONAL: { uint32* ma; int32 maa; uint32 mab; float* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); maa=*(int32*)ma; ma++; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); mab=*ma++; if (mab==0) *mb++=0.0; else *mb++=(float)maa/(float)mab; } } break; case TIFF_DOUBLE: { double* ma; float* mb; uint32 n; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8((uint64*)origdata,count); TIFFCvtIEEEDoubleToNative(tif,count,(double*)origdata); ma=(double*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(float)(*ma++); } break; } _TIFFfree(origdata); *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryDoubleArray(TIFF* tif, TIFFDirEntry* direntry, double** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; double* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: case TIFF_DOUBLE: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_DOUBLE: if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8((uint64*)origdata,count); TIFFCvtIEEEDoubleToNative(tif,count,(double*)origdata); *value=(double*)origdata; return(TIFFReadDirEntryErrOk); } data=(double*)_TIFFmalloc(count*sizeof(double)); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; double* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(double)(*ma++); } break; case TIFF_SBYTE: { int8* ma; double* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(double)(*ma++); } break; case TIFF_SHORT: { uint16* ma; double* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(double)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; double* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); *mb++=(double)(*ma++); } } break; case TIFF_LONG: { uint32* ma; double* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); *mb++=(double)(*ma++); } } break; case TIFF_SLONG: { int32* ma; double* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); *mb++=(double)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; double* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); #if defined(__WIN32__) && (_MSC_VER < 1500) /* * XXX: MSVC 6.0 does not support * conversion of 64-bit integers into * floating point values. */ *mb++ = _TIFFUInt64ToDouble(*ma++); #else *mb++ = (double)(*ma++); #endif } } break; case TIFF_SLONG8: { int64* ma; double* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); *mb++=(double)(*ma++); } } break; case TIFF_RATIONAL: { uint32* ma; uint32 maa; uint32 mab; double* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); maa=*ma++; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); mab=*ma++; if (mab==0) *mb++=0.0; else *mb++=(double)maa/(double)mab; } } break; case TIFF_SRATIONAL: { uint32* ma; int32 maa; uint32 mab; double* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); maa=*(int32*)ma; ma++; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); mab=*ma++; if (mab==0) *mb++=0.0; else *mb++=(double)maa/(double)mab; } } break; case TIFF_FLOAT: { float* ma; double* mb; uint32 n; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)origdata,count); TIFFCvtIEEEFloatToNative(tif,count,(float*)origdata); ma=(float*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(double)(*ma++); } break; } _TIFFfree(origdata); *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; uint64* data; switch (direntry->tdir_type) { case TIFF_LONG: case TIFF_LONG8: case TIFF_IFD: case TIFF_IFD8: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_LONG8: case TIFF_IFD8: *value=(uint64*)origdata; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8(*value,count); return(TIFFReadDirEntryErrOk); } data=(uint64*)_TIFFmalloc(count*8); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_LONG: case TIFF_IFD: { uint32* ma; uint64* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); *mb++=(uint64)(*ma++); } } break; } _TIFFfree(origdata); *value=data; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value) { enum TIFFReadDirEntryErr err; uint16* m; uint16* na; uint16 nb; if (direntry->tdir_count<(uint64)tif->tif_dir.td_samplesperpixel) return(TIFFReadDirEntryErrCount); err=TIFFReadDirEntryShortArray(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); na=m; nb=tif->tif_dir.td_samplesperpixel; *value=*na++; nb--; while (nb>0) { if (*na++!=*value) { err=TIFFReadDirEntryErrPsdif; break; } nb--; } _TIFFfree(m); return(err); } #if 0 static enum TIFFReadDirEntryErr TIFFReadDirEntryPersampleDouble(TIFF* tif, TIFFDirEntry* direntry, double* value) { enum TIFFReadDirEntryErr err; double* m; double* na; uint16 nb; if (direntry->tdir_count<(uint64)tif->tif_dir.td_samplesperpixel) return(TIFFReadDirEntryErrCount); err=TIFFReadDirEntryDoubleArray(tif,direntry,&m); if (err!=TIFFReadDirEntryErrOk) return(err); na=m; nb=tif->tif_dir.td_samplesperpixel; *value=*na++; nb--; while (nb>0) { if (*na++!=*value) { err=TIFFReadDirEntryErrPsdif; break; } nb--; } _TIFFfree(m); return(err); } #endif static void TIFFReadDirEntryCheckedByte(TIFF* tif, TIFFDirEntry* direntry, uint8* value) { (void) tif; *value=*(uint8*)(&direntry->tdir_offset); } static void TIFFReadDirEntryCheckedSbyte(TIFF* tif, TIFFDirEntry* direntry, int8* value) { (void) tif; *value=*(int8*)(&direntry->tdir_offset); } static void TIFFReadDirEntryCheckedShort(TIFF* tif, TIFFDirEntry* direntry, uint16* value) { *value = direntry->tdir_offset.toff_short; /* *value=*(uint16*)(&direntry->tdir_offset); */ if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(value); } static void TIFFReadDirEntryCheckedSshort(TIFF* tif, TIFFDirEntry* direntry, int16* value) { *value=*(int16*)(&direntry->tdir_offset); if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)value); } static void TIFFReadDirEntryCheckedLong(TIFF* tif, TIFFDirEntry* direntry, uint32* value) { *value=*(uint32*)(&direntry->tdir_offset); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(value); } static void TIFFReadDirEntryCheckedSlong(TIFF* tif, TIFFDirEntry* direntry, int32* value) { *value=*(int32*)(&direntry->tdir_offset); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)value); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedLong8(TIFF* tif, TIFFDirEntry* direntry, uint64* value) { if (!(tif->tif_flags&TIFF_BIGTIFF)) { enum TIFFReadDirEntryErr err; uint32 offset = direntry->tdir_offset.toff_long; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&offset); err=TIFFReadDirEntryData(tif,offset,8,value); if (err!=TIFFReadDirEntryErrOk) return(err); } else *value = direntry->tdir_offset.toff_long8; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(value); return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSlong8(TIFF* tif, TIFFDirEntry* direntry, int64* value) { if (!(tif->tif_flags&TIFF_BIGTIFF)) { enum TIFFReadDirEntryErr err; uint32 offset = direntry->tdir_offset.toff_long; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&offset); err=TIFFReadDirEntryData(tif,offset,8,value); if (err!=TIFFReadDirEntryErrOk) return(err); } else *value=*(int64*)(&direntry->tdir_offset); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)value); return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedRational(TIFF* tif, TIFFDirEntry* direntry, double* value) { UInt64Aligned_t m; assert(sizeof(double)==8); assert(sizeof(uint64)==8); assert(sizeof(uint32)==4); if (!(tif->tif_flags&TIFF_BIGTIFF)) { enum TIFFReadDirEntryErr err; uint32 offset = direntry->tdir_offset.toff_long; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&offset); err=TIFFReadDirEntryData(tif,offset,8,m.i); if (err!=TIFFReadDirEntryErrOk) return(err); } else m.l = direntry->tdir_offset.toff_long8; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(m.i,2); if (m.i[0]==0) *value=0.0; else *value=(double)m.i[0]/(double)m.i[1]; return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedSrational(TIFF* tif, TIFFDirEntry* direntry, double* value) { UInt64Aligned_t m; assert(sizeof(double)==8); assert(sizeof(uint64)==8); assert(sizeof(int32)==4); assert(sizeof(uint32)==4); if (!(tif->tif_flags&TIFF_BIGTIFF)) { enum TIFFReadDirEntryErr err; uint32 offset = direntry->tdir_offset.toff_long; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&offset); err=TIFFReadDirEntryData(tif,offset,8,m.i); if (err!=TIFFReadDirEntryErrOk) return(err); } else m.l=direntry->tdir_offset.toff_long8; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(m.i,2); if ((int32)m.i[0]==0) *value=0.0; else *value=(double)((int32)m.i[0])/(double)m.i[1]; return(TIFFReadDirEntryErrOk); } static void TIFFReadDirEntryCheckedFloat(TIFF* tif, TIFFDirEntry* direntry, float* value) { union { float f; uint32 i; } float_union; assert(sizeof(float)==4); assert(sizeof(uint32)==4); assert(sizeof(float_union)==4); float_union.i=*(uint32*)(&direntry->tdir_offset); *value=float_union.f; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)value); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckedDouble(TIFF* tif, TIFFDirEntry* direntry, double* value) { assert(sizeof(double)==8); assert(sizeof(uint64)==8); assert(sizeof(UInt64Aligned_t)==8); if (!(tif->tif_flags&TIFF_BIGTIFF)) { enum TIFFReadDirEntryErr err; uint32 offset = direntry->tdir_offset.toff_long; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&offset); err=TIFFReadDirEntryData(tif,offset,8,value); if (err!=TIFFReadDirEntryErrOk) return(err); } else { UInt64Aligned_t uint64_union; uint64_union.l=direntry->tdir_offset.toff_long8; *value=uint64_union.d; } if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)value); return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSbyte(int8 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteShort(uint16 value) { if (value>0xFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSshort(int16 value) { if ((value<0)||(value>0xFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong(uint32 value) { if (value>0xFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong(int32 value) { if ((value<0)||(value>0xFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteLong8(uint64 value) { if (value>0xFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSlong8(int64 value) { if ((value<0)||(value>0xFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteByte(uint8 value) { if (value>0x7F) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteShort(uint16 value) { if (value>0x7F) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSshort(int16 value) { if ((value<-0x80)||(value>0x7F)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong(uint32 value) { if (value>0x7F) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong(int32 value) { if ((value<-0x80)||(value>0x7F)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteLong8(uint64 value) { if (value>0x7F) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSbyteSlong8(int64 value) { if ((value<-0x80)||(value>0x7F)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSbyte(int8 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSshort(int16 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong(uint32 value) { if (value>0xFFFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong(int32 value) { if ((value<0)||(value>0xFFFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortLong8(uint64 value) { if (value>0xFFFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeShortSlong8(int64 value) { if ((value<0)||(value>0xFFFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortShort(uint16 value) { if (value>0x7FFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong(uint32 value) { if (value>0x7FFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong(int32 value) { if ((value<-0x8000)||(value>0x7FFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortLong8(uint64 value) { if (value>0x7FFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSshortSlong8(int64 value) { if ((value<-0x8000)||(value>0x7FFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSbyte(int8 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSshort(int16 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong(int32 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } /* * Largest 32-bit unsigned integer value. */ #define TIFF_UINT32_MAX 0xFFFFFFFFU static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongLong8(uint64 value) { if (value > TIFF_UINT32_MAX) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSlong8(int64 value) { if ((value < 0) || (value > (int64) TIFF_UINT32_MAX)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } #undef TIFF_UINT32_MAX static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongLong(uint32 value) { if (value > 0x7FFFFFFFUL) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } /* Check that the 8-byte unsigned value can fit in a 4-byte unsigned range */ static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongLong8(uint64 value) { if (value > 0x7FFFFFFF) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } /* Check that the 8-byte signed value can fit in a 4-byte signed range */ static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlongSlong8(int64 value) { if ((value < 0-((int64) 0x7FFFFFFF+1)) || (value > 0x7FFFFFFF)) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Sbyte(int8 value) { if (value < 0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Sshort(int16 value) { if (value < 0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Slong(int32 value) { if (value < 0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLong8Slong8(int64 value) { if (value < 0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } /* * Largest 64-bit signed integer value. */ #define TIFF_INT64_MAX ((int64)(((uint64) ~0) >> 1)) static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeSlong8Long8(uint64 value) { if (value > TIFF_INT64_MAX) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } #undef TIFF_INT64_MAX static enum TIFFReadDirEntryErr TIFFReadDirEntryData(TIFF* tif, uint64 offset, tmsize_t size, void* dest) { assert(size>0); if (!isMapped(tif)) { if (!SeekOK(tif,offset)) return(TIFFReadDirEntryErrIo); if (!ReadOK(tif,dest,size)) return(TIFFReadDirEntryErrIo); } else { size_t ma,mb; ma=(size_t)offset; mb=ma+size; if (((uint64)ma!=offset) || (mb < ma) || (mb - ma != (size_t) size) || (mb < (size_t)size) || (mb > (size_t)tif->tif_size) ) return(TIFFReadDirEntryErrIo); _TIFFmemcpy(dest,tif->tif_base+ma,size); } return(TIFFReadDirEntryErrOk); } static void TIFFReadDirEntryOutputErr(TIFF* tif, enum TIFFReadDirEntryErr err, const char* module, const char* tagname, int recover) { if (!recover) { switch (err) { case TIFFReadDirEntryErrCount: TIFFErrorExt(tif->tif_clientdata, module, "Incorrect count for \"%s\"", tagname); break; case TIFFReadDirEntryErrType: TIFFErrorExt(tif->tif_clientdata, module, "Incompatible type for \"%s\"", tagname); break; case TIFFReadDirEntryErrIo: TIFFErrorExt(tif->tif_clientdata, module, "IO error during reading of \"%s\"", tagname); break; case TIFFReadDirEntryErrRange: TIFFErrorExt(tif->tif_clientdata, module, "Incorrect value for \"%s\"", tagname); break; case TIFFReadDirEntryErrPsdif: TIFFErrorExt(tif->tif_clientdata, module, "Cannot handle different values per sample for \"%s\"", tagname); break; case TIFFReadDirEntryErrSizesan: TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on size of \"%s\" value failed", tagname); break; case TIFFReadDirEntryErrAlloc: TIFFErrorExt(tif->tif_clientdata, module, "Out of memory reading of \"%s\"", tagname); break; default: assert(0); /* we should never get here */ break; } } else { switch (err) { case TIFFReadDirEntryErrCount: TIFFWarningExt(tif->tif_clientdata, module, "Incorrect count for \"%s\"; tag ignored", tagname); break; case TIFFReadDirEntryErrType: TIFFWarningExt(tif->tif_clientdata, module, "Incompatible type for \"%s\"; tag ignored", tagname); break; case TIFFReadDirEntryErrIo: TIFFWarningExt(tif->tif_clientdata, module, "IO error during reading of \"%s\"; tag ignored", tagname); break; case TIFFReadDirEntryErrRange: TIFFWarningExt(tif->tif_clientdata, module, "Incorrect value for \"%s\"; tag ignored", tagname); break; case TIFFReadDirEntryErrPsdif: TIFFWarningExt(tif->tif_clientdata, module, "Cannot handle different values per sample for \"%s\"; tag ignored", tagname); break; case TIFFReadDirEntryErrSizesan: TIFFWarningExt(tif->tif_clientdata, module, "Sanity check on size of \"%s\" value failed; tag ignored", tagname); break; case TIFFReadDirEntryErrAlloc: TIFFWarningExt(tif->tif_clientdata, module, "Out of memory reading of \"%s\"; tag ignored", tagname); break; default: assert(0); /* we should never get here */ break; } } } /* * Read the next TIFF directory from a file and convert it to the internal * format. We read directories sequentially. */ int TIFFReadDirectory(TIFF* tif) { static const char module[] = "TIFFReadDirectory"; TIFFDirEntry* dir; uint16 dircount; TIFFDirEntry* dp; uint16 di; const TIFFField* fip; uint32 fii=FAILED_FII; toff_t nextdiroff; int bitspersample_read = FALSE; tif->tif_diroff=tif->tif_nextdiroff; if (!TIFFCheckDirOffset(tif,tif->tif_nextdiroff)) return 0; /* last offset or bad offset (IFD looping) */ (*tif->tif_cleanup)(tif); /* cleanup any previous compression state */ tif->tif_curdir++; nextdiroff = tif->tif_nextdiroff; dircount=TIFFFetchDirectory(tif,nextdiroff,&dir,&tif->tif_nextdiroff); if (!dircount) { TIFFErrorExt(tif->tif_clientdata,module, "Failed to read directory at offset " TIFF_UINT64_FORMAT,nextdiroff); return 0; } TIFFReadDirectoryCheckOrder(tif,dir,dircount); /* * Mark duplicates of any tag to be ignored (bugzilla 1994) * to avoid certain pathological problems. */ { TIFFDirEntry* ma; uint16 mb; for (ma=dir, mb=0; mb<dircount; ma++, mb++) { TIFFDirEntry* na; uint16 nb; for (na=ma+1, nb=mb+1; nb<dircount; na++, nb++) { if (ma->tdir_tag==na->tdir_tag) na->tdir_tag=IGNORE; } } } tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ tif->tif_flags &= ~TIFF_BUF4WRITE; /* reset before new dir */ /* free any old stuff and reinit */ TIFFFreeDirectory(tif); TIFFDefaultDirectory(tif); /* * Electronic Arts writes gray-scale TIFF files * without a PlanarConfiguration directory entry. * Thus we setup a default value here, even though * the TIFF spec says there is no default value. */ TIFFSetField(tif,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); /* * Setup default value and then make a pass over * the fields to check type and tag information, * and to extract info required to size data * structures. A second pass is made afterwards * to read in everything not taken in the first pass. * But we must process the Compression tag first * in order to merge in codec-private tag definitions (otherwise * we may get complaints about unknown tags). However, the * Compression tag may be dependent on the SamplesPerPixel * tag value because older TIFF specs permitted Compression * to be written as a SamplesPerPixel-count tag entry. * Thus if we don't first figure out the correct SamplesPerPixel * tag value then we may end up ignoring the Compression tag * value because it has an incorrect count value (if the * true value of SamplesPerPixel is not 1). */ dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_SAMPLESPERPIXEL); if (dp) { if (!TIFFFetchNormalTag(tif,dp,0)) goto bad; dp->tdir_tag=IGNORE; } dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_COMPRESSION); if (dp) { /* * The 5.0 spec says the Compression tag has one value, while * earlier specs say it has one value per sample. Because of * this, we accept the tag if one value is supplied with either * count. */ uint16 value; enum TIFFReadDirEntryErr err; err=TIFFReadDirEntryShort(tif,dp,&value); if (err==TIFFReadDirEntryErrCount) err=TIFFReadDirEntryPersampleShort(tif,dp,&value); if (err!=TIFFReadDirEntryErrOk) { TIFFReadDirEntryOutputErr(tif,err,module,"Compression",0); goto bad; } if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,value)) goto bad; dp->tdir_tag=IGNORE; } else { if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,COMPRESSION_NONE)) goto bad; } /* * First real pass over the directory. */ for (di=0, dp=dir; di<dircount; di++, dp++) { if (dp->tdir_tag!=IGNORE) { TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); if (fii == FAILED_FII) { TIFFWarningExt(tif->tif_clientdata, module, "Unknown field with tag %d (0x%x) encountered", dp->tdir_tag,dp->tdir_tag); /* the following knowingly leaks the anonymous field structure */ if (!_TIFFMergeFields(tif, _TIFFCreateAnonField(tif, dp->tdir_tag, (TIFFDataType) dp->tdir_type), 1)) { TIFFWarningExt(tif->tif_clientdata, module, "Registering anonymous field with tag %d (0x%x) failed", dp->tdir_tag, dp->tdir_tag); dp->tdir_tag=IGNORE; } else { TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); assert(fii != FAILED_FII); } } } if (dp->tdir_tag!=IGNORE) { fip=tif->tif_fields[fii]; if (fip->field_bit==FIELD_IGNORE) dp->tdir_tag=IGNORE; else { switch (dp->tdir_tag) { case TIFFTAG_STRIPOFFSETS: case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEOFFSETS: case TIFFTAG_TILEBYTECOUNTS: TIFFSetFieldBit(tif,fip->field_bit); break; case TIFFTAG_IMAGEWIDTH: case TIFFTAG_IMAGELENGTH: case TIFFTAG_IMAGEDEPTH: case TIFFTAG_TILELENGTH: case TIFFTAG_TILEWIDTH: case TIFFTAG_TILEDEPTH: case TIFFTAG_PLANARCONFIG: case TIFFTAG_ROWSPERSTRIP: case TIFFTAG_EXTRASAMPLES: if (!TIFFFetchNormalTag(tif,dp,0)) goto bad; dp->tdir_tag=IGNORE; break; } } } } /* * XXX: OJPEG hack. * If a) compression is OJPEG, b) planarconfig tag says it's separate, * c) strip offsets/bytecounts tag are both present and * d) both contain exactly one value, then we consistently find * that the buggy implementation of the buggy compression scheme * matches contig planarconfig best. So we 'fix-up' the tag here */ if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG)&& (tif->tif_dir.td_planarconfig==PLANARCONFIG_SEPARATE)) { if (!_TIFFFillStriles(tif)) goto bad; dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_STRIPOFFSETS); if ((dp!=0)&&(dp->tdir_count==1)) { dp=TIFFReadDirectoryFindEntry(tif,dir,dircount, TIFFTAG_STRIPBYTECOUNTS); if ((dp!=0)&&(dp->tdir_count==1)) { tif->tif_dir.td_planarconfig=PLANARCONFIG_CONTIG; TIFFWarningExt(tif->tif_clientdata,module, "Planarconfig tag value assumed incorrect, " "assuming data is contig instead of chunky"); } } } /* * Allocate directory structure and setup defaults. */ if (!TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) { MissingRequired(tif,"ImageLength"); goto bad; } /* * Setup appropriate structures (by strip or by tile) */ if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { tif->tif_dir.td_nstrips = TIFFNumberOfStrips(tif); tif->tif_dir.td_tilewidth = tif->tif_dir.td_imagewidth; tif->tif_dir.td_tilelength = tif->tif_dir.td_rowsperstrip; tif->tif_dir.td_tiledepth = tif->tif_dir.td_imagedepth; tif->tif_flags &= ~TIFF_ISTILED; } else { tif->tif_dir.td_nstrips = TIFFNumberOfTiles(tif); tif->tif_flags |= TIFF_ISTILED; } if (!tif->tif_dir.td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "Cannot handle zero number of %s", isTiled(tif) ? "tiles" : "strips"); goto bad; } tif->tif_dir.td_stripsperimage = tif->tif_dir.td_nstrips; if (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE) tif->tif_dir.td_stripsperimage /= tif->tif_dir.td_samplesperpixel; if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { #ifdef OJPEG_SUPPORT if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG) && (isTiled(tif)==0) && (tif->tif_dir.td_nstrips==1)) { /* * XXX: OJPEG hack. * If a) compression is OJPEG, b) it's not a tiled TIFF, * and c) the number of strips is 1, * then we tolerate the absence of stripoffsets tag, * because, presumably, all required data is in the * JpegInterchangeFormat stream. */ TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS); } else #endif { MissingRequired(tif, isTiled(tif) ? "TileOffsets" : "StripOffsets"); goto bad; } } /* * Second pass: extract other information. */ for (di=0, dp=dir; di<dircount; di++, dp++) { switch (dp->tdir_tag) { case IGNORE: break; case TIFFTAG_MINSAMPLEVALUE: case TIFFTAG_MAXSAMPLEVALUE: case TIFFTAG_BITSPERSAMPLE: case TIFFTAG_DATATYPE: case TIFFTAG_SAMPLEFORMAT: /* * The MinSampleValue, MaxSampleValue, BitsPerSample * DataType and SampleFormat tags are supposed to be * written as one value/sample, but some vendors * incorrectly write one value only -- so we accept * that as well (yuck). Other vendors write correct * value for NumberOfSamples, but incorrect one for * BitsPerSample and friends, and we will read this * too. */ { uint16 value; enum TIFFReadDirEntryErr err; err=TIFFReadDirEntryShort(tif,dp,&value); if (err==TIFFReadDirEntryErrCount) err=TIFFReadDirEntryPersampleShort(tif,dp,&value); if (err!=TIFFReadDirEntryErrOk) { fip = TIFFFieldWithTag(tif,dp->tdir_tag); TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",0); goto bad; } if (!TIFFSetField(tif,dp->tdir_tag,value)) goto bad; if( dp->tdir_tag == TIFFTAG_BITSPERSAMPLE ) bitspersample_read = TRUE; } break; case TIFFTAG_SMINSAMPLEVALUE: case TIFFTAG_SMAXSAMPLEVALUE: { double *data = NULL; enum TIFFReadDirEntryErr err; uint32 saved_flags; int m; if (dp->tdir_count != (uint64)tif->tif_dir.td_samplesperpixel) err = TIFFReadDirEntryErrCount; else err = TIFFReadDirEntryDoubleArray(tif, dp, &data); if (err!=TIFFReadDirEntryErrOk) { fip = TIFFFieldWithTag(tif,dp->tdir_tag); TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",0); goto bad; } saved_flags = tif->tif_flags; tif->tif_flags |= TIFF_PERSAMPLE; m = TIFFSetField(tif,dp->tdir_tag,data); tif->tif_flags = saved_flags; _TIFFfree(data); if (!m) goto bad; } break; case TIFFTAG_STRIPOFFSETS: case TIFFTAG_TILEOFFSETS: #if defined(DEFER_STRILE_LOAD) _TIFFmemcpy( &(tif->tif_dir.td_stripoffset_entry), dp, sizeof(TIFFDirEntry) ); #else if (!TIFFFetchStripThing(tif,dp,tif->tif_dir.td_nstrips,&tif->tif_dir.td_stripoffset)) goto bad; #endif break; case TIFFTAG_STRIPBYTECOUNTS: case TIFFTAG_TILEBYTECOUNTS: #if defined(DEFER_STRILE_LOAD) _TIFFmemcpy( &(tif->tif_dir.td_stripbytecount_entry), dp, sizeof(TIFFDirEntry) ); #else if (!TIFFFetchStripThing(tif,dp,tif->tif_dir.td_nstrips,&tif->tif_dir.td_stripbytecount)) goto bad; #endif break; case TIFFTAG_COLORMAP: case TIFFTAG_TRANSFERFUNCTION: { enum TIFFReadDirEntryErr err; uint32 countpersample; uint32 countrequired; uint32 incrementpersample; uint16* value=NULL; /* It would be dangerous to instantiate those tag values */ /* since if td_bitspersample has not yet been read (due to */ /* unordered tags), it could be read afterwards with a */ /* values greater than the default one (1), which may cause */ /* crashes in user code */ if( !bitspersample_read ) { fip = TIFFFieldWithTag(tif,dp->tdir_tag); TIFFWarningExt(tif->tif_clientdata,module, "Ignoring %s since BitsPerSample tag not found", fip ? fip->field_name : "unknown tagname"); continue; } /* ColorMap or TransferFunction for high bit */ /* depths do not make much sense and could be */ /* used as a denial of service vector */ if (tif->tif_dir.td_bitspersample > 24) { fip = TIFFFieldWithTag(tif,dp->tdir_tag); TIFFWarningExt(tif->tif_clientdata,module, "Ignoring %s because BitsPerSample=%d>24", fip ? fip->field_name : "unknown tagname", tif->tif_dir.td_bitspersample); continue; } countpersample=(1U<<tif->tif_dir.td_bitspersample); if ((dp->tdir_tag==TIFFTAG_TRANSFERFUNCTION)&&(dp->tdir_count==(uint64)countpersample)) { countrequired=countpersample; incrementpersample=0; } else { countrequired=3*countpersample; incrementpersample=countpersample; } if (dp->tdir_count!=(uint64)countrequired) err=TIFFReadDirEntryErrCount; else err=TIFFReadDirEntryShortArray(tif,dp,&value); if (err!=TIFFReadDirEntryErrOk) { fip = TIFFFieldWithTag(tif,dp->tdir_tag); TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",1); } else { TIFFSetField(tif,dp->tdir_tag,value,value+incrementpersample,value+2*incrementpersample); _TIFFfree(value); } } break; /* BEGIN REV 4.0 COMPATIBILITY */ case TIFFTAG_OSUBFILETYPE: { uint16 valueo; uint32 value; if (TIFFReadDirEntryShort(tif,dp,&valueo)==TIFFReadDirEntryErrOk) { switch (valueo) { case OFILETYPE_REDUCEDIMAGE: value=FILETYPE_REDUCEDIMAGE; break; case OFILETYPE_PAGE: value=FILETYPE_PAGE; break; default: value=0; break; } if (value!=0) TIFFSetField(tif,TIFFTAG_SUBFILETYPE,value); } } break; /* END REV 4.0 COMPATIBILITY */ default: (void) TIFFFetchNormalTag(tif, dp, TRUE); break; } } /* * OJPEG hack: * - If a) compression is OJPEG, and b) photometric tag is missing, * then we consistently find that photometric should be YCbCr * - If a) compression is OJPEG, and b) photometric tag says it's RGB, * then we consistently find that the buggy implementation of the * buggy compression scheme matches photometric YCbCr instead. * - If a) compression is OJPEG, and b) bitspersample tag is missing, * then we consistently find bitspersample should be 8. * - If a) compression is OJPEG, b) samplesperpixel tag is missing, * and c) photometric is RGB or YCbCr, then we consistently find * samplesperpixel should be 3 * - If a) compression is OJPEG, b) samplesperpixel tag is missing, * and c) photometric is MINISWHITE or MINISBLACK, then we consistently * find samplesperpixel should be 3 */ if (tif->tif_dir.td_compression==COMPRESSION_OJPEG) { if (!TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) { TIFFWarningExt(tif->tif_clientdata, module, "Photometric tag is missing, assuming data is YCbCr"); if (!TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,PHOTOMETRIC_YCBCR)) goto bad; } else if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB) { tif->tif_dir.td_photometric=PHOTOMETRIC_YCBCR; TIFFWarningExt(tif->tif_clientdata, module, "Photometric tag value assumed incorrect, " "assuming data is YCbCr instead of RGB"); } if (!TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) { TIFFWarningExt(tif->tif_clientdata,module, "BitsPerSample tag is missing, assuming 8 bits per sample"); if (!TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,8)) goto bad; } if (!TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) { if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB) { TIFFWarningExt(tif->tif_clientdata,module, "SamplesPerPixel tag is missing, " "assuming correct SamplesPerPixel value is 3"); if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3)) goto bad; } if (tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR) { TIFFWarningExt(tif->tif_clientdata,module, "SamplesPerPixel tag is missing, " "applying correct SamplesPerPixel value of 3"); if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3)) goto bad; } else if ((tif->tif_dir.td_photometric==PHOTOMETRIC_MINISWHITE) || (tif->tif_dir.td_photometric==PHOTOMETRIC_MINISBLACK)) { /* * SamplesPerPixel tag is missing, but is not required * by spec. Assume correct SamplesPerPixel value of 1. */ if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,1)) goto bad; } } } /* * Verify Palette image has a Colormap. */ if (tif->tif_dir.td_photometric == PHOTOMETRIC_PALETTE && !TIFFFieldSet(tif, FIELD_COLORMAP)) { if ( tif->tif_dir.td_bitspersample>=8 && tif->tif_dir.td_samplesperpixel==3) tif->tif_dir.td_photometric = PHOTOMETRIC_RGB; else if (tif->tif_dir.td_bitspersample>=8) tif->tif_dir.td_photometric = PHOTOMETRIC_MINISBLACK; else { MissingRequired(tif, "Colormap"); goto bad; } } /* * OJPEG hack: * We do no further messing with strip/tile offsets/bytecounts in OJPEG * TIFFs */ if (tif->tif_dir.td_compression!=COMPRESSION_OJPEG) { /* * Attempt to deal with a missing StripByteCounts tag. */ if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { /* * Some manufacturers violate the spec by not giving * the size of the strips. In this case, assume there * is one uncompressed strip of data. */ if ((tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG && tif->tif_dir.td_nstrips > 1) || (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE && tif->tif_dir.td_nstrips != (uint32)tif->tif_dir.td_samplesperpixel)) { MissingRequired(tif, "StripByteCounts"); goto bad; } TIFFWarningExt(tif->tif_clientdata, module, "TIFF directory is missing required " "\"StripByteCounts\" field, calculating from imagelength"); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; /* * Assume we have wrong StripByteCount value (in case * of single strip) in following cases: * - it is equal to zero along with StripOffset; * - it is larger than file itself (in case of uncompressed * image); * - it is smaller than the size of the bytes per row * multiplied on the number of rows. The last case should * not be checked in the case of writing new image, * because we may do not know the exact strip size * until the whole image will be written and directory * dumped out. */ #define BYTECOUNTLOOKSBAD \ ( (tif->tif_dir.td_stripbytecount[0] == 0 && tif->tif_dir.td_stripoffset[0] != 0) || \ (tif->tif_dir.td_compression == COMPRESSION_NONE && \ tif->tif_dir.td_stripbytecount[0] > TIFFGetFileSize(tif) - tif->tif_dir.td_stripoffset[0]) || \ (tif->tif_mode == O_RDONLY && \ tif->tif_dir.td_compression == COMPRESSION_NONE && \ tif->tif_dir.td_stripbytecount[0] < TIFFScanlineSize64(tif) * tif->tif_dir.td_imagelength) ) } else if (tif->tif_dir.td_nstrips == 1 && _TIFFFillStriles(tif) && tif->tif_dir.td_stripoffset[0] != 0 && BYTECOUNTLOOKSBAD) { /* * XXX: Plexus (and others) sometimes give a value of * zero for a tag when they don't know what the * correct value is! Try and handle the simple case * of estimating the size of a one strip image. */ TIFFWarningExt(tif->tif_clientdata, module, "Bogus \"StripByteCounts\" field, ignoring and calculating from imagelength"); if(EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; #if !defined(DEFER_STRILE_LOAD) } else if (tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG && tif->tif_dir.td_nstrips > 2 && tif->tif_dir.td_compression == COMPRESSION_NONE && tif->tif_dir.td_stripbytecount[0] != tif->tif_dir.td_stripbytecount[1] && tif->tif_dir.td_stripbytecount[0] != 0 && tif->tif_dir.td_stripbytecount[1] != 0 ) { /* * XXX: Some vendors fill StripByteCount array with * absolutely wrong values (it can be equal to * StripOffset array, for example). Catch this case * here. * * We avoid this check if deferring strile loading * as it would always force us to load the strip/tile * information. */ TIFFWarningExt(tif->tif_clientdata, module, "Wrong \"StripByteCounts\" field, ignoring and calculating from imagelength"); if (EstimateStripByteCounts(tif, dir, dircount) < 0) goto bad; #endif /* !defined(DEFER_STRILE_LOAD) */ } } if (dir) { _TIFFfree(dir); dir=NULL; } if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) { if (tif->tif_dir.td_bitspersample>=16) tif->tif_dir.td_maxsamplevalue=0xFFFF; else tif->tif_dir.td_maxsamplevalue = (uint16)((1L<<tif->tif_dir.td_bitspersample)-1); } /* * XXX: We can optimize checking for the strip bounds using the sorted * bytecounts array. See also comments for TIFFAppendToStrip() * function in tif_write.c. */ #if !defined(DEFER_STRILE_LOAD) if (tif->tif_dir.td_nstrips > 1) { uint32 strip; tif->tif_dir.td_stripbytecountsorted = 1; for (strip = 1; strip < tif->tif_dir.td_nstrips; strip++) { if (tif->tif_dir.td_stripoffset[strip - 1] > tif->tif_dir.td_stripoffset[strip]) { tif->tif_dir.td_stripbytecountsorted = 0; break; } } } #endif /* !defined(DEFER_STRILE_LOAD) */ /* * An opportunity for compression mode dependent tag fixup */ (*tif->tif_fixuptags)(tif); /* * Some manufacturers make life difficult by writing * large amounts of uncompressed data as a single strip. * This is contrary to the recommendations of the spec. * The following makes an attempt at breaking such images * into strips closer to the recommended 8k bytes. A * side effect, however, is that the RowsPerStrip tag * value may be changed. */ if ((tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&& (tif->tif_dir.td_nstrips==1)&& (tif->tif_dir.td_compression==COMPRESSION_NONE)&& ((tif->tif_flags&(TIFF_STRIPCHOP|TIFF_ISTILED))==TIFF_STRIPCHOP)) { if ( !_TIFFFillStriles(tif) || !tif->tif_dir.td_stripbytecount ) return 0; ChopUpSingleUncompressedStrip(tif); } /* * Clear the dirty directory flag. */ tif->tif_flags &= ~TIFF_DIRTYDIRECT; tif->tif_flags &= ~TIFF_DIRTYSTRIP; /* * Reinitialize i/o since we are starting on a new directory. */ tif->tif_row = (uint32) -1; tif->tif_curstrip = (uint32) -1; tif->tif_col = (uint32) -1; tif->tif_curtile = (uint32) -1; tif->tif_tilesize = (tmsize_t) -1; tif->tif_scanlinesize = TIFFScanlineSize(tif); if (!tif->tif_scanlinesize) { TIFFErrorExt(tif->tif_clientdata, module, "Cannot handle zero scanline size"); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (!tif->tif_tilesize) { TIFFErrorExt(tif->tif_clientdata, module, "Cannot handle zero tile size"); return (0); } } else { if (!TIFFStripSize(tif)) { TIFFErrorExt(tif->tif_clientdata, module, "Cannot handle zero strip size"); return (0); } } return (1); bad: if (dir) _TIFFfree(dir); return (0); } static void TIFFReadDirectoryCheckOrder(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { static const char module[] = "TIFFReadDirectoryCheckOrder"; uint16 m; uint16 n; TIFFDirEntry* o; m=0; for (n=0, o=dir; n<dircount; n++, o++) { if (o->tdir_tag<m) { TIFFWarningExt(tif->tif_clientdata,module, "Invalid TIFF directory; tags are not sorted in ascending order"); break; } m=o->tdir_tag+1; } } static TIFFDirEntry* TIFFReadDirectoryFindEntry(TIFF* tif, TIFFDirEntry* dir, uint16 dircount, uint16 tagid) { TIFFDirEntry* m; uint16 n; (void) tif; for (m=dir, n=0; n<dircount; m++, n++) { if (m->tdir_tag==tagid) return(m); } return(0); } static void TIFFReadDirectoryFindFieldInfo(TIFF* tif, uint16 tagid, uint32* fii) { int32 ma,mb,mc; ma=-1; mc=(int32)tif->tif_nfields; while (1) { if (ma+1==mc) { *fii = FAILED_FII; return; } mb=(ma+mc)/2; if (tif->tif_fields[mb]->field_tag==(uint32)tagid) break; if (tif->tif_fields[mb]->field_tag<(uint32)tagid) ma=mb; else mc=mb; } while (1) { if (mb==0) break; if (tif->tif_fields[mb-1]->field_tag!=(uint32)tagid) break; mb--; } *fii=mb; } /* * Read custom directory from the arbitrary offset. * The code is very similar to TIFFReadDirectory(). */ int TIFFReadCustomDirectory(TIFF* tif, toff_t diroff, const TIFFFieldArray* infoarray) { static const char module[] = "TIFFReadCustomDirectory"; TIFFDirEntry* dir; uint16 dircount; TIFFDirEntry* dp; uint16 di; const TIFFField* fip; uint32 fii; _TIFFSetupFields(tif, infoarray); dircount=TIFFFetchDirectory(tif,diroff,&dir,NULL); if (!dircount) { TIFFErrorExt(tif->tif_clientdata,module, "Failed to read custom directory at offset " TIFF_UINT64_FORMAT,diroff); return 0; } TIFFFreeDirectory(tif); _TIFFmemset(&tif->tif_dir, 0, sizeof(TIFFDirectory)); TIFFReadDirectoryCheckOrder(tif,dir,dircount); for (di=0, dp=dir; di<dircount; di++, dp++) { TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); if (fii == FAILED_FII) { TIFFWarningExt(tif->tif_clientdata, module, "Unknown field with tag %d (0x%x) encountered", dp->tdir_tag, dp->tdir_tag); if (!_TIFFMergeFields(tif, _TIFFCreateAnonField(tif, dp->tdir_tag, (TIFFDataType) dp->tdir_type), 1)) { TIFFWarningExt(tif->tif_clientdata, module, "Registering anonymous field with tag %d (0x%x) failed", dp->tdir_tag, dp->tdir_tag); dp->tdir_tag=IGNORE; } else { TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); assert( fii != FAILED_FII ); } } if (dp->tdir_tag!=IGNORE) { fip=tif->tif_fields[fii]; if (fip->field_bit==FIELD_IGNORE) dp->tdir_tag=IGNORE; else { /* check data type */ while ((fip->field_type!=TIFF_ANY)&&(fip->field_type!=dp->tdir_type)) { fii++; if ((fii==tif->tif_nfields)|| (tif->tif_fields[fii]->field_tag!=(uint32)dp->tdir_tag)) { fii=0xFFFF; break; } fip=tif->tif_fields[fii]; } if (fii==0xFFFF) { TIFFWarningExt(tif->tif_clientdata, module, "Wrong data type %d for \"%s\"; tag ignored", dp->tdir_type,fip->field_name); dp->tdir_tag=IGNORE; } else { /* check count if known in advance */ if ((fip->field_readcount!=TIFF_VARIABLE)&& (fip->field_readcount!=TIFF_VARIABLE2)) { uint32 expected; if (fip->field_readcount==TIFF_SPP) expected=(uint32)tif->tif_dir.td_samplesperpixel; else expected=(uint32)fip->field_readcount; if (!CheckDirCount(tif,dp,expected)) dp->tdir_tag=IGNORE; } } } switch (dp->tdir_tag) { case IGNORE: break; case EXIFTAG_SUBJECTDISTANCE: (void) TIFFFetchSubjectDistance(tif,dp); break; default: (void) TIFFFetchNormalTag(tif, dp, TRUE); break; } } } if (dir) _TIFFfree(dir); return 1; } /* * EXIF is important special case of custom IFD, so we have a special * function to read it. */ int TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff) { const TIFFFieldArray* exifFieldArray; exifFieldArray = _TIFFGetExifFields(); return TIFFReadCustomDirectory(tif, diroff, exifFieldArray); } static int EstimateStripByteCounts(TIFF* tif, TIFFDirEntry* dir, uint16 dircount) { static const char module[] = "EstimateStripByteCounts"; TIFFDirEntry *dp; TIFFDirectory *td = &tif->tif_dir; uint32 strip; /* Do not try to load stripbytecount as we will compute it */ if( !_TIFFFillStrilesInternal( tif, 0 ) ) return -1; if (td->td_stripbytecount) _TIFFfree(td->td_stripbytecount); td->td_stripbytecount = (uint64*) _TIFFCheckMalloc(tif, td->td_nstrips, sizeof (uint64), "for \"StripByteCounts\" array"); if( td->td_stripbytecount == NULL ) return -1; if (td->td_compression != COMPRESSION_NONE) { uint64 space; uint64 filesize; uint16 n; filesize = TIFFGetFileSize(tif); if (!(tif->tif_flags&TIFF_BIGTIFF)) space=sizeof(TIFFHeaderClassic)+2+dircount*12+4; else space=sizeof(TIFFHeaderBig)+8+dircount*20+8; /* calculate amount of space used by indirect values */ for (dp = dir, n = dircount; n > 0; n--, dp++) { uint32 typewidth; uint64 datasize; typewidth = TIFFDataWidth((TIFFDataType) dp->tdir_type); if (typewidth == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Cannot determine size of unknown tag type %d", dp->tdir_type); return -1; } datasize=(uint64)typewidth*dp->tdir_count; if (!(tif->tif_flags&TIFF_BIGTIFF)) { if (datasize<=4) datasize=0; } else { if (datasize<=8) datasize=0; } space+=datasize; } space = filesize - space; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) space /= td->td_samplesperpixel; for (strip = 0; strip < td->td_nstrips; strip++) td->td_stripbytecount[strip] = space; /* * This gross hack handles the case were the offset to * the last strip is past the place where we think the strip * should begin. Since a strip of data must be contiguous, * it's safe to assume that we've overestimated the amount * of data in the strip and trim this number back accordingly. */ strip--; if (td->td_stripoffset[strip]+td->td_stripbytecount[strip] > filesize) td->td_stripbytecount[strip] = filesize - td->td_stripoffset[strip]; } else if (isTiled(tif)) { uint64 bytespertile = TIFFTileSize64(tif); for (strip = 0; strip < td->td_nstrips; strip++) td->td_stripbytecount[strip] = bytespertile; } else { uint64 rowbytes = TIFFScanlineSize64(tif); uint32 rowsperstrip = td->td_imagelength/td->td_stripsperimage; for (strip = 0; strip < td->td_nstrips; strip++) td->td_stripbytecount[strip] = rowbytes * rowsperstrip; } TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP)) td->td_rowsperstrip = td->td_imagelength; return 1; } static void MissingRequired(TIFF* tif, const char* tagname) { static const char module[] = "MissingRequired"; TIFFErrorExt(tif->tif_clientdata, module, "TIFF directory is missing required \"%s\" field", tagname); } /* * Check the directory offset against the list of already seen directory * offsets. This is a trick to prevent IFD looping. The one can create TIFF * file with looped directory pointers. We will maintain a list of already * seen directories and check every IFD offset against that list. */ static int TIFFCheckDirOffset(TIFF* tif, uint64 diroff) { uint16 n; if (diroff == 0) /* no more directories */ return 0; if (tif->tif_dirnumber == 65535) { TIFFErrorExt(tif->tif_clientdata, "TIFFCheckDirOffset", "Cannot handle more than 65535 TIFF directories"); return 0; } for (n = 0; n < tif->tif_dirnumber && tif->tif_dirlist; n++) { if (tif->tif_dirlist[n] == diroff) return 0; } tif->tif_dirnumber++; if (tif->tif_dirlist == NULL || tif->tif_dirnumber > tif->tif_dirlistsize) { uint64* new_dirlist; /* * XXX: Reduce memory allocation granularity of the dirlist * array. */ new_dirlist = (uint64*)_TIFFCheckRealloc(tif, tif->tif_dirlist, tif->tif_dirnumber, 2 * sizeof(uint64), "for IFD list"); if (!new_dirlist) return 0; if( tif->tif_dirnumber >= 32768 ) tif->tif_dirlistsize = 65535; else tif->tif_dirlistsize = 2 * tif->tif_dirnumber; tif->tif_dirlist = new_dirlist; } tif->tif_dirlist[tif->tif_dirnumber - 1] = diroff; return 1; } /* * Check the count field of a directory entry against a known value. The * caller is expected to skip/ignore the tag if there is a mismatch. */ static int CheckDirCount(TIFF* tif, TIFFDirEntry* dir, uint32 count) { if ((uint64)count > dir->tdir_count) { const TIFFField* fip = TIFFFieldWithTag(tif, dir->tdir_tag); TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "incorrect count for field \"%s\" (" TIFF_UINT64_FORMAT ", expecting %u); tag ignored", fip ? fip->field_name : "unknown tagname", dir->tdir_count, count); return (0); } else if ((uint64)count < dir->tdir_count) { const TIFFField* fip = TIFFFieldWithTag(tif, dir->tdir_tag); TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "incorrect count for field \"%s\" (" TIFF_UINT64_FORMAT ", expecting %u); tag trimmed", fip ? fip->field_name : "unknown tagname", dir->tdir_count, count); dir->tdir_count = count; return (1); } return (1); } /* * Read IFD structure from the specified offset. If the pointer to * nextdiroff variable has been specified, read it too. Function returns a * number of fields in the directory or 0 if failed. */ static uint16 TIFFFetchDirectory(TIFF* tif, uint64 diroff, TIFFDirEntry** pdir, uint64 *nextdiroff) { static const char module[] = "TIFFFetchDirectory"; void* origdir; uint16 dircount16; uint32 dirsize; TIFFDirEntry* dir; uint8* ma; TIFFDirEntry* mb; uint16 n; assert(pdir); tif->tif_diroff = diroff; if (nextdiroff) *nextdiroff = 0; if (!isMapped(tif)) { if (!SeekOK(tif, tif->tif_diroff)) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Seek error accessing TIFF directory", tif->tif_name); return 0; } if (!(tif->tif_flags&TIFF_BIGTIFF)) { if (!ReadOK(tif, &dircount16, sizeof (uint16))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return 0; } if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount16); if (dircount16>4096) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on directory count failed, this is probably not a valid IFD offset"); return 0; } dirsize = 12; } else { uint64 dircount64; if (!ReadOK(tif, &dircount64, sizeof (uint64))) { TIFFErrorExt(tif->tif_clientdata, module, "%s: Can not read TIFF directory count", tif->tif_name); return 0; } if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&dircount64); if (dircount64>4096) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on directory count failed, this is probably not a valid IFD offset"); return 0; } dircount16 = (uint16)dircount64; dirsize = 20; } origdir = _TIFFCheckMalloc(tif, dircount16, dirsize, "to read TIFF directory"); if (origdir == NULL) return 0; if (!ReadOK(tif, origdir, (tmsize_t)(dircount16*dirsize))) { TIFFErrorExt(tif->tif_clientdata, module, "%.100s: Can not read TIFF directory", tif->tif_name); _TIFFfree(origdir); return 0; } /* * Read offset to next directory for sequential scans if * needed. */ if (nextdiroff) { if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 nextdiroff32; if (!ReadOK(tif, &nextdiroff32, sizeof(uint32))) nextdiroff32 = 0; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&nextdiroff32); *nextdiroff=nextdiroff32; } else { if (!ReadOK(tif, nextdiroff, sizeof(uint64))) *nextdiroff = 0; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(nextdiroff); } } } else { tmsize_t m; tmsize_t off = (tmsize_t) tif->tif_diroff; if ((uint64)off!=tif->tif_diroff) { TIFFErrorExt(tif->tif_clientdata,module,"Can not read TIFF directory count"); return(0); } /* * Check for integer overflow when validating the dir_off, * otherwise a very high offset may cause an OOB read and * crash the client. Make two comparisons instead of * * off + sizeof(uint16) > tif->tif_size * * to avoid overflow. */ if (!(tif->tif_flags&TIFF_BIGTIFF)) { m=off+sizeof(uint16); if ((m<off)||(m<(tmsize_t)sizeof(uint16))||(m>tif->tif_size)) { TIFFErrorExt(tif->tif_clientdata, module, "Can not read TIFF directory count"); return 0; } else { _TIFFmemcpy(&dircount16, tif->tif_base + off, sizeof(uint16)); } off += sizeof (uint16); if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount16); if (dircount16>4096) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on directory count failed, this is probably not a valid IFD offset"); return 0; } dirsize = 12; } else { uint64 dircount64; m=off+sizeof(uint64); if ((m<off)||(m<(tmsize_t)sizeof(uint64))||(m>tif->tif_size)) { TIFFErrorExt(tif->tif_clientdata, module, "Can not read TIFF directory count"); return 0; } else { _TIFFmemcpy(&dircount64, tif->tif_base + off, sizeof(uint64)); } off += sizeof (uint64); if (tif->tif_flags & TIFF_SWAB) TIFFSwabLong8(&dircount64); if (dircount64>4096) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on directory count failed, this is probably not a valid IFD offset"); return 0; } dircount16 = (uint16)dircount64; dirsize = 20; } if (dircount16 == 0 ) { TIFFErrorExt(tif->tif_clientdata, module, "Sanity check on directory count failed, zero tag directories not supported"); return 0; } origdir = _TIFFCheckMalloc(tif, dircount16, dirsize, "to read TIFF directory"); if (origdir == NULL) return 0; m=off+dircount16*dirsize; if ((m<off)||(m<(tmsize_t)(dircount16*dirsize))||(m>tif->tif_size)) { TIFFErrorExt(tif->tif_clientdata, module, "Can not read TIFF directory"); _TIFFfree(origdir); return 0; } else { _TIFFmemcpy(origdir, tif->tif_base + off, dircount16 * dirsize); } if (nextdiroff) { off += dircount16 * dirsize; if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 nextdiroff32; m=off+sizeof(uint32); if ((m<off)||(m<(tmsize_t)sizeof(uint32))||(m>tif->tif_size)) nextdiroff32 = 0; else _TIFFmemcpy(&nextdiroff32, tif->tif_base + off, sizeof (uint32)); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&nextdiroff32); *nextdiroff = nextdiroff32; } else { m=off+sizeof(uint64); if ((m<off)||(m<(tmsize_t)sizeof(uint64))||(m>tif->tif_size)) *nextdiroff = 0; else _TIFFmemcpy(nextdiroff, tif->tif_base + off, sizeof (uint64)); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(nextdiroff); } } } dir = (TIFFDirEntry*)_TIFFCheckMalloc(tif, dircount16, sizeof(TIFFDirEntry), "to read TIFF directory"); if (dir==0) { _TIFFfree(origdir); return 0; } ma=(uint8*)origdir; mb=dir; for (n=0; n<dircount16; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); mb->tdir_tag=*(uint16*)ma; ma+=sizeof(uint16); if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); mb->tdir_type=*(uint16*)ma; ma+=sizeof(uint16); if (!(tif->tif_flags&TIFF_BIGTIFF)) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); mb->tdir_count=(uint64)(*(uint32*)ma); ma+=sizeof(uint32); *(uint32*)(&mb->tdir_offset)=*(uint32*)ma; ma+=sizeof(uint32); } else { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); mb->tdir_count=TIFFReadUInt64(ma); ma+=sizeof(uint64); mb->tdir_offset.toff_long8=TIFFReadUInt64(ma); ma+=sizeof(uint64); } mb++; } _TIFFfree(origdir); *pdir = dir; return dircount16; } /* * Fetch a tag that is not handled by special case code. */ static int TIFFFetchNormalTag(TIFF* tif, TIFFDirEntry* dp, int recover) { static const char module[] = "TIFFFetchNormalTag"; enum TIFFReadDirEntryErr err; uint32 fii; const TIFFField* fip = NULL; TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); if( fii == FAILED_FII ) { TIFFErrorExt(tif->tif_clientdata, "TIFFFetchNormalTag", "No definition found for tag %d", dp->tdir_tag); return 0; } fip=tif->tif_fields[fii]; assert(fip != NULL); /* should not happen */ assert(fip->set_field_type!=TIFF_SETGET_OTHER); /* if so, we shouldn't arrive here but deal with this in specialized code */ assert(fip->set_field_type!=TIFF_SETGET_INT); /* if so, we shouldn't arrive here as this is only the case for pseudo-tags */ err=TIFFReadDirEntryErrOk; switch (fip->set_field_type) { case TIFF_SETGET_UNDEFINED: break; case TIFF_SETGET_ASCII: { uint8* data; assert(fip->field_passcount==0); err=TIFFReadDirEntryByteArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { uint8* ma; uint32 mb; int n; ma=data; mb=0; while (mb<(uint32)dp->tdir_count) { if (*ma==0) break; ma++; mb++; } if (mb+1<(uint32)dp->tdir_count) TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" contains null byte in value; value incorrectly truncated during reading due to implementation limitations",fip->field_name); else if (mb+1>(uint32)dp->tdir_count) { uint8* o; TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte",fip->field_name); if ((uint32)dp->tdir_count+1!=dp->tdir_count+1) o=NULL; else o=_TIFFmalloc((uint32)dp->tdir_count+1); if (o==NULL) { if (data!=NULL) _TIFFfree(data); return(0); } _TIFFmemcpy(o,data,(uint32)dp->tdir_count); o[(uint32)dp->tdir_count]=0; if (data!=0) _TIFFfree(data); data=o; } n=TIFFSetField(tif,dp->tdir_tag,data); if (data!=0) _TIFFfree(data); if (!n) return(0); } } break; case TIFF_SETGET_UINT8: { uint8 data=0; assert(fip->field_readcount==1); assert(fip->field_passcount==0); err=TIFFReadDirEntryByte(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { if (!TIFFSetField(tif,dp->tdir_tag,data)) return(0); } } break; case TIFF_SETGET_UINT16: { uint16 data; assert(fip->field_readcount==1); assert(fip->field_passcount==0); err=TIFFReadDirEntryShort(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { if (!TIFFSetField(tif,dp->tdir_tag,data)) return(0); } } break; case TIFF_SETGET_UINT32: { uint32 data; assert(fip->field_readcount==1); assert(fip->field_passcount==0); err=TIFFReadDirEntryLong(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { if (!TIFFSetField(tif,dp->tdir_tag,data)) return(0); } } break; case TIFF_SETGET_UINT64: { uint64 data; assert(fip->field_readcount==1); assert(fip->field_passcount==0); err=TIFFReadDirEntryLong8(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { if (!TIFFSetField(tif,dp->tdir_tag,data)) return(0); } } break; case TIFF_SETGET_FLOAT: { float data; assert(fip->field_readcount==1); assert(fip->field_passcount==0); err=TIFFReadDirEntryFloat(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { if (!TIFFSetField(tif,dp->tdir_tag,data)) return(0); } } break; case TIFF_SETGET_DOUBLE: { double data; assert(fip->field_readcount==1); assert(fip->field_passcount==0); err=TIFFReadDirEntryDouble(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { if (!TIFFSetField(tif,dp->tdir_tag,data)) return(0); } } break; case TIFF_SETGET_IFD8: { uint64 data; assert(fip->field_readcount==1); assert(fip->field_passcount==0); err=TIFFReadDirEntryIfd8(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { if (!TIFFSetField(tif,dp->tdir_tag,data)) return(0); } } break; case TIFF_SETGET_UINT16_PAIR: { uint16* data; assert(fip->field_readcount==2); assert(fip->field_passcount==0); if (dp->tdir_count!=2) { TIFFWarningExt(tif->tif_clientdata,module, "incorrect count for field \"%s\", expected 2, got %d", fip->field_name,(int)dp->tdir_count); return(0); } err=TIFFReadDirEntryShortArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,data[0],data[1]); _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C0_UINT8: { uint8* data; assert(fip->field_readcount>=1); assert(fip->field_passcount==0); if (dp->tdir_count!=(uint64)fip->field_readcount) { TIFFWarningExt(tif->tif_clientdata,module, "incorrect count for field \"%s\", expected %d, got %d", fip->field_name,(int) fip->field_readcount, (int)dp->tdir_count); return 0; } else { err=TIFFReadDirEntryByteArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C0_UINT16: { uint16* data; assert(fip->field_readcount>=1); assert(fip->field_passcount==0); if (dp->tdir_count!=(uint64)fip->field_readcount) /* corrupt file */; else { err=TIFFReadDirEntryShortArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C0_UINT32: { uint32* data; assert(fip->field_readcount>=1); assert(fip->field_passcount==0); if (dp->tdir_count!=(uint64)fip->field_readcount) /* corrupt file */; else { err=TIFFReadDirEntryLongArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C0_FLOAT: { float* data; assert(fip->field_readcount>=1); assert(fip->field_passcount==0); if (dp->tdir_count!=(uint64)fip->field_readcount) /* corrupt file */; else { err=TIFFReadDirEntryFloatArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_ASCII: { uint8* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryByteArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; if( dp->tdir_count > 0 && data[dp->tdir_count-1] != '\0' ) { TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte. Forcing it to be null",fip->field_name); data[dp->tdir_count-1] = '\0'; } m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_UINT8: { uint8* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryByteArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_UINT16: { uint16* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryShortArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_UINT32: { uint32* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryLongArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_UINT64: { uint64* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryLong8Array(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_FLOAT: { float* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryFloatArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_DOUBLE: { double* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryDoubleArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C16_IFD8: { uint64* data; assert(fip->field_readcount==TIFF_VARIABLE); assert(fip->field_passcount==1); if (dp->tdir_count>0xFFFF) err=TIFFReadDirEntryErrCount; else { err=TIFFReadDirEntryIfd8Array(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint16)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } } break; case TIFF_SETGET_C32_ASCII: { uint8* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryByteArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; if( dp->tdir_count > 0 && data[dp->tdir_count-1] != '\0' ) { TIFFWarningExt(tif->tif_clientdata,module,"ASCII value for tag \"%s\" does not end in null byte. Forcing it to be null",fip->field_name); data[dp->tdir_count-1] = '\0'; } m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_UINT8: { uint8* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryByteArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_SINT8: { int8* data = NULL; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntrySbyteArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_UINT16: { uint16* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryShortArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_SINT16: { int16* data = NULL; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntrySshortArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_UINT32: { uint32* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryLongArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_SINT32: { int32* data = NULL; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntrySlongArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_UINT64: { uint64* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryLong8Array(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_SINT64: { int64* data = NULL; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntrySlong8Array(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_FLOAT: { float* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryFloatArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_DOUBLE: { double* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryDoubleArray(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; case TIFF_SETGET_C32_IFD8: { uint64* data; assert(fip->field_readcount==TIFF_VARIABLE2); assert(fip->field_passcount==1); err=TIFFReadDirEntryIfd8Array(tif,dp,&data); if (err==TIFFReadDirEntryErrOk) { int m; m=TIFFSetField(tif,dp->tdir_tag,(uint32)(dp->tdir_count),data); if (data!=0) _TIFFfree(data); if (!m) return(0); } } break; default: assert(0); /* we should never get here */ break; } if (err!=TIFFReadDirEntryErrOk) { TIFFReadDirEntryOutputErr(tif,err,module,fip->field_name,recover); return(0); } return(1); } /* * Fetch a set of offsets or lengths. * While this routine says "strips", in fact it's also used for tiles. */ static int TIFFFetchStripThing(TIFF* tif, TIFFDirEntry* dir, uint32 nstrips, uint64** lpp) { static const char module[] = "TIFFFetchStripThing"; enum TIFFReadDirEntryErr err; uint64* data; err=TIFFReadDirEntryLong8Array(tif,dir,&data); if (err!=TIFFReadDirEntryErrOk) { const TIFFField* fip = TIFFFieldWithTag(tif,dir->tdir_tag); TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",0); return(0); } if (dir->tdir_count!=(uint64)nstrips) { uint64* resizeddata; resizeddata=(uint64*)_TIFFCheckMalloc(tif,nstrips,sizeof(uint64),"for strip array"); if (resizeddata==0) { _TIFFfree(data); return(0); } if (dir->tdir_count<(uint64)nstrips) { _TIFFmemcpy(resizeddata,data,(uint32)dir->tdir_count*sizeof(uint64)); _TIFFmemset(resizeddata+(uint32)dir->tdir_count,0,(nstrips-(uint32)dir->tdir_count)*sizeof(uint64)); } else _TIFFmemcpy(resizeddata,data,nstrips*sizeof(uint64)); _TIFFfree(data); data=resizeddata; } *lpp=data; return(1); } /* * Fetch and set the SubjectDistance EXIF tag. */ static int TIFFFetchSubjectDistance(TIFF* tif, TIFFDirEntry* dir) { static const char module[] = "TIFFFetchSubjectDistance"; enum TIFFReadDirEntryErr err; UInt64Aligned_t m; m.l=0; assert(sizeof(double)==8); assert(sizeof(uint64)==8); assert(sizeof(uint32)==4); if (dir->tdir_count!=1) err=TIFFReadDirEntryErrCount; else if (dir->tdir_type!=TIFF_RATIONAL) err=TIFFReadDirEntryErrType; else { if (!(tif->tif_flags&TIFF_BIGTIFF)) { uint32 offset; offset=*(uint32*)(&dir->tdir_offset); if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(&offset); err=TIFFReadDirEntryData(tif,offset,8,m.i); } else { m.l=dir->tdir_offset.toff_long8; err=TIFFReadDirEntryErrOk; } } if (err==TIFFReadDirEntryErrOk) { double n; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong(m.i,2); if (m.i[0]==0) n=0.0; else if (m.i[0]==0xFFFFFFFF) /* * XXX: Numerator 0xFFFFFFFF means that we have infinite * distance. Indicate that with a negative floating point * SubjectDistance value. */ n=-1.0; else n=(double)m.i[0]/(double)m.i[1]; return(TIFFSetField(tif,dir->tdir_tag,n)); } else { TIFFReadDirEntryOutputErr(tif,err,module,"SubjectDistance",TRUE); return(0); } } /* * Replace a single strip (tile) of uncompressed data by multiple strips * (tiles), each approximately STRIP_SIZE_DEFAULT bytes. This is useful for * dealing with large images or for dealing with machines with a limited * amount memory. */ static void ChopUpSingleUncompressedStrip(TIFF* tif) { register TIFFDirectory *td = &tif->tif_dir; uint64 bytecount; uint64 offset; uint32 rowblock; uint64 rowblockbytes; uint64 stripbytes; uint32 strip; uint64 nstrips64; uint32 nstrips32; uint32 rowsperstrip; uint64* newcounts; uint64* newoffsets; bytecount = td->td_stripbytecount[0]; offset = td->td_stripoffset[0]; assert(td->td_planarconfig == PLANARCONFIG_CONTIG); if ((td->td_photometric == PHOTOMETRIC_YCBCR)&& (!isUpSampled(tif))) rowblock = td->td_ycbcrsubsampling[1]; else rowblock = 1; rowblockbytes = TIFFVTileSize64(tif, rowblock); /* * Make the rows hold at least one scanline, but fill specified amount * of data if possible. */ if (rowblockbytes > STRIP_SIZE_DEFAULT) { stripbytes = rowblockbytes; rowsperstrip = rowblock; } else if (rowblockbytes > 0 ) { uint32 rowblocksperstrip; rowblocksperstrip = (uint32) (STRIP_SIZE_DEFAULT / rowblockbytes); rowsperstrip = rowblocksperstrip * rowblock; stripbytes = rowblocksperstrip * rowblockbytes; } else return; /* * never increase the number of strips in an image */ if (rowsperstrip >= td->td_rowsperstrip) return; nstrips64 = TIFFhowmany_64(bytecount, stripbytes); if ((nstrips64==0)||(nstrips64>0xFFFFFFFF)) /* something is wonky, do nothing. */ return; nstrips32 = (uint32)nstrips64; newcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64), "for chopped \"StripByteCounts\" array"); newoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64), "for chopped \"StripOffsets\" array"); if (newcounts == NULL || newoffsets == NULL) { /* * Unable to allocate new strip information, give up and use * the original one strip information. */ if (newcounts != NULL) _TIFFfree(newcounts); if (newoffsets != NULL) _TIFFfree(newoffsets); return; } /* * Fill the strip information arrays with new bytecounts and offsets * that reflect the broken-up format. */ for (strip = 0; strip < nstrips32; strip++) { if (stripbytes > bytecount) stripbytes = bytecount; newcounts[strip] = stripbytes; newoffsets[strip] = offset; offset += stripbytes; bytecount -= stripbytes; } /* * Replace old single strip info with multi-strip info. */ td->td_stripsperimage = td->td_nstrips = nstrips32; TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); _TIFFfree(td->td_stripbytecount); _TIFFfree(td->td_stripoffset); td->td_stripbytecount = newcounts; td->td_stripoffset = newoffsets; td->td_stripbytecountsorted = 1; } int _TIFFFillStriles( TIFF *tif ) { return _TIFFFillStrilesInternal( tif, 1 ); } static int _TIFFFillStrilesInternal( TIFF *tif, int loadStripByteCount ) { #if defined(DEFER_STRILE_LOAD) register TIFFDirectory *td = &tif->tif_dir; int return_value = 1; if( td->td_stripoffset != NULL ) return 1; if( td->td_stripoffset_entry.tdir_count == 0 ) return 0; if (!TIFFFetchStripThing(tif,&(td->td_stripoffset_entry), td->td_nstrips,&td->td_stripoffset)) { return_value = 0; } if (loadStripByteCount && !TIFFFetchStripThing(tif,&(td->td_stripbytecount_entry), td->td_nstrips,&td->td_stripbytecount)) { return_value = 0; } _TIFFmemset( &(td->td_stripoffset_entry), 0, sizeof(TIFFDirEntry)); _TIFFmemset( &(td->td_stripbytecount_entry), 0, sizeof(TIFFDirEntry)); if (tif->tif_dir.td_nstrips > 1 && return_value == 1 ) { uint32 strip; tif->tif_dir.td_stripbytecountsorted = 1; for (strip = 1; strip < tif->tif_dir.td_nstrips; strip++) { if (tif->tif_dir.td_stripoffset[strip - 1] > tif->tif_dir.td_stripoffset[strip]) { tif->tif_dir.td_stripbytecountsorted = 0; break; } } } return return_value; #else /* !defined(DEFER_STRILE_LOAD) */ (void) tif; (void) loadStripByteCount; return 1; #endif } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4857_1
crossvul-cpp_data_good_501_1
/* radare - LGPL - Copyright 2015-2018 - pancake */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <r_util.h> typedef enum optype_t { ARM_NOTYPE = -1, ARM_GPR = 1, ARM_CONSTANT = 2, ARM_FP = 4, ARM_MEM_OPT = 8 } OpType; typedef enum regtype_t { ARM_UNDEFINED = -1, ARM_REG64 = 1, ARM_REG32 = 2, ARM_SP = 4, ARM_PC = 8, ARM_SIMD = 16 } RegType; typedef enum shifttype_t { ARM_NO_SHIFT = -1, ARM_LSL = 0, ARM_LSR = 1, ARM_ASR = 2 } ShiftType; typedef struct operand_t { OpType type; union { struct { int reg; RegType reg_type; ut16 sp_val; }; struct { ut64 immediate; int sign; }; struct { ut64 shift_amount; ShiftType shift; }; struct { ut32 mem_option; }; }; } Operand; #define MAX_OPERANDS 7 typedef struct Opcode_t { char *mnemonic; ut32 op[3]; size_t op_len; ut8 opcode[3]; int operands_count; Operand operands[MAX_OPERANDS]; } ArmOp; static int get_mem_option(char *token) { // values 4, 8, 12, are unused. XXX to adjust const char *options[] = {"sy", "st", "ld", "xxx", "ish", "ishst", "ishld", "xxx", "nsh", "nshst", "nshld", "xxx", "osh", "oshst", "oshld", NULL}; int i = 0; while (options[i]) { if (!r_str_casecmp (token, options[i])) { return 15 - i; } i++; } return -1; } static int countLeadingZeros(ut32 x) { int count = 0; while (x) { x >>= 1; --count; } return count; } static int countTrailingZeros(ut32 x) { int count = 0; while (x > 0) { if ((x & 1) == 1) { break; } else { count ++; x = x >> 1; } } return count; } static int calcNegOffset(int n, int shift) { int a = n >> shift; if (a == 0) { return 0xff; } // find first set bit then invert it and all // bits below it int t = 0x400; while (!(t & a) && a != 0 && t != 0) { t = t >> 1; } t = t & (t - 1); a = a ^ t; // If bits below 32 are set if (countTrailingZeros(n) > shift) { a--; } return 0xff & (0xff - a); } static int countLeadingOnes(ut32 x) { return countLeadingZeros (~x); } static int countTrailingOnes(ut32 x) { return countTrailingZeros (~x); } static bool isMask(ut32 value) { return value && ((value + 1) & value) == 0; } static bool isShiftedMask (ut32 value) { return value && isMask ((value - 1) | value); } static ut32 decodeBitMasks(ut32 imm) { // get element size int size = 32; // determine rot to make element be 0^m 1^n ut32 cto, i; ut32 mask = ((ut64) - 1LL) >> (64 - size); if (isShiftedMask (imm)) { i = countTrailingZeros (imm); cto = countTrailingOnes (imm >> i); } else { imm |= ~mask; if (!isShiftedMask (imm)) { return UT32_MAX; } ut32 clo = countLeadingOnes (imm); i = 64 - clo; cto = clo + countTrailingOnes (imm) - (64 - size); } // Encode in Immr the number of RORs it would take to get *from* 0^m 1^n // to our target value, where I is the number of RORs to go the opposite // direction ut32 immr = (size - i) & (size - 1); // If size has a 1 in the n'th bit, create a value that has zeroes in // bits [0, n] and ones above that. ut64 nimms = ~(size - 1) << 1; // Or the cto value into the low bits, which must be below the Nth bit // bit mentioned above. nimms |= (cto - 1); // Extract and toggle seventh bit to make N field. ut32 n = ((nimms >> 6) & 1) ^ 1; ut64 encoding = (n << 12) | (immr << 6) | (nimms & 0x3f); return encoding; } static ut32 mov(ArmOp *op) { int k = 0; ut32 data = UT32_MAX; if (!strncmp (op->mnemonic, "movz", 4)) { if (op->operands[0].reg_type & ARM_REG64) { k = 0x80d2; } else if (op->operands[0].reg_type & ARM_REG32) { k = 0x8052; } } else if (!strncmp (op->mnemonic, "movk", 4)) { if (op->operands[0].reg_type & ARM_REG32) { k = 0x8072; } else if (op->operands[0].reg_type & ARM_REG64) { k = 0x80f2; } } else if (!strncmp (op->mnemonic, "movn", 4)) { if (op->operands[0].reg_type & ARM_REG32) { k = 0x8012; } else if (op->operands[0].reg_type & ARM_REG64) { k = 0x8092; } } else if (!strncmp (op->mnemonic, "mov", 3)) { //printf ("%d - %d [%d]\n", op->operands[0].type, op->operands[1].type, ARM_GPR); if (op->operands[0].type & ARM_GPR) { if (op->operands[1].type & ARM_GPR) { if (op->operands[1].reg_type & ARM_REG64) { k = 0xe00300aa; } else { k = 0xe003002a; } data = k | op->operands[1].reg << 8; } else if (op->operands[1].type & ARM_CONSTANT) { k = 0x80d2; data = k | op->operands[1].immediate << 29; } data |= op->operands[0].reg << 24; } return data; } data = k; data |= (op->operands[0].reg << 24); // arg(0) data |= ((op->operands[1].immediate & 7) << 29); // arg(1) data |= (((op->operands[1].immediate >> 3) & 0xff) << 16); // arg(1) data |= ((op->operands[1].immediate >> 10) << 7); // arg(1) return data; } static ut32 cmp(ArmOp *op) { ut32 data = UT32_MAX; int k = 0; if (op->operands[0].reg_type & ARM_REG64 && op->operands[1].reg_type & ARM_REG64) { k = 0x1f0000eb; } else if (op->operands[0].reg_type & ARM_REG32 && op->operands[1].reg_type & ARM_REG32) { if (op->operands[2].shift_amount > 31) { return UT32_MAX; } k = 0x1f00006b; } else { return UT32_MAX; } data = k | (op->operands[0].reg & 0x18) << 13 | op->operands[0].reg << 29 | op->operands[1].reg << 8; if (op->operands[2].shift != ARM_NO_SHIFT) { data |= op->operands[2].shift_amount << 18 | op->operands[2].shift << 14; } return data; } static ut32 regsluop(ArmOp *op, int k) { ut32 data = UT32_MAX; if (op->operands[1].reg_type & ARM_REG32) { return data; } if (op->operands[0].reg_type & ARM_REG32) { k -= 0x40; } if (op->operands[2].type & ARM_GPR) { return data; } int n = op->operands[2].immediate; if (n > 0xff || n < -0x100) { return data; } data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13; if (n < 0) { n *= -1; data |= ( 0xf & (0xf - (n - 1)) ) << 20; if (countTrailingZeros(n) > 3) { data |= (0x1f - ((n >> 4) - 1)) << 8; } else { data |= (0x1f - (n >> 4)) << 8; } } else { data |= (0xf & (n & 63)) << 20; if (countTrailingZeros(n) < 4) { data |= (n >> 4) << 8; } else { data |= (0xff & n) << 4; } data |= (n >> 8) << 8; } return data; } // Register Load/store ops static ut32 reglsop(ArmOp *op, int k) { ut32 data = UT32_MAX; if (op->operands[1].reg_type & ARM_REG32) { return data; } if (op->operands[0].reg_type & ARM_REG32) { k -= 0x40; } if (op->operands[2].type & ARM_GPR) { k += 0x00682000; data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13; data |= op->operands[2].reg << 8; } else { int n = op->operands[2].immediate; if (n > 0x100 || n < -0x100) { return UT32_MAX; } if (n == 0 || (n > 0 && countTrailingZeros(n) >= 4)) { k ++; } data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13; if (n < 0) { n *= -1; data |= ( 0xf & (0xf - (n - 1)) ) << 20; if (countTrailingZeros(n) > 3) { data |= (0x1f - ((n >> 4) - 1)) << 8; } else { data |= (0x1f - (n >> 4)) << 8; } } else { if (op->operands[0].reg_type & ARM_REG32) { if (countTrailingZeros(n) < 2) { data |= (0xf & (n & 63)) << 20; data |= (n >> 4) << 8; } else { data++; data |= (0xff & n) << 16; } data |= (n >> 8) << 8; } else { data |= (0xf & (n & 63)) << 20; if (countTrailingZeros(n) < 4) { data |= (n >> 4) << 8; } else { data |= (0xff & n) << 15; } data |= (n >> 8) << 23; } } } return data; } // Byte load/store ops static ut32 bytelsop(ArmOp *op, int k) { ut32 data = UT32_MAX; if (op->operands[0].reg_type & ARM_REG64) { return data; } if (op->operands[1].reg_type & ARM_REG32) { return data; } if (op->operands[2].type & ARM_GPR) { if ((k & 0xf) != 8) { k--; } k += 0x00682000; data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13; data |= op->operands[2].reg << 8; return data; } int n = op->operands[2].immediate; if (n > 0xfff || n < -0x100) { return UT32_MAX; } // Half ops int halfop = false; if ((k & 0xf) == 8) { halfop = true; if (n == 0 || (countTrailingZeros(n) && n > 0)) { k++; } } else { if (n < 0) { k--; } } data = k | op->operands[0].reg << 24 | op->operands[1].reg << 29 | (op->operands[1].reg & 56) << 13; int imm = n; int low_shift = 20; int high_shift = 8; int top_shift = 10; if (n < 0) { imm = 0xfff + (n + 1); } if (halfop) { if (imm & 0x1 || n < 0) { data |= (0xf & imm) << low_shift ; data |= (0x7 & (imm >> 4)) << high_shift; data |= (0x7 & (imm >> 6)) << top_shift; } else { data |= (0xf & imm) << (low_shift - 3); data |= (0x7 & (imm >> 4)) << (high_shift + 13); data |= (0x7 & (imm >> 7)) << (top_shift - 2); } } else { if (n < 0) { data |= (0xf & imm) << 20; data |= (0x1f & (imm >> 4)) << 8; } else { data |= (0xf & imm) << 18; data |= (0x3 & (imm >> 4)) << 22; data |= (0x7 & (imm >> 6)) << 8; } } return data; } static ut32 branch(ArmOp *op, ut64 addr, int k) { ut32 data = UT32_MAX; int n = 0; if (op->operands[0].type & ARM_CONSTANT) { n = op->operands[0].immediate; if (!(n & 0x3 || n > 0x7ffffff)) { n -= addr; n = n >> 2; int t = n >> 24; int h = n >> 16; int m = (n & 0xff00) >> 8; n &= 0xff; data = k; data |= n << 24; data |= m << 16; data |= h << 8; data |= t; } } else { n = op->operands[0].reg; if (n < 0 || n > 31) { return -1; } n = n << 5; int h = n >> 8; n &= 0xff; data = k; data |= n << 24; data |= h << 16; } return data; } static ut32 bdot(ArmOp *op, ut64 addr, int k) { ut32 data = UT32_MAX; int n = 0; int a = 0; n = op->operands[0].immediate; // I am sure there's a logical way to do negative offsets, // but I was unable to find any sensible docs so I did my best if (!(n & 0x3 || n > 0x7ffffff)) { n -= addr; data = k; if (n < 0) { n *= -1; a = (n << 3) - 1; data |= (0xff - a) << 24; a = calcNegOffset(n, 5); data |= a << 16; a = calcNegOffset(n, 13); data |= a << 8; } else { data |= (n & 31) << 27; data |= (0xff & (n >> 5)) << 16; data |= (0xff & (n >> 13)) << 8; } } return data; } static ut32 mem_barrier (ArmOp *op, ut64 addr, int k) { ut32 data = UT32_MAX; data = k; if (!strncmp (op->mnemonic, "isb", 3)) { if (op->operands[0].mem_option == 15 || op->operands[0].type == ARM_NOTYPE) { return data; } else { return UT32_MAX; } } if (op->operands[0].type == ARM_MEM_OPT) { data |= op->operands[0].mem_option << 16; } else if (op->operands_count == 1 && op->operands[0].type == ARM_CONSTANT) { data |= (op->operands[0].immediate << 16); } return data; } #include "armass64_const.h" static ut32 msrk(ut16 v) { ut32 r = 0; ut32 a = ((v >> 12) & 0xf) << 1; ut32 b = ((v & 0xfff) >> 3) & 0xff; r |= a << 8; r |= b << 16; return r; } static ut32 msr(ArmOp *op, int w) { ut32 data = UT32_MAX; int i; ut32 r, b; /* handle swapped args */ if (w) { if (op->operands[1].reg_type != (ARM_REG64 | ARM_SP)) { if (op->operands[1].type == ARM_CONSTANT) { for (i = 0; msr_const[i].name; i++) { if (op->operands[1].immediate == msr_const[i].val) { op->operands[1].sp_val = msr_const[i].val; op->operands[1].reg = op->operands[1].immediate; break; } } } else { return data; } } r = op->operands[0].reg; b = msrk (op->operands[0].sp_val); } else { if (op->operands[0].reg_type != (ARM_REG64 | ARM_SP)) { if (op->operands[0].type == ARM_CONSTANT) { for (i = 0; msr_const[i].name; i++) { if (op->operands[0].immediate == msr_const[i].val) { op->operands[0].sp_val = msr_const[i].val; op->operands[0].reg = op->operands[0].immediate; break; } } } else { return data; } } r = op->operands[0].reg; b = msrk (op->operands[0].sp_val); } data = (r << 24) | b | 0xd5; if (w) { /* mrs */ data |= 0x413000; } if (op->operands[1].reg_type == ARM_REG64) { data |= op->operands[1].reg << 24; } return data; } static ut32 orr(ArmOp *op, int addr) { ut32 data = UT32_MAX; if (op->operands[2].type & ARM_GPR) { // All operands need to be the same if (!(op->operands[0].reg_type == op->operands[1].reg_type && op->operands[1].reg_type == op->operands[2].reg_type)) { return data; } if (op->operands[0].reg_type & ARM_REG64) { data = 0x000000aa; } else { data = 0x0000002a; } data += op->operands[0].reg << 24; data += op->operands[1].reg << 29; data += (op->operands[1].reg >> 3) << 16; data += op->operands[2].reg << 8; } else if (op->operands[2].type & ARM_CONSTANT) { // Reg types need to match if (!(op->operands[0].reg_type == op->operands[1].reg_type)) { return data; } if (op->operands[0].reg_type & ARM_REG64) { data = 0x000040b2; } else { data = 0x00000032; } data += op->operands[0].reg << 24; data += op->operands[1].reg << 29; data += (op->operands[1].reg >> 3) << 16; ut32 imm = decodeBitMasks (op->operands[2].immediate); if (imm == -1) { return imm; } int low = imm & 0xF; if (op->operands[0].reg_type & ARM_REG64) { imm = ((imm >> 6) | 0x78); if (imm > 120) { data |= imm << 8; } } else { imm = ((imm >> 2)); if (imm > 120) { data |= imm << 4; } } data |= (4 * low) << 16; } return data; } static ut32 adrp(ArmOp *op, ut64 addr, ut32 k) { //, int reg, ut64 dst) { ut64 at = 0LL; ut32 data = k; if (op->operands[0].type == ARM_GPR) { data += ((op->operands[0].reg & 0xff) << 24); } else { eprintf ("Usage: adrp x0, addr\n"); return UT32_MAX; } if (op->operands[1].type == ARM_CONSTANT) { // XXX what about negative values? at = op->operands[1].immediate - addr; at /= 4; } else { eprintf ("Usage: adrp, x0, addr\n"); return UT32_MAX; } ut8 b0 = at; ut8 b1 = (at >> 3) & 0xff; #if 0 ut8 b2 = (at >> (8 + 7)) & 0xff; data += b0 << 29; data += b1 << 16; data += b2 << 24; #endif data += b0 << 16; data += b1 << 8; return data; } static ut32 adr(ArmOp *op, int addr) { ut32 data = UT32_MAX; ut64 at = 0LL; if (op->operands[1].type & ARM_CONSTANT) { // XXX what about negative values? at = op->operands[1].immediate - addr; at /= 4; } data = 0x00000030; data += 0x01000000 * op->operands[0].reg; ut8 b0 = at; ut8 b1 = (at >> 3) & 0xff; ut8 b2 = (at >> (8 + 7)) & 0xff; data += b0 << 29; data += b1 << 16; data += b2 << 24; return data; } static ut32 stp(ArmOp *op, int k) { ut32 data = UT32_MAX; if (op->operands[3].immediate & 0x7) { return data; } if (k == 0x000040a9 && (op->operands[0].reg == op->operands[1].reg)) { return data; } data = k; data += op->operands[0].reg << 24; data += op->operands[1].reg << 18; data += (op->operands[2].reg & 0x7) << 29; data += (op->operands[2].reg >> 3) << 16; data += (op->operands[3].immediate & 0x8) << 20; data += (op->operands[3].immediate >> 4) << 8; return data; } static ut32 exception(ArmOp *op, ut32 k) { ut32 data = UT32_MAX; if (op->operands[0].type == ARM_CONSTANT) { int n = op->operands[0].immediate; data = k; data += (((n / 8) & 0xff) << 16); data += n << 29;//((n >> 8) << 8); } return data; } static ut32 arithmetic (ArmOp *op, int k) { ut32 data = UT32_MAX; if (op->operands_count < 3) { return data; } if (!(op->operands[0].type & ARM_GPR && op->operands[1].type & ARM_GPR)) { return data; } if (op->operands[2].type & ARM_GPR) { k -= 6; } data = k; data += op->operands[0].reg << 24; data += (op->operands[1].reg & 7) << (24 + 5); data += (op->operands[1].reg >> 3) << 16; if (op->operands[2].reg_type & ARM_REG64) { data += op->operands[2].reg << 8; } else { data += (op->operands[2].reg & 0x3f) << 18; data += (op->operands[2].reg >> 6) << 8; } return data; } static bool parseOperands(char* str, ArmOp *op) { char *t = strdup (str); int operand = 0; char *token = t; char *x; int imm_count = 0; int mem_opt = 0; if (!token) { return false; } while (token) { char *next = strchr (token, ','); if (next) { *next++ = 0; } while (token[0] == ' ') { token++; } if (operand >= MAX_OPERANDS) { eprintf ("Too many operands\n"); return false; } op->operands[operand].type = ARM_NOTYPE; op->operands[operand].reg_type = ARM_UNDEFINED; op->operands[operand].shift = ARM_NO_SHIFT; while (token[0] == ' ' || token[0] == '[' || token[0] == ']') { token ++; } if (!strncmp (token, "lsl", 3)) { op->operands[operand].shift = ARM_LSL; } else if (!strncmp (token, "lsr", 3)) { op->operands[operand].shift = ARM_LSR; } else if (!strncmp (token, "asr", 3)) { op->operands[operand].shift = ARM_ASR; } if (strlen(token) > 4 && op->operands[operand].shift != ARM_NO_SHIFT) { op->operands_count ++; op->operands[operand].shift_amount = r_num_math (NULL, token + 4); if (op->operands[operand].shift_amount > 63) { return false; } operand ++; token = next; continue; } switch (token[0]) { case 'x': x = strchr (token, ','); if (x) { x[0] = '\0'; } op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_REG64; op->operands[operand].reg = r_num_math (NULL, token + 1); if (op->operands[operand].reg > 31) { return false; } break; case 'w': op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_REG32; op->operands[operand].reg = r_num_math (NULL, token + 1); if (op->operands[operand].reg > 31) { return false; } break; case 'v': op->operands_count ++; op->operands[operand].type = ARM_FP; op->operands[operand].reg = r_num_math (NULL, token + 1); break; case 's': case 'S': if (token[1] == 'P' || token [1] == 'p') { int i; for (i = 0; msr_const[i].name; i++) { if (!r_str_ncasecmp (token, msr_const[i].name, strlen (msr_const[i].name))) { op->operands[operand].sp_val = msr_const[i].val; break; } } op->operands_count ++; op->operands[operand].type = ARM_GPR; op->operands[operand].reg_type = ARM_SP | ARM_REG64; op->operands[operand].reg = 31; break; } mem_opt = get_mem_option (token); if (mem_opt != -1) { op->operands_count ++; op->operands[operand].type = ARM_MEM_OPT; op->operands[operand].mem_option = mem_opt; } break; case 'L': case 'l': case 'I': case 'i': case 'N': case 'n': case 'O': case 'o': case 'p': case 'P': mem_opt = get_mem_option (token); if (mem_opt != -1) { op->operands_count ++; op->operands[operand].type = ARM_MEM_OPT; op->operands[operand].mem_option = mem_opt; } break; case '-': op->operands[operand].sign = -1; // falthru default: op->operands_count ++; op->operands[operand].type = ARM_CONSTANT; op->operands[operand].immediate = r_num_math (NULL, token); imm_count++; break; } token = next; operand ++; if (operand > MAX_OPERANDS) { free (t); return false; } } free (t); return true; } static bool parseOpcode(const char *str, ArmOp *op) { char *in = strdup (str); char *space = strchr (in, ' '); if (!space) { op->operands[0].type = ARM_NOTYPE; op->mnemonic = in; return true; } space[0] = '\0'; op->mnemonic = in; space ++; return parseOperands (space, op); } bool arm64ass(const char *str, ut64 addr, ut32 *op) { ArmOp ops = {0}; if (!parseOpcode (str, &ops)) { return false; } /* TODO: write tests for this and move out the regsize logic into the mov */ if (!strncmp (str, "mov", 3)) { *op = mov (&ops); return *op != -1; } if (!strncmp (str, "cmp", 3)) { *op = cmp (&ops); return *op != -1; } if (!strncmp (str, "ldrb", 4)) { *op = bytelsop (&ops, 0x00004039); return *op != -1; } if (!strncmp (str, "ldrh", 4)) { *op = bytelsop (&ops, 0x00004078); return *op != -1; } if (!strncmp (str, "ldrsh", 5)) { *op = bytelsop (&ops, 0x0000c078); return *op != -1; } if (!strncmp (str, "ldrsw", 5)) { *op = bytelsop (&ops, 0x000080b8); return *op != -1; } if (!strncmp (str, "ldrsb", 5)) { *op = bytelsop (&ops, 0x0000c039); return *op != -1; } if (!strncmp (str, "strb", 4)) { *op = bytelsop (&ops, 0x00000039); return *op != -1; } if (!strncmp (str, "strh", 4)) { *op = bytelsop (&ops, 0x00000078); return *op != -1; } if (!strncmp (str, "ldr", 3)) { *op = reglsop (&ops, 0x000040f8); return *op != -1; } if (!strncmp (str, "stur", 4)) { *op = regsluop (&ops, 0x000000f8); return *op != -1; } if (!strncmp (str, "ldur", 4)) { *op = regsluop (&ops, 0x000040f8); return *op != -1; } if (!strncmp (str, "str", 3)) { *op = reglsop (&ops, 0x000000f8); return *op != -1; } if (!strncmp (str, "stp", 3)) { *op = stp (&ops, 0x000000a9); return *op != -1; } if (!strncmp (str, "ldp", 3)) { *op = stp (&ops, 0x000040a9); return *op != -1; } if (!strncmp (str, "sub", 3)) { // w *op = arithmetic (&ops, 0xd1); return *op != -1; } if (!strncmp (str, "add", 3)) { // w *op = arithmetic (&ops, 0x91); return *op != -1; } if (!strncmp (str, "adr x", 5)) { // w *op = adr (&ops, addr); return *op != -1; } if (!strncmp (str, "adrp x", 6)) { *op = adrp (&ops, addr, 0x00000090); return *op != -1; } if (!strcmp (str, "isb")) { *op = 0xdf3f03d5; return *op != -1; } if (!strcmp (str, "nop")) { *op = 0x1f2003d5; return *op != -1; } if (!strcmp (str, "ret")) { *op = 0xc0035fd6; return true; } if (!strncmp (str, "msr ", 4)) { *op = msr (&ops, 0); if (*op != UT32_MAX) { return true; } } if (!strncmp (str, "mrs ", 4)) { *op = msr (&ops, 1); if (*op != UT32_MAX) { return true; } } if (!strncmp (str, "orr ", 4)) { *op = orr (&ops, addr); return *op != UT32_MAX; } if (!strncmp (str, "svc ", 4)) { // system level exception *op = exception (&ops, 0x010000d4); return *op != -1; } if (!strncmp (str, "hvc ", 4)) { // hypervisor level exception *op = exception (&ops, 0x020000d4); return *op != -1; } if (!strncmp (str, "smc ", 4)) { // secure monitor exception *op = exception (&ops, 0x030000d4); return *op != -1; } if (!strncmp (str, "brk ", 4)) { // breakpoint *op = exception (&ops, 0x000020d4); return *op != -1; } if (!strncmp (str, "hlt ", 4)) { // halt *op = exception (&ops, 0x000040d4); return *op != -1; } if (!strncmp (str, "b ", 2)) { *op = branch (&ops, addr, 0x14); return *op != -1; } if (!strncmp (str, "b.eq ", 5)) { *op = bdot (&ops, addr, 0x00000054); return *op != -1; } if (!strncmp (str, "b.hs ", 5)) { *op = bdot (&ops, addr, 0x02000054); return *op != -1; } if (!strncmp (str, "bl ", 3)) { *op = branch (&ops, addr, 0x94); return *op != -1; } if (!strncmp (str, "br x", 4)) { *op = branch (&ops, addr, 0x1fd6); return *op != -1; } if (!strncmp (str, "blr x", 5)) { *op = branch (&ops, addr, 0x3fd6); return *op != -1; } if (!strncmp (str, "dmb ", 4)) { *op = mem_barrier (&ops, addr, 0xbf3003d5); return *op != -1; } if (!strncmp (str, "dsb ", 4)) { *op = mem_barrier (&ops, addr, 0x9f3003d5); return *op != -1; } if (!strncmp (str, "isb", 3)) { *op = mem_barrier (&ops, addr, 0xdf3f03d5); return *op != -1; } return false; }
./CrossVul/dataset_final_sorted/CWE-125/c/good_501_1
crossvul-cpp_data_bad_1280_0
/* * This file includes functions to transform a concrete syntax tree (CST) to * an abstract syntax tree (AST). The main function is PyAST_FromNode(). * */ #include "Python.h" #include "Python-ast.h" #include "node.h" #include "ast.h" #include "token.h" #include "pythonrun.h" #include <assert.h> #include <stdbool.h> #define MAXLEVEL 200 /* Max parentheses level */ static int validate_stmts(asdl_seq *); static int validate_exprs(asdl_seq *, expr_context_ty, int); static int validate_nonempty_seq(asdl_seq *, const char *, const char *); static int validate_stmt(stmt_ty); static int validate_expr(expr_ty, expr_context_ty); static int validate_comprehension(asdl_seq *gens) { Py_ssize_t i; if (!asdl_seq_LEN(gens)) { PyErr_SetString(PyExc_ValueError, "comprehension with no generators"); return 0; } for (i = 0; i < asdl_seq_LEN(gens); i++) { comprehension_ty comp = asdl_seq_GET(gens, i); if (!validate_expr(comp->target, Store) || !validate_expr(comp->iter, Load) || !validate_exprs(comp->ifs, Load, 0)) return 0; } return 1; } static int validate_slice(slice_ty slice) { switch (slice->kind) { case Slice_kind: return (!slice->v.Slice.lower || validate_expr(slice->v.Slice.lower, Load)) && (!slice->v.Slice.upper || validate_expr(slice->v.Slice.upper, Load)) && (!slice->v.Slice.step || validate_expr(slice->v.Slice.step, Load)); case ExtSlice_kind: { Py_ssize_t i; if (!validate_nonempty_seq(slice->v.ExtSlice.dims, "dims", "ExtSlice")) return 0; for (i = 0; i < asdl_seq_LEN(slice->v.ExtSlice.dims); i++) if (!validate_slice(asdl_seq_GET(slice->v.ExtSlice.dims, i))) return 0; return 1; } case Index_kind: return validate_expr(slice->v.Index.value, Load); default: PyErr_SetString(PyExc_SystemError, "unknown slice node"); return 0; } } static int validate_keywords(asdl_seq *keywords) { Py_ssize_t i; for (i = 0; i < asdl_seq_LEN(keywords); i++) if (!validate_expr(((keyword_ty)asdl_seq_GET(keywords, i))->value, Load)) return 0; return 1; } static int validate_args(asdl_seq *args) { Py_ssize_t i; for (i = 0; i < asdl_seq_LEN(args); i++) { arg_ty arg = asdl_seq_GET(args, i); if (arg->annotation && !validate_expr(arg->annotation, Load)) return 0; } return 1; } static const char * expr_context_name(expr_context_ty ctx) { switch (ctx) { case Load: return "Load"; case Store: return "Store"; case Del: return "Del"; case AugLoad: return "AugLoad"; case AugStore: return "AugStore"; case Param: return "Param"; default: Py_UNREACHABLE(); } } static int validate_arguments(arguments_ty args) { if (!validate_args(args->args)) return 0; if (args->vararg && args->vararg->annotation && !validate_expr(args->vararg->annotation, Load)) { return 0; } if (!validate_args(args->kwonlyargs)) return 0; if (args->kwarg && args->kwarg->annotation && !validate_expr(args->kwarg->annotation, Load)) { return 0; } if (asdl_seq_LEN(args->defaults) > asdl_seq_LEN(args->args)) { PyErr_SetString(PyExc_ValueError, "more positional defaults than args on arguments"); return 0; } if (asdl_seq_LEN(args->kw_defaults) != asdl_seq_LEN(args->kwonlyargs)) { PyErr_SetString(PyExc_ValueError, "length of kwonlyargs is not the same as " "kw_defaults on arguments"); return 0; } return validate_exprs(args->defaults, Load, 0) && validate_exprs(args->kw_defaults, Load, 1); } static int validate_constant(PyObject *value) { if (value == Py_None || value == Py_Ellipsis) return 1; if (PyLong_CheckExact(value) || PyFloat_CheckExact(value) || PyComplex_CheckExact(value) || PyBool_Check(value) || PyUnicode_CheckExact(value) || PyBytes_CheckExact(value)) return 1; if (PyTuple_CheckExact(value) || PyFrozenSet_CheckExact(value)) { PyObject *it; it = PyObject_GetIter(value); if (it == NULL) return 0; while (1) { PyObject *item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) { Py_DECREF(it); return 0; } break; } if (!validate_constant(item)) { Py_DECREF(it); Py_DECREF(item); return 0; } Py_DECREF(item); } Py_DECREF(it); return 1; } return 0; } static int validate_expr(expr_ty exp, expr_context_ty ctx) { int check_ctx = 1; expr_context_ty actual_ctx; /* First check expression context. */ switch (exp->kind) { case Attribute_kind: actual_ctx = exp->v.Attribute.ctx; break; case Subscript_kind: actual_ctx = exp->v.Subscript.ctx; break; case Starred_kind: actual_ctx = exp->v.Starred.ctx; break; case Name_kind: actual_ctx = exp->v.Name.ctx; break; case List_kind: actual_ctx = exp->v.List.ctx; break; case Tuple_kind: actual_ctx = exp->v.Tuple.ctx; break; default: if (ctx != Load) { PyErr_Format(PyExc_ValueError, "expression which can't be " "assigned to in %s context", expr_context_name(ctx)); return 0; } check_ctx = 0; /* set actual_ctx to prevent gcc warning */ actual_ctx = 0; } if (check_ctx && actual_ctx != ctx) { PyErr_Format(PyExc_ValueError, "expression must have %s context but has %s instead", expr_context_name(ctx), expr_context_name(actual_ctx)); return 0; } /* Now validate expression. */ switch (exp->kind) { case BoolOp_kind: if (asdl_seq_LEN(exp->v.BoolOp.values) < 2) { PyErr_SetString(PyExc_ValueError, "BoolOp with less than 2 values"); return 0; } return validate_exprs(exp->v.BoolOp.values, Load, 0); case BinOp_kind: return validate_expr(exp->v.BinOp.left, Load) && validate_expr(exp->v.BinOp.right, Load); case UnaryOp_kind: return validate_expr(exp->v.UnaryOp.operand, Load); case Lambda_kind: return validate_arguments(exp->v.Lambda.args) && validate_expr(exp->v.Lambda.body, Load); case IfExp_kind: return validate_expr(exp->v.IfExp.test, Load) && validate_expr(exp->v.IfExp.body, Load) && validate_expr(exp->v.IfExp.orelse, Load); case Dict_kind: if (asdl_seq_LEN(exp->v.Dict.keys) != asdl_seq_LEN(exp->v.Dict.values)) { PyErr_SetString(PyExc_ValueError, "Dict doesn't have the same number of keys as values"); return 0; } /* null_ok=1 for keys expressions to allow dict unpacking to work in dict literals, i.e. ``{**{a:b}}`` */ return validate_exprs(exp->v.Dict.keys, Load, /*null_ok=*/ 1) && validate_exprs(exp->v.Dict.values, Load, /*null_ok=*/ 0); case Set_kind: return validate_exprs(exp->v.Set.elts, Load, 0); #define COMP(NAME) \ case NAME ## _kind: \ return validate_comprehension(exp->v.NAME.generators) && \ validate_expr(exp->v.NAME.elt, Load); COMP(ListComp) COMP(SetComp) COMP(GeneratorExp) #undef COMP case DictComp_kind: return validate_comprehension(exp->v.DictComp.generators) && validate_expr(exp->v.DictComp.key, Load) && validate_expr(exp->v.DictComp.value, Load); case Yield_kind: return !exp->v.Yield.value || validate_expr(exp->v.Yield.value, Load); case YieldFrom_kind: return validate_expr(exp->v.YieldFrom.value, Load); case Await_kind: return validate_expr(exp->v.Await.value, Load); case Compare_kind: if (!asdl_seq_LEN(exp->v.Compare.comparators)) { PyErr_SetString(PyExc_ValueError, "Compare with no comparators"); return 0; } if (asdl_seq_LEN(exp->v.Compare.comparators) != asdl_seq_LEN(exp->v.Compare.ops)) { PyErr_SetString(PyExc_ValueError, "Compare has a different number " "of comparators and operands"); return 0; } return validate_exprs(exp->v.Compare.comparators, Load, 0) && validate_expr(exp->v.Compare.left, Load); case Call_kind: return validate_expr(exp->v.Call.func, Load) && validate_exprs(exp->v.Call.args, Load, 0) && validate_keywords(exp->v.Call.keywords); case Constant_kind: if (!validate_constant(exp->v.Constant.value)) { PyErr_Format(PyExc_TypeError, "got an invalid type in Constant: %s", Py_TYPE(exp->v.Constant.value)->tp_name); return 0; } return 1; case JoinedStr_kind: return validate_exprs(exp->v.JoinedStr.values, Load, 0); case FormattedValue_kind: if (validate_expr(exp->v.FormattedValue.value, Load) == 0) return 0; if (exp->v.FormattedValue.format_spec) return validate_expr(exp->v.FormattedValue.format_spec, Load); return 1; case Attribute_kind: return validate_expr(exp->v.Attribute.value, Load); case Subscript_kind: return validate_slice(exp->v.Subscript.slice) && validate_expr(exp->v.Subscript.value, Load); case Starred_kind: return validate_expr(exp->v.Starred.value, ctx); case List_kind: return validate_exprs(exp->v.List.elts, ctx, 0); case Tuple_kind: return validate_exprs(exp->v.Tuple.elts, ctx, 0); case NamedExpr_kind: return validate_expr(exp->v.NamedExpr.value, Load); /* This last case doesn't have any checking. */ case Name_kind: return 1; } PyErr_SetString(PyExc_SystemError, "unexpected expression"); return 0; } static int validate_nonempty_seq(asdl_seq *seq, const char *what, const char *owner) { if (asdl_seq_LEN(seq)) return 1; PyErr_Format(PyExc_ValueError, "empty %s on %s", what, owner); return 0; } static int validate_assignlist(asdl_seq *targets, expr_context_ty ctx) { return validate_nonempty_seq(targets, "targets", ctx == Del ? "Delete" : "Assign") && validate_exprs(targets, ctx, 0); } static int validate_body(asdl_seq *body, const char *owner) { return validate_nonempty_seq(body, "body", owner) && validate_stmts(body); } static int validate_stmt(stmt_ty stmt) { Py_ssize_t i; switch (stmt->kind) { case FunctionDef_kind: return validate_body(stmt->v.FunctionDef.body, "FunctionDef") && validate_arguments(stmt->v.FunctionDef.args) && validate_exprs(stmt->v.FunctionDef.decorator_list, Load, 0) && (!stmt->v.FunctionDef.returns || validate_expr(stmt->v.FunctionDef.returns, Load)); case ClassDef_kind: return validate_body(stmt->v.ClassDef.body, "ClassDef") && validate_exprs(stmt->v.ClassDef.bases, Load, 0) && validate_keywords(stmt->v.ClassDef.keywords) && validate_exprs(stmt->v.ClassDef.decorator_list, Load, 0); case Return_kind: return !stmt->v.Return.value || validate_expr(stmt->v.Return.value, Load); case Delete_kind: return validate_assignlist(stmt->v.Delete.targets, Del); case Assign_kind: return validate_assignlist(stmt->v.Assign.targets, Store) && validate_expr(stmt->v.Assign.value, Load); case AugAssign_kind: return validate_expr(stmt->v.AugAssign.target, Store) && validate_expr(stmt->v.AugAssign.value, Load); case AnnAssign_kind: if (stmt->v.AnnAssign.target->kind != Name_kind && stmt->v.AnnAssign.simple) { PyErr_SetString(PyExc_TypeError, "AnnAssign with simple non-Name target"); return 0; } return validate_expr(stmt->v.AnnAssign.target, Store) && (!stmt->v.AnnAssign.value || validate_expr(stmt->v.AnnAssign.value, Load)) && validate_expr(stmt->v.AnnAssign.annotation, Load); case For_kind: return validate_expr(stmt->v.For.target, Store) && validate_expr(stmt->v.For.iter, Load) && validate_body(stmt->v.For.body, "For") && validate_stmts(stmt->v.For.orelse); case AsyncFor_kind: return validate_expr(stmt->v.AsyncFor.target, Store) && validate_expr(stmt->v.AsyncFor.iter, Load) && validate_body(stmt->v.AsyncFor.body, "AsyncFor") && validate_stmts(stmt->v.AsyncFor.orelse); case While_kind: return validate_expr(stmt->v.While.test, Load) && validate_body(stmt->v.While.body, "While") && validate_stmts(stmt->v.While.orelse); case If_kind: return validate_expr(stmt->v.If.test, Load) && validate_body(stmt->v.If.body, "If") && validate_stmts(stmt->v.If.orelse); case With_kind: if (!validate_nonempty_seq(stmt->v.With.items, "items", "With")) return 0; for (i = 0; i < asdl_seq_LEN(stmt->v.With.items); i++) { withitem_ty item = asdl_seq_GET(stmt->v.With.items, i); if (!validate_expr(item->context_expr, Load) || (item->optional_vars && !validate_expr(item->optional_vars, Store))) return 0; } return validate_body(stmt->v.With.body, "With"); case AsyncWith_kind: if (!validate_nonempty_seq(stmt->v.AsyncWith.items, "items", "AsyncWith")) return 0; for (i = 0; i < asdl_seq_LEN(stmt->v.AsyncWith.items); i++) { withitem_ty item = asdl_seq_GET(stmt->v.AsyncWith.items, i); if (!validate_expr(item->context_expr, Load) || (item->optional_vars && !validate_expr(item->optional_vars, Store))) return 0; } return validate_body(stmt->v.AsyncWith.body, "AsyncWith"); case Raise_kind: if (stmt->v.Raise.exc) { return validate_expr(stmt->v.Raise.exc, Load) && (!stmt->v.Raise.cause || validate_expr(stmt->v.Raise.cause, Load)); } if (stmt->v.Raise.cause) { PyErr_SetString(PyExc_ValueError, "Raise with cause but no exception"); return 0; } return 1; case Try_kind: if (!validate_body(stmt->v.Try.body, "Try")) return 0; if (!asdl_seq_LEN(stmt->v.Try.handlers) && !asdl_seq_LEN(stmt->v.Try.finalbody)) { PyErr_SetString(PyExc_ValueError, "Try has neither except handlers nor finalbody"); return 0; } if (!asdl_seq_LEN(stmt->v.Try.handlers) && asdl_seq_LEN(stmt->v.Try.orelse)) { PyErr_SetString(PyExc_ValueError, "Try has orelse but no except handlers"); return 0; } for (i = 0; i < asdl_seq_LEN(stmt->v.Try.handlers); i++) { excepthandler_ty handler = asdl_seq_GET(stmt->v.Try.handlers, i); if ((handler->v.ExceptHandler.type && !validate_expr(handler->v.ExceptHandler.type, Load)) || !validate_body(handler->v.ExceptHandler.body, "ExceptHandler")) return 0; } return (!asdl_seq_LEN(stmt->v.Try.finalbody) || validate_stmts(stmt->v.Try.finalbody)) && (!asdl_seq_LEN(stmt->v.Try.orelse) || validate_stmts(stmt->v.Try.orelse)); case Assert_kind: return validate_expr(stmt->v.Assert.test, Load) && (!stmt->v.Assert.msg || validate_expr(stmt->v.Assert.msg, Load)); case Import_kind: return validate_nonempty_seq(stmt->v.Import.names, "names", "Import"); case ImportFrom_kind: if (stmt->v.ImportFrom.level < 0) { PyErr_SetString(PyExc_ValueError, "Negative ImportFrom level"); return 0; } return validate_nonempty_seq(stmt->v.ImportFrom.names, "names", "ImportFrom"); case Global_kind: return validate_nonempty_seq(stmt->v.Global.names, "names", "Global"); case Nonlocal_kind: return validate_nonempty_seq(stmt->v.Nonlocal.names, "names", "Nonlocal"); case Expr_kind: return validate_expr(stmt->v.Expr.value, Load); case AsyncFunctionDef_kind: return validate_body(stmt->v.AsyncFunctionDef.body, "AsyncFunctionDef") && validate_arguments(stmt->v.AsyncFunctionDef.args) && validate_exprs(stmt->v.AsyncFunctionDef.decorator_list, Load, 0) && (!stmt->v.AsyncFunctionDef.returns || validate_expr(stmt->v.AsyncFunctionDef.returns, Load)); case Pass_kind: case Break_kind: case Continue_kind: return 1; default: PyErr_SetString(PyExc_SystemError, "unexpected statement"); return 0; } } static int validate_stmts(asdl_seq *seq) { Py_ssize_t i; for (i = 0; i < asdl_seq_LEN(seq); i++) { stmt_ty stmt = asdl_seq_GET(seq, i); if (stmt) { if (!validate_stmt(stmt)) return 0; } else { PyErr_SetString(PyExc_ValueError, "None disallowed in statement list"); return 0; } } return 1; } static int validate_exprs(asdl_seq *exprs, expr_context_ty ctx, int null_ok) { Py_ssize_t i; for (i = 0; i < asdl_seq_LEN(exprs); i++) { expr_ty expr = asdl_seq_GET(exprs, i); if (expr) { if (!validate_expr(expr, ctx)) return 0; } else if (!null_ok) { PyErr_SetString(PyExc_ValueError, "None disallowed in expression list"); return 0; } } return 1; } int PyAST_Validate(mod_ty mod) { int res = 0; switch (mod->kind) { case Module_kind: res = validate_stmts(mod->v.Module.body); break; case Interactive_kind: res = validate_stmts(mod->v.Interactive.body); break; case Expression_kind: res = validate_expr(mod->v.Expression.body, Load); break; case Suite_kind: PyErr_SetString(PyExc_ValueError, "Suite is not valid in the CPython compiler"); break; default: PyErr_SetString(PyExc_SystemError, "impossible module node"); res = 0; break; } return res; } /* This is done here, so defines like "test" don't interfere with AST use above. */ #include "grammar.h" #include "parsetok.h" #include "graminit.h" /* Data structure used internally */ struct compiling { PyArena *c_arena; /* Arena for allocating memory. */ PyObject *c_filename; /* filename */ PyObject *c_normalize; /* Normalization function from unicodedata. */ int c_feature_version; /* Latest minor version of Python for allowed features */ }; static asdl_seq *seq_for_testlist(struct compiling *, const node *); static expr_ty ast_for_expr(struct compiling *, const node *); static stmt_ty ast_for_stmt(struct compiling *, const node *); static asdl_seq *ast_for_suite(struct compiling *c, const node *n); static asdl_seq *ast_for_exprlist(struct compiling *, const node *, expr_context_ty); static expr_ty ast_for_testlist(struct compiling *, const node *); static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *); static stmt_ty ast_for_with_stmt(struct compiling *, const node *, bool); static stmt_ty ast_for_for_stmt(struct compiling *, const node *, bool); /* Note different signature for ast_for_call */ static expr_ty ast_for_call(struct compiling *, const node *, expr_ty, const node *, const node *); static PyObject *parsenumber(struct compiling *, const char *); static expr_ty parsestrplus(struct compiling *, const node *n); static void get_last_end_pos(asdl_seq *, int *, int *); #define COMP_GENEXP 0 #define COMP_LISTCOMP 1 #define COMP_SETCOMP 2 static int init_normalization(struct compiling *c) { PyObject *m = PyImport_ImportModuleNoBlock("unicodedata"); if (!m) return 0; c->c_normalize = PyObject_GetAttrString(m, "normalize"); Py_DECREF(m); if (!c->c_normalize) return 0; return 1; } static identifier new_identifier(const char *n, struct compiling *c) { PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL); if (!id) return NULL; /* PyUnicode_DecodeUTF8 should always return a ready string. */ assert(PyUnicode_IS_READY(id)); /* Check whether there are non-ASCII characters in the identifier; if so, normalize to NFKC. */ if (!PyUnicode_IS_ASCII(id)) { PyObject *id2; _Py_IDENTIFIER(NFKC); if (!c->c_normalize && !init_normalization(c)) { Py_DECREF(id); return NULL; } PyObject *form = _PyUnicode_FromId(&PyId_NFKC); if (form == NULL) { Py_DECREF(id); return NULL; } PyObject *args[2] = {form, id}; id2 = _PyObject_FastCall(c->c_normalize, args, 2); Py_DECREF(id); if (!id2) return NULL; if (!PyUnicode_Check(id2)) { PyErr_Format(PyExc_TypeError, "unicodedata.normalize() must return a string, not " "%.200s", Py_TYPE(id2)->tp_name); Py_DECREF(id2); return NULL; } id = id2; } PyUnicode_InternInPlace(&id); if (PyArena_AddPyObject(c->c_arena, id) < 0) { Py_DECREF(id); return NULL; } return id; } #define NEW_IDENTIFIER(n) new_identifier(STR(n), c) static int ast_error(struct compiling *c, const node *n, const char *errmsg, ...) { PyObject *value, *errstr, *loc, *tmp; va_list va; va_start(va, errmsg); errstr = PyUnicode_FromFormatV(errmsg, va); va_end(va); if (!errstr) { return 0; } loc = PyErr_ProgramTextObject(c->c_filename, LINENO(n)); if (!loc) { Py_INCREF(Py_None); loc = Py_None; } tmp = Py_BuildValue("(OiiN)", c->c_filename, LINENO(n), n->n_col_offset + 1, loc); if (!tmp) { Py_DECREF(errstr); return 0; } value = PyTuple_Pack(2, errstr, tmp); Py_DECREF(errstr); Py_DECREF(tmp); if (value) { PyErr_SetObject(PyExc_SyntaxError, value); Py_DECREF(value); } return 0; } /* num_stmts() returns number of contained statements. Use this routine to determine how big a sequence is needed for the statements in a parse tree. Its raison d'etre is this bit of grammar: stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE A simple_stmt can contain multiple small_stmt elements joined by semicolons. If the arg is a simple_stmt, the number of small_stmt elements is returned. */ static string new_type_comment(const char *s, struct compiling *c) { PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL); if (res == NULL) return NULL; if (PyArena_AddPyObject(c->c_arena, res) < 0) { Py_DECREF(res); return NULL; } return res; } #define NEW_TYPE_COMMENT(n) new_type_comment(STR(n), c) static int num_stmts(const node *n) { int i, l; node *ch; switch (TYPE(n)) { case single_input: if (TYPE(CHILD(n, 0)) == NEWLINE) return 0; else return num_stmts(CHILD(n, 0)); case file_input: l = 0; for (i = 0; i < NCH(n); i++) { ch = CHILD(n, i); if (TYPE(ch) == stmt) l += num_stmts(ch); } return l; case stmt: return num_stmts(CHILD(n, 0)); case compound_stmt: return 1; case simple_stmt: return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */ case suite: case func_body_suite: /* func_body_suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */ /* suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT */ if (NCH(n) == 1) return num_stmts(CHILD(n, 0)); else { i = 2; l = 0; if (TYPE(CHILD(n, 1)) == TYPE_COMMENT) i += 2; for (; i < (NCH(n) - 1); i++) l += num_stmts(CHILD(n, i)); return l; } default: { char buf[128]; sprintf(buf, "Non-statement found: %d %d", TYPE(n), NCH(n)); Py_FatalError(buf); } } Py_UNREACHABLE(); } /* Transform the CST rooted at node * to the appropriate AST */ mod_ty PyAST_FromNodeObject(const node *n, PyCompilerFlags *flags, PyObject *filename, PyArena *arena) { int i, j, k, num; asdl_seq *stmts = NULL; asdl_seq *type_ignores = NULL; stmt_ty s; node *ch; struct compiling c; mod_ty res = NULL; asdl_seq *argtypes = NULL; expr_ty ret, arg; c.c_arena = arena; /* borrowed reference */ c.c_filename = filename; c.c_normalize = NULL; c.c_feature_version = flags->cf_feature_version; if (TYPE(n) == encoding_decl) n = CHILD(n, 0); k = 0; switch (TYPE(n)) { case file_input: stmts = _Py_asdl_seq_new(num_stmts(n), arena); if (!stmts) goto out; for (i = 0; i < NCH(n) - 1; i++) { ch = CHILD(n, i); if (TYPE(ch) == NEWLINE) continue; REQ(ch, stmt); num = num_stmts(ch); if (num == 1) { s = ast_for_stmt(&c, ch); if (!s) goto out; asdl_seq_SET(stmts, k++, s); } else { ch = CHILD(ch, 0); REQ(ch, simple_stmt); for (j = 0; j < num; j++) { s = ast_for_stmt(&c, CHILD(ch, j * 2)); if (!s) goto out; asdl_seq_SET(stmts, k++, s); } } } /* Type ignores are stored under the ENDMARKER in file_input. */ ch = CHILD(n, NCH(n) - 1); REQ(ch, ENDMARKER); num = NCH(ch); type_ignores = _Py_asdl_seq_new(num, arena); if (!type_ignores) goto out; for (i = 0; i < num; i++) { type_ignore_ty ti = TypeIgnore(LINENO(CHILD(ch, i)), arena); if (!ti) goto out; asdl_seq_SET(type_ignores, i, ti); } res = Module(stmts, type_ignores, arena); break; case eval_input: { expr_ty testlist_ast; /* XXX Why not comp_for here? */ testlist_ast = ast_for_testlist(&c, CHILD(n, 0)); if (!testlist_ast) goto out; res = Expression(testlist_ast, arena); break; } case single_input: if (TYPE(CHILD(n, 0)) == NEWLINE) { stmts = _Py_asdl_seq_new(1, arena); if (!stmts) goto out; asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, arena)); if (!asdl_seq_GET(stmts, 0)) goto out; res = Interactive(stmts, arena); } else { n = CHILD(n, 0); num = num_stmts(n); stmts = _Py_asdl_seq_new(num, arena); if (!stmts) goto out; if (num == 1) { s = ast_for_stmt(&c, n); if (!s) goto out; asdl_seq_SET(stmts, 0, s); } else { /* Only a simple_stmt can contain multiple statements. */ REQ(n, simple_stmt); for (i = 0; i < NCH(n); i += 2) { if (TYPE(CHILD(n, i)) == NEWLINE) break; s = ast_for_stmt(&c, CHILD(n, i)); if (!s) goto out; asdl_seq_SET(stmts, i / 2, s); } } res = Interactive(stmts, arena); } break; case func_type_input: n = CHILD(n, 0); REQ(n, func_type); if (TYPE(CHILD(n, 1)) == typelist) { ch = CHILD(n, 1); /* this is overly permissive -- we don't pay any attention to * stars on the args -- just parse them into an ordered list */ num = 0; for (i = 0; i < NCH(ch); i++) { if (TYPE(CHILD(ch, i)) == test) { num++; } } argtypes = _Py_asdl_seq_new(num, arena); if (!argtypes) goto out; j = 0; for (i = 0; i < NCH(ch); i++) { if (TYPE(CHILD(ch, i)) == test) { arg = ast_for_expr(&c, CHILD(ch, i)); if (!arg) goto out; asdl_seq_SET(argtypes, j++, arg); } } } else { argtypes = _Py_asdl_seq_new(0, arena); if (!argtypes) goto out; } ret = ast_for_expr(&c, CHILD(n, NCH(n) - 1)); if (!ret) goto out; res = FunctionType(argtypes, ret, arena); break; default: PyErr_Format(PyExc_SystemError, "invalid node %d for PyAST_FromNode", TYPE(n)); goto out; } out: if (c.c_normalize) { Py_DECREF(c.c_normalize); } return res; } mod_ty PyAST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename_str, PyArena *arena) { mod_ty mod; PyObject *filename; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; mod = PyAST_FromNodeObject(n, flags, filename, arena); Py_DECREF(filename); return mod; } /* Return the AST repr. of the operator represented as syntax (|, ^, etc.) */ static operator_ty get_operator(struct compiling *c, const node *n) { switch (TYPE(n)) { case VBAR: return BitOr; case CIRCUMFLEX: return BitXor; case AMPER: return BitAnd; case LEFTSHIFT: return LShift; case RIGHTSHIFT: return RShift; case PLUS: return Add; case MINUS: return Sub; case STAR: return Mult; case AT: if (c->c_feature_version < 5) { ast_error(c, n, "The '@' operator is only supported in Python 3.5 and greater"); return (operator_ty)0; } return MatMult; case SLASH: return Div; case DOUBLESLASH: return FloorDiv; case PERCENT: return Mod; default: return (operator_ty)0; } } static const char * const FORBIDDEN[] = { "None", "True", "False", "__debug__", NULL, }; static int forbidden_name(struct compiling *c, identifier name, const node *n, int full_checks) { assert(PyUnicode_Check(name)); const char * const *p = FORBIDDEN; if (!full_checks) { /* In most cases, the parser will protect True, False, and None from being assign to. */ p += 3; } for (; *p; p++) { if (_PyUnicode_EqualToASCIIString(name, *p)) { ast_error(c, n, "cannot assign to %U", name); return 1; } } return 0; } static expr_ty copy_location(expr_ty e, const node *n) { if (e) { e->lineno = LINENO(n); e->col_offset = n->n_col_offset; e->end_lineno = n->n_end_lineno; e->end_col_offset = n->n_end_col_offset; } return e; } static const char * get_expr_name(expr_ty e) { switch (e->kind) { case Attribute_kind: return "attribute"; case Subscript_kind: return "subscript"; case Starred_kind: return "starred"; case Name_kind: return "name"; case List_kind: return "list"; case Tuple_kind: return "tuple"; case Lambda_kind: return "lambda"; case Call_kind: return "function call"; case BoolOp_kind: case BinOp_kind: case UnaryOp_kind: return "operator"; case GeneratorExp_kind: return "generator expression"; case Yield_kind: case YieldFrom_kind: return "yield expression"; case Await_kind: return "await expression"; case ListComp_kind: return "list comprehension"; case SetComp_kind: return "set comprehension"; case DictComp_kind: return "dict comprehension"; case Dict_kind: return "dict display"; case Set_kind: return "set display"; case JoinedStr_kind: case FormattedValue_kind: return "f-string expression"; case Constant_kind: { PyObject *value = e->v.Constant.value; if (value == Py_None) { return "None"; } if (value == Py_False) { return "False"; } if (value == Py_True) { return "True"; } if (value == Py_Ellipsis) { return "Ellipsis"; } return "literal"; } case Compare_kind: return "comparison"; case IfExp_kind: return "conditional expression"; case NamedExpr_kind: return "named expression"; default: PyErr_Format(PyExc_SystemError, "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return NULL; } } /* Set the context ctx for expr_ty e, recursively traversing e. Only sets context for expr kinds that "can appear in assignment context" (according to ../Parser/Python.asdl). For other expr kinds, it sets an appropriate syntax error and returns false. */ static int set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n) { asdl_seq *s = NULL; /* The ast defines augmented store and load contexts, but the implementation here doesn't actually use them. The code may be a little more complex than necessary as a result. It also means that expressions in an augmented assignment have a Store context. Consider restructuring so that augmented assignment uses set_context(), too. */ assert(ctx != AugStore && ctx != AugLoad); switch (e->kind) { case Attribute_kind: e->v.Attribute.ctx = ctx; if (ctx == Store && forbidden_name(c, e->v.Attribute.attr, n, 1)) return 0; break; case Subscript_kind: e->v.Subscript.ctx = ctx; break; case Starred_kind: e->v.Starred.ctx = ctx; if (!set_context(c, e->v.Starred.value, ctx, n)) return 0; break; case Name_kind: if (ctx == Store) { if (forbidden_name(c, e->v.Name.id, n, 0)) return 0; /* forbidden_name() calls ast_error() */ } e->v.Name.ctx = ctx; break; case List_kind: e->v.List.ctx = ctx; s = e->v.List.elts; break; case Tuple_kind: e->v.Tuple.ctx = ctx; s = e->v.Tuple.elts; break; default: { const char *expr_name = get_expr_name(e); if (expr_name != NULL) { ast_error(c, n, "cannot %s %s", ctx == Store ? "assign to" : "delete", expr_name); } return 0; } } /* If the LHS is a list or tuple, we need to set the assignment context for all the contained elements. */ if (s) { Py_ssize_t i; for (i = 0; i < asdl_seq_LEN(s); i++) { if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n)) return 0; } } return 1; } static operator_ty ast_for_augassign(struct compiling *c, const node *n) { REQ(n, augassign); n = CHILD(n, 0); switch (STR(n)[0]) { case '+': return Add; case '-': return Sub; case '/': if (STR(n)[1] == '/') return FloorDiv; else return Div; case '%': return Mod; case '<': return LShift; case '>': return RShift; case '&': return BitAnd; case '^': return BitXor; case '|': return BitOr; case '*': if (STR(n)[1] == '*') return Pow; else return Mult; case '@': if (c->c_feature_version < 5) { ast_error(c, n, "The '@' operator is only supported in Python 3.5 and greater"); return (operator_ty)0; } return MatMult; default: PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n)); return (operator_ty)0; } } static cmpop_ty ast_for_comp_op(struct compiling *c, const node *n) { /* comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is' |'is' 'not' */ REQ(n, comp_op); if (NCH(n) == 1) { n = CHILD(n, 0); switch (TYPE(n)) { case LESS: return Lt; case GREATER: return Gt; case EQEQUAL: /* == */ return Eq; case LESSEQUAL: return LtE; case GREATEREQUAL: return GtE; case NOTEQUAL: return NotEq; case NAME: if (strcmp(STR(n), "in") == 0) return In; if (strcmp(STR(n), "is") == 0) return Is; /* fall through */ default: PyErr_Format(PyExc_SystemError, "invalid comp_op: %s", STR(n)); return (cmpop_ty)0; } } else if (NCH(n) == 2) { /* handle "not in" and "is not" */ switch (TYPE(CHILD(n, 0))) { case NAME: if (strcmp(STR(CHILD(n, 1)), "in") == 0) return NotIn; if (strcmp(STR(CHILD(n, 0)), "is") == 0) return IsNot; /* fall through */ default: PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s", STR(CHILD(n, 0)), STR(CHILD(n, 1))); return (cmpop_ty)0; } } PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children", NCH(n)); return (cmpop_ty)0; } static asdl_seq * seq_for_testlist(struct compiling *c, const node *n) { /* testlist: test (',' test)* [','] testlist_star_expr: test|star_expr (',' test|star_expr)* [','] */ asdl_seq *seq; expr_ty expression; int i; assert(TYPE(n) == testlist || TYPE(n) == testlist_star_expr || TYPE(n) == testlist_comp); seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) return NULL; for (i = 0; i < NCH(n); i += 2) { const node *ch = CHILD(n, i); assert(TYPE(ch) == test || TYPE(ch) == test_nocond || TYPE(ch) == star_expr || TYPE(ch) == namedexpr_test); expression = ast_for_expr(c, ch); if (!expression) return NULL; assert(i / 2 < seq->size); asdl_seq_SET(seq, i / 2, expression); } return seq; } static arg_ty ast_for_arg(struct compiling *c, const node *n) { identifier name; expr_ty annotation = NULL; node *ch; arg_ty ret; assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef); ch = CHILD(n, 0); name = NEW_IDENTIFIER(ch); if (!name) return NULL; if (forbidden_name(c, name, ch, 0)) return NULL; if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) { annotation = ast_for_expr(c, CHILD(n, 2)); if (!annotation) return NULL; } ret = arg(name, annotation, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!ret) return NULL; return ret; } /* returns -1 if failed to handle keyword only arguments returns new position to keep processing if successful (',' tfpdef ['=' test])* ^^^ start pointing here */ static int handle_keywordonly_args(struct compiling *c, const node *n, int start, asdl_seq *kwonlyargs, asdl_seq *kwdefaults) { PyObject *argname; node *ch; expr_ty expression, annotation; arg_ty arg = NULL; int i = start; int j = 0; /* index for kwdefaults and kwonlyargs */ if (kwonlyargs == NULL) { ast_error(c, CHILD(n, start), "named arguments must follow bare *"); return -1; } assert(kwdefaults != NULL); while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case vfpdef: case tfpdef: if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) goto error; asdl_seq_SET(kwdefaults, j, expression); i += 2; /* '=' and test */ } else { /* setting NULL if no default value exists */ asdl_seq_SET(kwdefaults, j, NULL); } if (NCH(ch) == 3) { /* ch is NAME ':' test */ annotation = ast_for_expr(c, CHILD(ch, 2)); if (!annotation) goto error; } else { annotation = NULL; } ch = CHILD(ch, 0); argname = NEW_IDENTIFIER(ch); if (!argname) goto error; if (forbidden_name(c, argname, ch, 0)) goto error; arg = arg(argname, annotation, NULL, LINENO(ch), ch->n_col_offset, ch->n_end_lineno, ch->n_end_col_offset, c->c_arena); if (!arg) goto error; asdl_seq_SET(kwonlyargs, j++, arg); i += 1; /* the name */ if (TYPE(CHILD(n, i)) == COMMA) i += 1; /* the comma, if present */ break; case TYPE_COMMENT: /* arg will be equal to the last argument processed */ arg->type_comment = NEW_TYPE_COMMENT(ch); if (!arg->type_comment) goto error; i += 1; break; case DOUBLESTAR: return i; default: ast_error(c, ch, "unexpected node"); goto error; } } return i; error: return -1; } /* Create AST for argument list. */ static arguments_ty ast_for_arguments(struct compiling *c, const node *n) { /* This function handles both typedargslist (function definition) and varargslist (lambda definition). parameters: '(' [typedargslist] ')' typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [ '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] | '**' tfpdef [',']]] | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] | '**' tfpdef [',']) tfpdef: NAME [':' test] varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [ '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] | '**' vfpdef [',']]] | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] | '**' vfpdef [','] ) vfpdef: NAME */ int i, j, k, nposargs = 0, nkwonlyargs = 0; int nposdefaults = 0, found_default = 0; asdl_seq *posargs, *posdefaults, *kwonlyargs, *kwdefaults; arg_ty vararg = NULL, kwarg = NULL; arg_ty arg = NULL; node *ch; if (TYPE(n) == parameters) { if (NCH(n) == 2) /* () as argument list */ return arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena); n = CHILD(n, 1); } assert(TYPE(n) == typedargslist || TYPE(n) == varargslist); /* First count the number of positional args & defaults. The variable i is the loop index for this for loop and the next. The next loop picks up where the first leaves off. */ for (i = 0; i < NCH(n); i++) { ch = CHILD(n, i); if (TYPE(ch) == STAR) { /* skip star */ i++; if (i < NCH(n) && /* skip argument following star */ (TYPE(CHILD(n, i)) == tfpdef || TYPE(CHILD(n, i)) == vfpdef)) { i++; } break; } if (TYPE(ch) == DOUBLESTAR) break; if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++; if (TYPE(ch) == EQUAL) nposdefaults++; } /* count the number of keyword only args & defaults for keyword only args */ for ( ; i < NCH(n); ++i) { ch = CHILD(n, i); if (TYPE(ch) == DOUBLESTAR) break; if (TYPE(ch) == tfpdef || TYPE(ch) == vfpdef) nkwonlyargs++; } posargs = (nposargs ? _Py_asdl_seq_new(nposargs, c->c_arena) : NULL); if (!posargs && nposargs) return NULL; kwonlyargs = (nkwonlyargs ? _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwonlyargs && nkwonlyargs) return NULL; posdefaults = (nposdefaults ? _Py_asdl_seq_new(nposdefaults, c->c_arena) : NULL); if (!posdefaults && nposdefaults) return NULL; /* The length of kwonlyargs and kwdefaults are same since we set NULL as default for keyword only argument w/o default - we have sequence data structure, but no dictionary */ kwdefaults = (nkwonlyargs ? _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwdefaults && nkwonlyargs) return NULL; /* tfpdef: NAME [':' test] vfpdef: NAME */ i = 0; j = 0; /* index for defaults */ k = 0; /* index for args */ while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case tfpdef: case vfpdef: /* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is anything other than EQUAL or a comma? */ /* XXX Should NCH(n) check be made a separate check? */ if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expr_ty expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) return NULL; assert(posdefaults != NULL); asdl_seq_SET(posdefaults, j++, expression); i += 2; found_default = 1; } else if (found_default) { ast_error(c, n, "non-default argument follows default argument"); return NULL; } arg = ast_for_arg(c, ch); if (!arg) return NULL; asdl_seq_SET(posargs, k++, arg); i += 1; /* the name */ if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA) i += 1; /* the comma, if present */ break; case STAR: if (i+1 >= NCH(n) || (i+2 == NCH(n) && (TYPE(CHILD(n, i+1)) == COMMA || TYPE(CHILD(n, i+1)) == TYPE_COMMENT))) { ast_error(c, CHILD(n, i), "named arguments must follow bare *"); return NULL; } ch = CHILD(n, i+1); /* tfpdef or COMMA */ if (TYPE(ch) == COMMA) { int res = 0; i += 2; /* now follows keyword only arguments */ if (i < NCH(n) && TYPE(CHILD(n, i)) == TYPE_COMMENT) { ast_error(c, CHILD(n, i), "bare * has associated type comment"); return NULL; } res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); if (res == -1) return NULL; i = res; /* res has new position to process */ } else { vararg = ast_for_arg(c, ch); if (!vararg) return NULL; i += 2; /* the star and the name */ if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA) i += 1; /* the comma, if present */ if (i < NCH(n) && TYPE(CHILD(n, i)) == TYPE_COMMENT) { vararg->type_comment = NEW_TYPE_COMMENT(CHILD(n, i)); if (!vararg->type_comment) return NULL; i += 1; } if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef || TYPE(CHILD(n, i)) == vfpdef)) { int res = 0; res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); if (res == -1) return NULL; i = res; /* res has new position to process */ } } break; case DOUBLESTAR: ch = CHILD(n, i+1); /* tfpdef */ assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef); kwarg = ast_for_arg(c, ch); if (!kwarg) return NULL; i += 2; /* the double star and the name */ if (TYPE(CHILD(n, i)) == COMMA) i += 1; /* the comma, if present */ break; case TYPE_COMMENT: assert(i); if (kwarg) arg = kwarg; /* arg will be equal to the last argument processed */ arg->type_comment = NEW_TYPE_COMMENT(ch); if (!arg->type_comment) return NULL; i += 1; break; default: PyErr_Format(PyExc_SystemError, "unexpected node in varargslist: %d @ %d", TYPE(ch), i); return NULL; } } return arguments(posargs, vararg, kwonlyargs, kwdefaults, kwarg, posdefaults, c->c_arena); } static expr_ty ast_for_dotted_name(struct compiling *c, const node *n) { expr_ty e; identifier id; int lineno, col_offset; int i; node *ch; REQ(n, dotted_name); lineno = LINENO(n); col_offset = n->n_col_offset; ch = CHILD(n, 0); id = NEW_IDENTIFIER(ch); if (!id) return NULL; e = Name(id, Load, lineno, col_offset, ch->n_end_lineno, ch->n_end_col_offset, c->c_arena); if (!e) return NULL; for (i = 2; i < NCH(n); i+=2) { id = NEW_IDENTIFIER(CHILD(n, i)); if (!id) return NULL; e = Attribute(e, id, Load, lineno, col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!e) return NULL; } return e; } static expr_ty ast_for_decorator(struct compiling *c, const node *n) { /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; } else if (NCH(n) == 5) { /* Call with no arguments */ d = Call(name_expr, NULL, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!d) return NULL; name_expr = NULL; } else { d = ast_for_call(c, CHILD(n, 3), name_expr, CHILD(n, 2), CHILD(n, 4)); if (!d) return NULL; name_expr = NULL; } return d; } static asdl_seq* ast_for_decorators(struct compiling *c, const node *n) { asdl_seq* decorator_seq; expr_ty d; int i; REQ(n, decorators); decorator_seq = _Py_asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) return NULL; asdl_seq_SET(decorator_seq, i, d); } return decorator_seq; } static stmt_ty ast_for_funcdef_impl(struct compiling *c, const node *n0, asdl_seq *decorator_seq, bool is_async) { /* funcdef: 'def' NAME parameters ['->' test] ':' [TYPE_COMMENT] suite */ const node * const n = is_async ? CHILD(n0, 1) : n0; identifier name; arguments_ty args; asdl_seq *body; expr_ty returns = NULL; int name_i = 1; int end_lineno, end_col_offset; node *tc; string type_comment = NULL; if (is_async && c->c_feature_version < 5) { ast_error(c, n, "Async functions are only supported in Python 3.5 and greater"); return NULL; } REQ(n, funcdef); name = NEW_IDENTIFIER(CHILD(n, name_i)); if (!name) return NULL; if (forbidden_name(c, name, CHILD(n, name_i), 0)) return NULL; args = ast_for_arguments(c, CHILD(n, name_i + 1)); if (!args) return NULL; if (TYPE(CHILD(n, name_i+2)) == RARROW) { returns = ast_for_expr(c, CHILD(n, name_i + 3)); if (!returns) return NULL; name_i += 2; } if (TYPE(CHILD(n, name_i + 3)) == TYPE_COMMENT) { type_comment = NEW_TYPE_COMMENT(CHILD(n, name_i + 3)); if (!type_comment) return NULL; name_i += 1; } body = ast_for_suite(c, CHILD(n, name_i + 3)); if (!body) return NULL; get_last_end_pos(body, &end_lineno, &end_col_offset); if (NCH(CHILD(n, name_i + 3)) > 1) { /* Check if the suite has a type comment in it. */ tc = CHILD(CHILD(n, name_i + 3), 1); if (TYPE(tc) == TYPE_COMMENT) { if (type_comment != NULL) { ast_error(c, n, "Cannot have two type comments on def"); return NULL; } type_comment = NEW_TYPE_COMMENT(tc); if (!type_comment) return NULL; } } if (is_async) return AsyncFunctionDef(name, args, body, decorator_seq, returns, type_comment, LINENO(n0), n0->n_col_offset, end_lineno, end_col_offset, c->c_arena); else return FunctionDef(name, args, body, decorator_seq, returns, type_comment, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } static stmt_ty ast_for_async_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq) { /* async_funcdef: ASYNC funcdef */ REQ(n, async_funcdef); REQ(CHILD(n, 0), ASYNC); REQ(CHILD(n, 1), funcdef); return ast_for_funcdef_impl(c, n, decorator_seq, true /* is_async */); } static stmt_ty ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq) { /* funcdef: 'def' NAME parameters ['->' test] ':' suite */ return ast_for_funcdef_impl(c, n, decorator_seq, false /* is_async */); } static stmt_ty ast_for_async_stmt(struct compiling *c, const node *n) { /* async_stmt: ASYNC (funcdef | with_stmt | for_stmt) */ REQ(n, async_stmt); REQ(CHILD(n, 0), ASYNC); switch (TYPE(CHILD(n, 1))) { case funcdef: return ast_for_funcdef_impl(c, n, NULL, true /* is_async */); case with_stmt: return ast_for_with_stmt(c, n, true /* is_async */); case for_stmt: return ast_for_for_stmt(c, n, true /* is_async */); default: PyErr_Format(PyExc_SystemError, "invalid async stament: %s", STR(CHILD(n, 1))); return NULL; } } static stmt_ty ast_for_decorated(struct compiling *c, const node *n) { /* decorated: decorators (classdef | funcdef | async_funcdef) */ stmt_ty thing = NULL; asdl_seq *decorator_seq = NULL; REQ(n, decorated); decorator_seq = ast_for_decorators(c, CHILD(n, 0)); if (!decorator_seq) return NULL; assert(TYPE(CHILD(n, 1)) == funcdef || TYPE(CHILD(n, 1)) == async_funcdef || TYPE(CHILD(n, 1)) == classdef); if (TYPE(CHILD(n, 1)) == funcdef) { thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq); } else if (TYPE(CHILD(n, 1)) == classdef) { thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq); } else if (TYPE(CHILD(n, 1)) == async_funcdef) { thing = ast_for_async_funcdef(c, CHILD(n, 1), decorator_seq); } return thing; } static expr_ty ast_for_namedexpr(struct compiling *c, const node *n) { /* if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite] namedexpr_test: test [':=' test] argument: ( test [comp_for] | test ':=' test | test '=' test | '**' test | '*' test ) */ expr_ty target, value; target = ast_for_expr(c, CHILD(n, 0)); if (!target) return NULL; value = ast_for_expr(c, CHILD(n, 2)); if (!value) return NULL; if (target->kind != Name_kind) { const char *expr_name = get_expr_name(target); if (expr_name != NULL) { ast_error(c, n, "cannot use named assignment with %s", expr_name); } return NULL; } if (!set_context(c, target, Store, n)) return NULL; return NamedExpr(target, value, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static expr_ty ast_for_lambdef(struct compiling *c, const node *n) { /* lambdef: 'lambda' [varargslist] ':' test lambdef_nocond: 'lambda' [varargslist] ':' test_nocond */ arguments_ty args; expr_ty expression; if (NCH(n) == 3) { args = arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena); if (!args) return NULL; expression = ast_for_expr(c, CHILD(n, 2)); if (!expression) return NULL; } else { args = ast_for_arguments(c, CHILD(n, 1)); if (!args) return NULL; expression = ast_for_expr(c, CHILD(n, 3)); if (!expression) return NULL; } return Lambda(args, expression, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); body = ast_for_expr(c, CHILD(n, 0)); if (!body) return NULL; expression = ast_for_expr(c, CHILD(n, 2)); if (!expression) return NULL; orelse = ast_for_expr(c, CHILD(n, 4)); if (!orelse) return NULL; return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } /* Count the number of 'for' loops in a comprehension. Helper for ast_for_comprehension(). */ static int count_comp_fors(struct compiling *c, const node *n) { int n_fors = 0; count_comp_for: n_fors++; REQ(n, comp_for); if (NCH(n) == 2) { REQ(CHILD(n, 0), ASYNC); n = CHILD(n, 1); } else if (NCH(n) == 1) { n = CHILD(n, 0); } else { goto error; } if (NCH(n) == (5)) { n = CHILD(n, 4); } else { return n_fors; } count_comp_iter: REQ(n, comp_iter); n = CHILD(n, 0); if (TYPE(n) == comp_for) goto count_comp_for; else if (TYPE(n) == comp_if) { if (NCH(n) == 3) { n = CHILD(n, 2); goto count_comp_iter; } else return n_fors; } error: /* Should never be reached */ PyErr_SetString(PyExc_SystemError, "logic error in count_comp_fors"); return -1; } /* Count the number of 'if' statements in a comprehension. Helper for ast_for_comprehension(). */ static int count_comp_ifs(struct compiling *c, const node *n) { int n_ifs = 0; while (1) { REQ(n, comp_iter); if (TYPE(CHILD(n, 0)) == comp_for) return n_ifs; n = CHILD(n, 0); REQ(n, comp_if); n_ifs++; if (NCH(n) == 2) return n_ifs; n = CHILD(n, 2); } } static asdl_seq * ast_for_comprehension(struct compiling *c, const node *n) { int i, n_fors; asdl_seq *comps; n_fors = count_comp_fors(c, n); if (n_fors == -1) return NULL; comps = _Py_asdl_seq_new(n_fors, c->c_arena); if (!comps) return NULL; for (i = 0; i < n_fors; i++) { comprehension_ty comp; asdl_seq *t; expr_ty expression, first; node *for_ch; node *sync_n; int is_async = 0; REQ(n, comp_for); if (NCH(n) == 2) { is_async = 1; REQ(CHILD(n, 0), ASYNC); sync_n = CHILD(n, 1); } else { sync_n = CHILD(n, 0); } REQ(sync_n, sync_comp_for); /* Async comprehensions only allowed in Python 3.6 and greater */ if (is_async && c->c_feature_version < 6) { ast_error(c, n, "Async comprehensions are only supported in Python 3.6 and greater"); return NULL; } for_ch = CHILD(sync_n, 1); t = ast_for_exprlist(c, for_ch, Store); if (!t) return NULL; expression = ast_for_expr(c, CHILD(sync_n, 3)); if (!expression) return NULL; /* Check the # of children rather than the length of t, since (x for x, in ...) has 1 element in t, but still requires a Tuple. */ first = (expr_ty)asdl_seq_GET(t, 0); if (NCH(for_ch) == 1) comp = comprehension(first, expression, NULL, is_async, c->c_arena); else comp = comprehension(Tuple(t, Store, first->lineno, first->col_offset, for_ch->n_end_lineno, for_ch->n_end_col_offset, c->c_arena), expression, NULL, is_async, c->c_arena); if (!comp) return NULL; if (NCH(sync_n) == 5) { int j, n_ifs; asdl_seq *ifs; n = CHILD(sync_n, 4); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) return NULL; ifs = _Py_asdl_seq_new(n_ifs, c->c_arena); if (!ifs) return NULL; for (j = 0; j < n_ifs; j++) { REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; asdl_seq_SET(ifs, j, expression); if (NCH(n) == 3) n = CHILD(n, 2); } /* on exit, must guarantee that n is a comp_for */ if (TYPE(n) == comp_iter) n = CHILD(n, 0); comp->ifs = ifs; } asdl_seq_SET(comps, i, comp); } return comps; } static expr_ty ast_for_itercomp(struct compiling *c, const node *n, int type) { /* testlist_comp: (test|star_expr) * ( comp_for | (',' (test|star_expr))* [','] ) */ expr_ty elt; asdl_seq *comps; node *ch; assert(NCH(n) > 1); ch = CHILD(n, 0); elt = ast_for_expr(c, ch); if (!elt) return NULL; if (elt->kind == Starred_kind) { ast_error(c, ch, "iterable unpacking cannot be used in comprehension"); return NULL; } comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; if (type == COMP_GENEXP) return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); else if (type == COMP_LISTCOMP) return ListComp(elt, comps, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); else if (type == COMP_SETCOMP) return SetComp(elt, comps, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); else /* Should never happen */ return NULL; } /* Fills in the key, value pair corresponding to the dict element. In case * of an unpacking, key is NULL. *i is advanced by the number of ast * elements. Iff successful, nonzero is returned. */ static int ast_for_dictelement(struct compiling *c, const node *n, int *i, expr_ty *key, expr_ty *value) { expr_ty expression; if (TYPE(CHILD(n, *i)) == DOUBLESTAR) { assert(NCH(n) - *i >= 2); expression = ast_for_expr(c, CHILD(n, *i + 1)); if (!expression) return 0; *key = NULL; *value = expression; *i += 2; } else { assert(NCH(n) - *i >= 3); expression = ast_for_expr(c, CHILD(n, *i)); if (!expression) return 0; *key = expression; REQ(CHILD(n, *i + 1), COLON); expression = ast_for_expr(c, CHILD(n, *i + 2)); if (!expression) return 0; *value = expression; *i += 3; } return 1; } static expr_ty ast_for_dictcomp(struct compiling *c, const node *n) { expr_ty key, value; asdl_seq *comps; int i = 0; if (!ast_for_dictelement(c, n, &i, &key, &value)) return NULL; assert(key); assert(NCH(n) - i >= 1); comps = ast_for_comprehension(c, CHILD(n, i)); if (!comps) return NULL; return DictComp(key, value, comps, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static expr_ty ast_for_dictdisplay(struct compiling *c, const node *n) { int i; int j; int size; asdl_seq *keys, *values; size = (NCH(n) + 1) / 3; /* +1 in case no trailing comma */ keys = _Py_asdl_seq_new(size, c->c_arena); if (!keys) return NULL; values = _Py_asdl_seq_new(size, c->c_arena); if (!values) return NULL; j = 0; for (i = 0; i < NCH(n); i++) { expr_ty key, value; if (!ast_for_dictelement(c, n, &i, &key, &value)) return NULL; asdl_seq_SET(keys, j, key); asdl_seq_SET(values, j, value); j++; } keys->size = j; values->size = j; return Dict(keys, values, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static expr_ty ast_for_genexp(struct compiling *c, const node *n) { assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument)); return ast_for_itercomp(c, n, COMP_GENEXP); } static expr_ty ast_for_listcomp(struct compiling *c, const node *n) { assert(TYPE(n) == (testlist_comp)); return ast_for_itercomp(c, n, COMP_LISTCOMP); } static expr_ty ast_for_setcomp(struct compiling *c, const node *n) { assert(TYPE(n) == (dictorsetmaker)); return ast_for_itercomp(c, n, COMP_SETCOMP); } static expr_ty ast_for_setdisplay(struct compiling *c, const node *n) { int i; int size; asdl_seq *elts; assert(TYPE(n) == (dictorsetmaker)); size = (NCH(n) + 1) / 2; /* +1 in case no trailing comma */ elts = _Py_asdl_seq_new(size, c->c_arena); if (!elts) return NULL; for (i = 0; i < NCH(n); i += 2) { expr_ty expression; expression = ast_for_expr(c, CHILD(n, i)); if (!expression) return NULL; asdl_seq_SET(elts, i / 2, expression); } return Set(elts, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static expr_ty ast_for_atom(struct compiling *c, const node *n) { /* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False' */ node *ch = CHILD(n, 0); switch (TYPE(ch)) { case NAME: { PyObject *name; const char *s = STR(ch); size_t len = strlen(s); if (len >= 4 && len <= 5) { if (!strcmp(s, "None")) return Constant(Py_None, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!strcmp(s, "True")) return Constant(Py_True, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!strcmp(s, "False")) return Constant(Py_False, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } name = new_identifier(s, c); if (!name) return NULL; /* All names start in Load context, but may later be changed. */ return Name(name, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case STRING: { expr_ty str = parsestrplus(c, n); if (!str) { const char *errtype = NULL; if (PyErr_ExceptionMatches(PyExc_UnicodeError)) errtype = "unicode error"; else if (PyErr_ExceptionMatches(PyExc_ValueError)) errtype = "value error"; if (errtype) { PyObject *type, *value, *tback, *errstr; PyErr_Fetch(&type, &value, &tback); errstr = PyObject_Str(value); if (errstr) { ast_error(c, n, "(%s) %U", errtype, errstr); Py_DECREF(errstr); } else { PyErr_Clear(); ast_error(c, n, "(%s) unknown error", errtype); } Py_DECREF(type); Py_XDECREF(value); Py_XDECREF(tback); } return NULL; } return str; } case NUMBER: { PyObject *pynum; /* Underscores in numeric literals are only allowed in Python 3.6 or greater */ /* Check for underscores here rather than in parse_number so we can report a line number on error */ if (c->c_feature_version < 6 && strchr(STR(ch), '_') != NULL) { ast_error(c, ch, "Underscores in numeric literals are only supported in Python 3.6 and greater"); return NULL; } pynum = parsenumber(c, STR(ch)); if (!pynum) return NULL; if (PyArena_AddPyObject(c->c_arena, pynum) < 0) { Py_DECREF(pynum); return NULL; } return Constant(pynum, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case ELLIPSIS: /* Ellipsis */ return Constant(Py_Ellipsis, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ if (NCH(ch) == 1) { return ast_for_testlist(c, ch); } if (TYPE(CHILD(ch, 1)) == comp_for) { return copy_location(ast_for_genexp(c, ch), n); } else { return copy_location(ast_for_testlist(c, ch), n); } case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); REQ(ch, testlist_comp); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); if (!elts) return NULL; return List(elts, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { return copy_location(ast_for_listcomp(c, ch), n); } case LBRACE: { /* dictorsetmaker: ( ((test ':' test | '**' test) * (comp_for | (',' (test ':' test | '**' test))* [','])) | * ((test | '*' test) * (comp_for | (',' (test | '*' test))* [','])) ) */ expr_ty res; ch = CHILD(n, 1); if (TYPE(ch) == RBRACE) { /* It's an empty dict. */ return Dict(NULL, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR); if (NCH(ch) == 1 || (NCH(ch) > 1 && TYPE(CHILD(ch, 1)) == COMMA)) { /* It's a set display. */ res = ast_for_setdisplay(c, ch); } else if (NCH(ch) > 1 && TYPE(CHILD(ch, 1)) == comp_for) { /* It's a set comprehension. */ res = ast_for_setcomp(c, ch); } else if (NCH(ch) > 3 - is_dict && TYPE(CHILD(ch, 3 - is_dict)) == comp_for) { /* It's a dictionary comprehension. */ if (is_dict) { ast_error(c, n, "dict unpacking cannot be used in dict comprehension"); return NULL; } res = ast_for_dictcomp(c, ch); } else { /* It's a dictionary display. */ res = ast_for_dictdisplay(c, ch); } return copy_location(res, n); } } default: PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch)); return NULL; } } static slice_ty ast_for_slice(struct compiling *c, const node *n) { node *ch; expr_ty lower = NULL, upper = NULL, step = NULL; REQ(n, subscript); /* subscript: test | [test] ':' [test] [sliceop] sliceop: ':' [test] */ ch = CHILD(n, 0); if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ step = ast_for_expr(c, ch); if (!step) return NULL; return Index(step, c->c_arena); } if (TYPE(ch) == test) { lower = ast_for_expr(c, ch); if (!lower) return NULL; } /* If there's an upper bound it's in the second or third position. */ if (TYPE(ch) == COLON) { if (NCH(n) > 1) { node *n2 = CHILD(n, 1); if (TYPE(n2) == test) { upper = ast_for_expr(c, n2); if (!upper) return NULL; } } } else if (NCH(n) > 2) { node *n2 = CHILD(n, 2); if (TYPE(n2) == test) { upper = ast_for_expr(c, n2); if (!upper) return NULL; } } ch = CHILD(n, NCH(n) - 1); if (TYPE(ch) == sliceop) { if (NCH(ch) != 1) { ch = CHILD(ch, 1); if (TYPE(ch) == test) { step = ast_for_expr(c, ch); if (!step) return NULL; } } } return Slice(lower, upper, step, c->c_arena); } static expr_ty ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ int i, nops; expr_ty expr1, expr2, result; operator_ty newoperator; expr1 = ast_for_expr(c, CHILD(n, 0)); if (!expr1) return NULL; expr2 = ast_for_expr(c, CHILD(n, 2)); if (!expr2) return NULL; newoperator = get_operator(c, CHILD(n, 1)); if (!newoperator) return NULL; result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, CHILD(n, 2)->n_end_lineno, CHILD(n, 2)->n_end_col_offset, c->c_arena); if (!result) return NULL; nops = (NCH(n) - 1) / 2; for (i = 1; i < nops; i++) { expr_ty tmp_result, tmp; const node* next_oper = CHILD(n, i * 2 + 1); newoperator = get_operator(c, next_oper); if (!newoperator) return NULL; tmp = ast_for_expr(c, CHILD(n, i * 2 + 2)); if (!tmp) return NULL; tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, CHILD(n, i * 2 + 2)->n_end_lineno, CHILD(n, i * 2 + 2)->n_end_col_offset, c->c_arena); if (!tmp_result) return NULL; result = tmp_result; } return result; } static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ const node *n_copy = n; REQ(n, trailer); if (TYPE(CHILD(n, 0)) == LPAR) { if (NCH(n) == 2) return Call(left_expr, NULL, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); else return ast_for_call(c, CHILD(n, 1), left_expr, CHILD(n, 0), CHILD(n, 2)); } else if (TYPE(CHILD(n, 0)) == DOT) { PyObject *attr_id = NEW_IDENTIFIER(CHILD(n, 1)); if (!attr_id) return NULL; return Attribute(left_expr, attr_id, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { REQ(CHILD(n, 0), LSQB); REQ(CHILD(n, 2), RSQB); n = CHILD(n, 1); if (NCH(n) == 1) { slice_ty slc = ast_for_slice(c, CHILD(n, 0)); if (!slc) return NULL; return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset, n_copy->n_end_lineno, n_copy->n_end_col_offset, c->c_arena); } else { /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ Py_ssize_t j; slice_ty slc; expr_ty e; int simple = 1; asdl_seq *slices, *elts; slices = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!slices) return NULL; for (j = 0; j < NCH(n); j += 2) { slc = ast_for_slice(c, CHILD(n, j)); if (!slc) return NULL; if (slc->kind != Index_kind) simple = 0; asdl_seq_SET(slices, j / 2, slc); } if (!simple) { return Subscript(left_expr, ExtSlice(slices, c->c_arena), Load, LINENO(n), n->n_col_offset, n_copy->n_end_lineno, n_copy->n_end_col_offset, c->c_arena); } /* extract Index values and put them in a Tuple */ elts = _Py_asdl_seq_new(asdl_seq_LEN(slices), c->c_arena); if (!elts) return NULL; for (j = 0; j < asdl_seq_LEN(slices); ++j) { slc = (slice_ty)asdl_seq_GET(slices, j); assert(slc->kind == Index_kind && slc->v.Index.value); asdl_seq_SET(elts, j, slc->v.Index.value); } e = Tuple(elts, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!e) return NULL; return Subscript(left_expr, Index(e, c->c_arena), Load, LINENO(n), n->n_col_offset, n_copy->n_end_lineno, n_copy->n_end_col_offset, c->c_arena); } } } static expr_ty ast_for_factor(struct compiling *c, const node *n) { expr_ty expression; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; switch (TYPE(CHILD(n, 0))) { case PLUS: return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case MINUS: return UnaryOp(USub, expression, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case TILDE: return UnaryOp(Invert, expression, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unhandled factor: %d", TYPE(CHILD(n, 0))); return NULL; } static expr_ty ast_for_atom_expr(struct compiling *c, const node *n) { int i, nch, start = 0; expr_ty e, tmp; REQ(n, atom_expr); nch = NCH(n); if (TYPE(CHILD(n, 0)) == AWAIT) { if (c->c_feature_version < 5) { ast_error(c, n, "Await expressions are only supported in Python 3.5 and greater"); return NULL; } start = 1; assert(nch > 1); } e = ast_for_atom(c, CHILD(n, start)); if (!e) return NULL; if (nch == 1) return e; if (start && nch == 2) { return Await(e, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } for (i = start + 1; i < nch; i++) { node *ch = CHILD(n, i); if (TYPE(ch) != trailer) break; tmp = ast_for_trailer(c, ch, e); if (!tmp) return NULL; tmp->lineno = e->lineno; tmp->col_offset = e->col_offset; e = tmp; } if (start) { /* there was an 'await' */ return Await(e, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { return e; } } static expr_ty ast_for_power(struct compiling *c, const node *n) { /* power: atom trailer* ('**' factor)* */ expr_ty e; REQ(n, power); e = ast_for_atom_expr(c, CHILD(n, 0)); if (!e) return NULL; if (NCH(n) == 1) return e; if (TYPE(CHILD(n, NCH(n) - 1)) == factor) { expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1)); if (!f) return NULL; e = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } return e; } static expr_ty ast_for_starred(struct compiling *c, const node *n) { expr_ty tmp; REQ(n, star_expr); tmp = ast_for_expr(c, CHILD(n, 1)); if (!tmp) return NULL; /* The Load context is changed later. */ return Starred(tmp, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } /* Do not name a variable 'expr'! Will cause a compile error. */ static expr_ty ast_for_expr(struct compiling *c, const node *n) { /* handle the full range of simple expressions namedexpr_test: test [':=' test] test: or_test ['if' or_test 'else' test] | lambdef test_nocond: or_test | lambdef_nocond or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* expr: xor_expr ('|' xor_expr)* xor_expr: and_expr ('^' and_expr)* and_expr: shift_expr ('&' shift_expr)* shift_expr: arith_expr (('<<'|'>>') arith_expr)* arith_expr: term (('+'|'-') term)* term: factor (('*'|'@'|'/'|'%'|'//') factor)* factor: ('+'|'-'|'~') factor | power power: atom_expr ['**' factor] atom_expr: [AWAIT] atom trailer* yield_expr: 'yield' [yield_arg] */ asdl_seq *seq; int i; loop: switch (TYPE(n)) { case namedexpr_test: if (NCH(n) == 3) return ast_for_namedexpr(c, n); /* Fallthrough */ case test: case test_nocond: if (TYPE(CHILD(n, 0)) == lambdef || TYPE(CHILD(n, 0)) == lambdef_nocond) return ast_for_lambdef(c, CHILD(n, 0)); else if (NCH(n) > 1) return ast_for_ifexpr(c, n); /* Fallthrough */ case or_test: case and_test: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) return NULL; for (i = 0; i < NCH(n); i += 2) { expr_ty e = ast_for_expr(c, CHILD(n, i)); if (!e) return NULL; asdl_seq_SET(seq, i / 2, e); } if (!strcmp(STR(CHILD(n, 1)), "and")) return BoolOp(And, seq, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); assert(!strcmp(STR(CHILD(n, 1)), "or")); return BoolOp(Or, seq, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case not_test: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } else { expr_ty expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; return UnaryOp(Not, expression, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case comparison: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } else { expr_ty expression; asdl_int_seq *ops; asdl_seq *cmps; ops = _Py_asdl_int_seq_new(NCH(n) / 2, c->c_arena); if (!ops) return NULL; cmps = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!cmps) { return NULL; } for (i = 1; i < NCH(n); i += 2) { cmpop_ty newoperator; newoperator = ast_for_comp_op(c, CHILD(n, i)); if (!newoperator) { return NULL; } expression = ast_for_expr(c, CHILD(n, i + 1)); if (!expression) { return NULL; } asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } expression = ast_for_expr(c, CHILD(n, 0)); if (!expression) { return NULL; } return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } break; case star_expr: return ast_for_starred(c, n); /* The next five cases all handle BinOps. The main body of code is the same in each case, but the switch turned inside out to reuse the code for each type of operator. */ case expr: case xor_expr: case and_expr: case shift_expr: case arith_expr: case term: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } return ast_for_binop(c, n); case yield_expr: { node *an = NULL; node *en = NULL; int is_from = 0; expr_ty exp = NULL; if (NCH(n) > 1) an = CHILD(n, 1); /* yield_arg */ if (an) { en = CHILD(an, NCH(an) - 1); if (NCH(an) == 2) { is_from = 1; exp = ast_for_expr(c, en); } else exp = ast_for_testlist(c, en); if (!exp) return NULL; } if (is_from) return YieldFrom(exp, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); return Yield(exp, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case factor: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } return ast_for_factor(c, n); case power: return ast_for_power(c, n); default: PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n)); return NULL; } /* should never get here unless if error is set */ return NULL; } static expr_ty ast_for_call(struct compiling *c, const node *n, expr_ty func, const node *maybegenbeg, const node *closepar) { /* arglist: argument (',' argument)* [','] argument: ( test [comp_for] | '*' test | test '=' test | '**' test ) */ int i, nargs, nkeywords; int ndoublestars; asdl_seq *args; asdl_seq *keywords; REQ(n, arglist); nargs = 0; nkeywords = 0; for (i = 0; i < NCH(n); i++) { node *ch = CHILD(n, i); if (TYPE(ch) == argument) { if (NCH(ch) == 1) nargs++; else if (TYPE(CHILD(ch, 1)) == comp_for) { nargs++; if (!maybegenbeg) { ast_error(c, ch, "invalid syntax"); return NULL; } if (NCH(n) > 1) { ast_error(c, ch, "Generator expression must be parenthesized"); return NULL; } } else if (TYPE(CHILD(ch, 0)) == STAR) nargs++; else if (TYPE(CHILD(ch, 1)) == COLONEQUAL) { nargs++; } else /* TYPE(CHILD(ch, 0)) == DOUBLESTAR or keyword argument */ nkeywords++; } } args = _Py_asdl_seq_new(nargs, c->c_arena); if (!args) return NULL; keywords = _Py_asdl_seq_new(nkeywords, c->c_arena); if (!keywords) return NULL; nargs = 0; /* positional arguments + iterable argument unpackings */ nkeywords = 0; /* keyword arguments + keyword argument unpackings */ ndoublestars = 0; /* just keyword argument unpackings */ for (i = 0; i < NCH(n); i++) { node *ch = CHILD(n, i); if (TYPE(ch) == argument) { expr_ty e; node *chch = CHILD(ch, 0); if (NCH(ch) == 1) { /* a positional argument */ if (nkeywords) { if (ndoublestars) { ast_error(c, chch, "positional argument follows " "keyword argument unpacking"); } else { ast_error(c, chch, "positional argument follows " "keyword argument"); } return NULL; } e = ast_for_expr(c, chch); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else if (TYPE(chch) == STAR) { /* an iterable argument unpacking */ expr_ty starred; if (ndoublestars) { ast_error(c, chch, "iterable argument unpacking follows " "keyword argument unpacking"); return NULL; } e = ast_for_expr(c, CHILD(ch, 1)); if (!e) return NULL; starred = Starred(e, Load, LINENO(chch), chch->n_col_offset, chch->n_end_lineno, chch->n_end_col_offset, c->c_arena); if (!starred) return NULL; asdl_seq_SET(args, nargs++, starred); } else if (TYPE(chch) == DOUBLESTAR) { /* a keyword argument unpacking */ keyword_ty kw; i++; e = ast_for_expr(c, CHILD(ch, 1)); if (!e) return NULL; kw = keyword(NULL, e, c->c_arena); asdl_seq_SET(keywords, nkeywords++, kw); ndoublestars++; } else if (TYPE(CHILD(ch, 1)) == comp_for) { /* the lone generator expression */ e = copy_location(ast_for_genexp(c, ch), maybegenbeg); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else if (TYPE(CHILD(ch, 1)) == COLONEQUAL) { /* treat colon equal as positional argument */ if (nkeywords) { if (ndoublestars) { ast_error(c, chch, "positional argument follows " "keyword argument unpacking"); } else { ast_error(c, chch, "positional argument follows " "keyword argument"); } return NULL; } e = ast_for_namedexpr(c, ch); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else { /* a keyword argument */ keyword_ty kw; identifier key, tmp; int k; // To remain LL(1), the grammar accepts any test (basically, any // expression) in the keyword slot of a call site. So, we need // to manually enforce that the keyword is a NAME here. static const int name_tree[] = { test, or_test, and_test, not_test, comparison, expr, xor_expr, and_expr, shift_expr, arith_expr, term, factor, power, atom_expr, atom, 0, }; node *expr_node = chch; for (int i = 0; name_tree[i]; i++) { if (TYPE(expr_node) != name_tree[i]) break; if (NCH(expr_node) != 1) break; expr_node = CHILD(expr_node, 0); } if (TYPE(expr_node) != NAME) { ast_error(c, chch, "expression cannot contain assignment, " "perhaps you meant \"==\"?"); return NULL; } key = new_identifier(STR(expr_node), c); if (key == NULL) { return NULL; } if (forbidden_name(c, key, chch, 1)) { return NULL; } for (k = 0; k < nkeywords; k++) { tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg; if (tmp && !PyUnicode_Compare(tmp, key)) { ast_error(c, chch, "keyword argument repeated"); return NULL; } } e = ast_for_expr(c, CHILD(ch, 2)); if (!e) return NULL; kw = keyword(key, e, c->c_arena); if (!kw) return NULL; asdl_seq_SET(keywords, nkeywords++, kw); } } } return Call(func, args, keywords, func->lineno, func->col_offset, closepar->n_end_lineno, closepar->n_end_col_offset, c->c_arena); } static expr_ty ast_for_testlist(struct compiling *c, const node* n) { /* testlist_comp: test (comp_for | (',' test)* [',']) */ /* testlist: test (',' test)* [','] */ assert(NCH(n) > 0); if (TYPE(n) == testlist_comp) { if (NCH(n) > 1) assert(TYPE(CHILD(n, 1)) != comp_for); } else { assert(TYPE(n) == testlist || TYPE(n) == testlist_star_expr); } if (NCH(n) == 1) return ast_for_expr(c, CHILD(n, 0)); else { asdl_seq *tmp = seq_for_testlist(c, n); if (!tmp) return NULL; return Tuple(tmp, Load, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } } static stmt_ty ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); /* expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) | [('=' (yield_expr|testlist_star_expr))+ [TYPE_COMMENT]] ) annassign: ':' test ['=' (yield_expr|testlist)] testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=') test: ... here starts the operator precedence dance */ int num = NCH(n); if (num == 1) { expr_ty e = ast_for_testlist(c, CHILD(n, 0)); if (!e) return NULL; return Expr(e, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else if (TYPE(CHILD(n, 1)) == augassign) { expr_ty expr1, expr2; operator_ty newoperator; node *ch = CHILD(n, 0); expr1 = ast_for_testlist(c, ch); if (!expr1) return NULL; if(!set_context(c, expr1, Store, ch)) return NULL; /* set_context checks that most expressions are not the left side. Augmented assignments can only have a name, a subscript, or an attribute on the left, though, so we have to explicitly check for those. */ switch (expr1->kind) { case Name_kind: case Attribute_kind: case Subscript_kind: break; default: ast_error(c, ch, "illegal expression for augmented assignment"); return NULL; } ch = CHILD(n, 2); if (TYPE(ch) == testlist) expr2 = ast_for_testlist(c, ch); else expr2 = ast_for_expr(c, ch); if (!expr2) return NULL; newoperator = ast_for_augassign(c, CHILD(n, 1)); if (!newoperator) return NULL; return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else if (TYPE(CHILD(n, 1)) == annassign) { expr_ty expr1, expr2, expr3; node *ch = CHILD(n, 0); node *deep, *ann = CHILD(n, 1); int simple = 1; /* AnnAssigns are only allowed in Python 3.6 or greater */ if (c->c_feature_version < 6) { ast_error(c, ch, "Variable annotation syntax is only supported in Python 3.6 and greater"); return NULL; } /* we keep track of parens to qualify (x) as expression not name */ deep = ch; while (NCH(deep) == 1) { deep = CHILD(deep, 0); } if (NCH(deep) > 0 && TYPE(CHILD(deep, 0)) == LPAR) { simple = 0; } expr1 = ast_for_testlist(c, ch); if (!expr1) { return NULL; } switch (expr1->kind) { case Name_kind: if (forbidden_name(c, expr1->v.Name.id, n, 0)) { return NULL; } expr1->v.Name.ctx = Store; break; case Attribute_kind: if (forbidden_name(c, expr1->v.Attribute.attr, n, 1)) { return NULL; } expr1->v.Attribute.ctx = Store; break; case Subscript_kind: expr1->v.Subscript.ctx = Store; break; case List_kind: ast_error(c, ch, "only single target (not list) can be annotated"); return NULL; case Tuple_kind: ast_error(c, ch, "only single target (not tuple) can be annotated"); return NULL; default: ast_error(c, ch, "illegal target for annotation"); return NULL; } if (expr1->kind != Name_kind) { simple = 0; } ch = CHILD(ann, 1); expr2 = ast_for_expr(c, ch); if (!expr2) { return NULL; } if (NCH(ann) == 2) { return AnnAssign(expr1, expr2, NULL, simple, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else { ch = CHILD(ann, 3); if (TYPE(ch) == testlist) { expr3 = ast_for_testlist(c, ch); } else { expr3 = ast_for_expr(c, ch); } if (!expr3) { return NULL; } return AnnAssign(expr1, expr2, expr3, simple, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } } else { int i, nch_minus_type, has_type_comment; asdl_seq *targets; node *value; expr_ty expression; string type_comment; /* a normal assignment */ REQ(CHILD(n, 1), EQUAL); has_type_comment = TYPE(CHILD(n, num - 1)) == TYPE_COMMENT; nch_minus_type = num - has_type_comment; targets = _Py_asdl_seq_new(nch_minus_type / 2, c->c_arena); if (!targets) return NULL; for (i = 0; i < nch_minus_type - 2; i += 2) { expr_ty e; node *ch = CHILD(n, i); if (TYPE(ch) == yield_expr) { ast_error(c, ch, "assignment to yield expression not possible"); return NULL; } e = ast_for_testlist(c, ch); if (!e) return NULL; /* set context to assign */ if (!set_context(c, e, Store, CHILD(n, i))) return NULL; asdl_seq_SET(targets, i / 2, e); } value = CHILD(n, nch_minus_type - 1); if (TYPE(value) == testlist_star_expr) expression = ast_for_testlist(c, value); else expression = ast_for_expr(c, value); if (!expression) return NULL; if (has_type_comment) { type_comment = NEW_TYPE_COMMENT(CHILD(n, nch_minus_type)); if (!type_comment) return NULL; } else type_comment = NULL; return Assign(targets, expression, type_comment, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } } static asdl_seq * ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context) { asdl_seq *seq; int i; expr_ty e; REQ(n, exprlist); seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) return NULL; for (i = 0; i < NCH(n); i += 2) { e = ast_for_expr(c, CHILD(n, i)); if (!e) return NULL; asdl_seq_SET(seq, i / 2, e); if (context && !set_context(c, e, context, CHILD(n, i))) return NULL; } return seq; } static stmt_ty ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); expr_list = ast_for_exprlist(c, CHILD(n, 1), Del); if (!expr_list) return NULL; return Delete(expr_list, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static stmt_ty ast_for_flow_stmt(struct compiling *c, const node *n) { /* flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt break_stmt: 'break' continue_stmt: 'continue' return_stmt: 'return' [testlist] yield_stmt: yield_expr yield_expr: 'yield' testlist | 'yield' 'from' test raise_stmt: 'raise' [test [',' test [',' test]]] */ node *ch; REQ(n, flow_stmt); ch = CHILD(n, 0); switch (TYPE(ch)) { case break_stmt: return Break(LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case continue_stmt: return Continue(LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case yield_stmt: { /* will reduce to yield_expr */ expr_ty exp = ast_for_expr(c, CHILD(ch, 0)); if (!exp) return NULL; return Expr(exp, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case return_stmt: if (NCH(ch) == 1) return Return(NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); else { expr_ty expression = ast_for_testlist(c, CHILD(ch, 1)); if (!expression) return NULL; return Return(expression, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } case raise_stmt: if (NCH(ch) == 1) return Raise(NULL, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); else if (NCH(ch) >= 2) { expr_ty cause = NULL; expr_ty expression = ast_for_expr(c, CHILD(ch, 1)); if (!expression) return NULL; if (NCH(ch) == 4) { cause = ast_for_expr(c, CHILD(ch, 3)); if (!cause) return NULL; } return Raise(expression, cause, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } /* fall through */ default: PyErr_Format(PyExc_SystemError, "unexpected flow_stmt: %d", TYPE(ch)); return NULL; } } static alias_ty alias_for_import_name(struct compiling *c, const node *n, int store) { /* import_as_name: NAME ['as' NAME] dotted_as_name: dotted_name ['as' NAME] dotted_name: NAME ('.' NAME)* */ identifier str, name; loop: switch (TYPE(n)) { case import_as_name: { node *name_node = CHILD(n, 0); str = NULL; name = NEW_IDENTIFIER(name_node); if (!name) return NULL; if (NCH(n) == 3) { node *str_node = CHILD(n, 2); str = NEW_IDENTIFIER(str_node); if (!str) return NULL; if (store && forbidden_name(c, str, str_node, 0)) return NULL; } else { if (forbidden_name(c, name, name_node, 0)) return NULL; } return alias(name, str, c->c_arena); } case dotted_as_name: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } else { node *asname_node = CHILD(n, 2); alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0); if (!a) return NULL; assert(!a->asname); a->asname = NEW_IDENTIFIER(asname_node); if (!a->asname) return NULL; if (forbidden_name(c, a->asname, asname_node, 0)) return NULL; return a; } break; case dotted_name: if (NCH(n) == 1) { node *name_node = CHILD(n, 0); name = NEW_IDENTIFIER(name_node); if (!name) return NULL; if (store && forbidden_name(c, name, name_node, 0)) return NULL; return alias(name, NULL, c->c_arena); } else { /* Create a string of the form "a.b.c" */ int i; size_t len; char *s; PyObject *uni; len = 0; for (i = 0; i < NCH(n); i += 2) /* length of string plus one for the dot */ len += strlen(STR(CHILD(n, i))) + 1; len--; /* the last name doesn't have a dot */ str = PyBytes_FromStringAndSize(NULL, len); if (!str) return NULL; s = PyBytes_AS_STRING(str); if (!s) return NULL; for (i = 0; i < NCH(n); i += 2) { char *sch = STR(CHILD(n, i)); strcpy(s, STR(CHILD(n, i))); s += strlen(sch); *s++ = '.'; } --s; *s = '\0'; uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL); Py_DECREF(str); if (!uni) return NULL; str = uni; PyUnicode_InternInPlace(&str); if (PyArena_AddPyObject(c->c_arena, str) < 0) { Py_DECREF(str); return NULL; } return alias(str, NULL, c->c_arena); } break; case STAR: str = PyUnicode_InternFromString("*"); if (!str) return NULL; if (PyArena_AddPyObject(c->c_arena, str) < 0) { Py_DECREF(str); return NULL; } return alias(str, NULL, c->c_arena); default: PyErr_Format(PyExc_SystemError, "unexpected import name: %d", TYPE(n)); return NULL; } PyErr_SetString(PyExc_SystemError, "unhandled import name condition"); return NULL; } static stmt_ty ast_for_import_stmt(struct compiling *c, const node *n) { /* import_stmt: import_name | import_from import_name: 'import' dotted_as_names import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+) 'import' ('*' | '(' import_as_names ')' | import_as_names) */ int lineno; int col_offset; int i; asdl_seq *aliases; REQ(n, import_stmt); lineno = LINENO(n); col_offset = n->n_col_offset; n = CHILD(n, 0); if (TYPE(n) == import_name) { n = CHILD(n, 1); REQ(n, dotted_as_names); aliases = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!aliases) return NULL; for (i = 0; i < NCH(n); i += 2) { alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, i / 2, import_alias); } // Even though n is modified above, the end position is not changed return Import(aliases, lineno, col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else if (TYPE(n) == import_from) { int n_children; int idx, ndots = 0; const node *n_copy = n; alias_ty mod = NULL; identifier modname = NULL; /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { if (TYPE(CHILD(n, idx)) == dotted_name) { mod = alias_for_import_name(c, CHILD(n, idx), 0); if (!mod) return NULL; idx++; break; } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) { /* three consecutive dots are tokenized as one ELLIPSIS */ ndots += 3; continue; } else if (TYPE(CHILD(n, idx)) != DOT) { break; } ndots++; } idx++; /* skip over the 'import' keyword */ switch (TYPE(CHILD(n, idx))) { case STAR: /* from ... import * */ n = CHILD(n, idx); n_children = 1; break; case LPAR: /* from ... import (x, y, z) */ n = CHILD(n, idx + 1); n_children = NCH(n); break; case import_as_names: /* from ... import x, y, z */ n = CHILD(n, idx); n_children = NCH(n); if (n_children % 2 == 0) { ast_error(c, n, "trailing comma not allowed without" " surrounding parentheses"); return NULL; } break; default: ast_error(c, n, "Unexpected node-type in from-import"); return NULL; } aliases = _Py_asdl_seq_new((n_children + 1) / 2, c->c_arena); if (!aliases) return NULL; /* handle "from ... import *" special b/c there's no children */ if (TYPE(n) == STAR) { alias_ty import_alias = alias_for_import_name(c, n, 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, 0, import_alias); } else { for (i = 0; i < NCH(n); i += 2) { alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, i / 2, import_alias); } } if (mod != NULL) modname = mod->name; return ImportFrom(modname, aliases, ndots, lineno, col_offset, n_copy->n_end_lineno, n_copy->n_end_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unknown import statement: starts with command '%s'", STR(CHILD(n, 0))); return NULL; } static stmt_ty ast_for_global_stmt(struct compiling *c, const node *n) { /* global_stmt: 'global' NAME (',' NAME)* */ identifier name; asdl_seq *s; int i; REQ(n, global_stmt); s = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!s) return NULL; for (i = 1; i < NCH(n); i += 2) { name = NEW_IDENTIFIER(CHILD(n, i)); if (!name) return NULL; asdl_seq_SET(s, i / 2, name); } return Global(s, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static stmt_ty ast_for_nonlocal_stmt(struct compiling *c, const node *n) { /* nonlocal_stmt: 'nonlocal' NAME (',' NAME)* */ identifier name; asdl_seq *s; int i; REQ(n, nonlocal_stmt); s = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!s) return NULL; for (i = 1; i < NCH(n); i += 2) { name = NEW_IDENTIFIER(CHILD(n, i)); if (!name) return NULL; asdl_seq_SET(s, i / 2, name); } return Nonlocal(s, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } static stmt_ty ast_for_assert_stmt(struct compiling *c, const node *n) { /* assert_stmt: 'assert' test [',' test] */ REQ(n, assert_stmt); if (NCH(n) == 2) { expr_ty expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; return Assert(expression, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } else if (NCH(n) == 4) { expr_ty expr1, expr2; expr1 = ast_for_expr(c, CHILD(n, 1)); if (!expr1) return NULL; expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; return Assert(expr1, expr2, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "improper number of parts to 'assert' statement: %d", NCH(n)); return NULL; } static asdl_seq * ast_for_suite(struct compiling *c, const node *n) { /* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */ asdl_seq *seq; stmt_ty s; int i, total, num, end, pos = 0; node *ch; if (TYPE(n) != func_body_suite) { REQ(n, suite); } total = num_stmts(n); seq = _Py_asdl_seq_new(total, c->c_arena); if (!seq) return NULL; if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) end--; /* loop by 2 to skip semi-colons */ for (i = 0; i < end; i += 2) { ch = CHILD(n, i); s = ast_for_stmt(c, ch); if (!s) return NULL; asdl_seq_SET(seq, pos++, s); } } else { i = 2; if (TYPE(CHILD(n, 1)) == TYPE_COMMENT) { i += 2; REQ(CHILD(n, 2), NEWLINE); } for (; i < (NCH(n) - 1); i++) { ch = CHILD(n, i); REQ(ch, stmt); num = num_stmts(ch); if (num == 1) { /* small_stmt or compound_stmt with only one child */ s = ast_for_stmt(c, ch); if (!s) return NULL; asdl_seq_SET(seq, pos++, s); } else { int j; ch = CHILD(ch, 0); REQ(ch, simple_stmt); for (j = 0; j < NCH(ch); j += 2) { /* statement terminates with a semi-colon ';' */ if (NCH(CHILD(ch, j)) == 0) { assert((j + 1) == NCH(ch)); break; } s = ast_for_stmt(c, CHILD(ch, j)); if (!s) return NULL; asdl_seq_SET(seq, pos++, s); } } } } assert(pos == seq->size); return seq; } static void get_last_end_pos(asdl_seq *s, int *end_lineno, int *end_col_offset) { Py_ssize_t tot = asdl_seq_LEN(s); // There must be no empty suites. assert(tot > 0); stmt_ty last = asdl_seq_GET(s, tot - 1); *end_lineno = last->end_lineno; *end_col_offset = last->end_col_offset; } static stmt_ty ast_for_if_stmt(struct compiling *c, const node *n) { /* if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */ char *s; int end_lineno, end_col_offset; REQ(n, if_stmt); if (NCH(n) == 4) { expr_ty expression; asdl_seq *suite_seq; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } s = STR(CHILD(n, 4)); /* s[2], the third character in the string, will be 's' for el_s_e, or 'i' for el_i_f */ if (s[2] == 's') { expr_ty expression; asdl_seq *seq1, *seq2; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; seq1 = ast_for_suite(c, CHILD(n, 3)); if (!seq1) return NULL; seq2 = ast_for_suite(c, CHILD(n, 6)); if (!seq2) return NULL; get_last_end_pos(seq2, &end_lineno, &end_col_offset); return If(expression, seq1, seq2, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } else if (s[2] == 'i') { int i, n_elif, has_else = 0; expr_ty expression; asdl_seq *suite_seq; asdl_seq *orelse = NULL; n_elif = NCH(n) - 4; /* must reference the child n_elif+1 since 'else' token is third, not fourth, child from the end. */ if (TYPE(CHILD(n, (n_elif + 1))) == NAME && STR(CHILD(n, (n_elif + 1)))[2] == 's') { has_else = 1; n_elif -= 3; } n_elif /= 4; if (has_else) { asdl_seq *suite_seq2; orelse = _Py_asdl_seq_new(1, c->c_arena); if (!orelse) return NULL; expression = ast_for_expr(c, CHILD(n, NCH(n) - 6)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4)); if (!suite_seq) return NULL; suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1)); if (!suite_seq2) return NULL; get_last_end_pos(suite_seq2, &end_lineno, &end_col_offset); asdl_seq_SET(orelse, 0, If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, end_lineno, end_col_offset, c->c_arena)); /* the just-created orelse handled the last elif */ n_elif--; } for (i = 0; i < n_elif; i++) { int off = 5 + (n_elif - i - 1) * 4; asdl_seq *newobj = _Py_asdl_seq_new(1, c->c_arena); if (!newobj) return NULL; expression = ast_for_expr(c, CHILD(n, off)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, off + 2)); if (!suite_seq) return NULL; if (orelse != NULL) { get_last_end_pos(orelse, &end_lineno, &end_col_offset); } else { get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); } asdl_seq_SET(newobj, 0, If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, end_lineno, end_col_offset, c->c_arena)); orelse = newobj; } expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; get_last_end_pos(orelse, &end_lineno, &end_col_offset); return If(expression, suite_seq, orelse, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unexpected token in 'if' statement: %s", s); return NULL; } static stmt_ty ast_for_while_stmt(struct compiling *c, const node *n) { /* while_stmt: 'while' test ':' suite ['else' ':' suite] */ REQ(n, while_stmt); int end_lineno, end_col_offset; if (NCH(n) == 4) { expr_ty expression; asdl_seq *suite_seq; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } else if (NCH(n) == 7) { expr_ty expression; asdl_seq *seq1, *seq2; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; seq1 = ast_for_suite(c, CHILD(n, 3)); if (!seq1) return NULL; seq2 = ast_for_suite(c, CHILD(n, 6)); if (!seq2) return NULL; get_last_end_pos(seq2, &end_lineno, &end_col_offset); return While(expression, seq1, seq2, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "wrong number of tokens for 'while' statement: %d", NCH(n)); return NULL; } static stmt_ty ast_for_for_stmt(struct compiling *c, const node *n0, bool is_async) { const node * const n = is_async ? CHILD(n0, 1) : n0; asdl_seq *_target, *seq = NULL, *suite_seq; expr_ty expression; expr_ty target, first; const node *node_target; int end_lineno, end_col_offset; int has_type_comment; string type_comment; if (is_async && c->c_feature_version < 5) { ast_error(c, n, "Async for loops are only supported in Python 3.5 and greater"); return NULL; } /* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */ REQ(n, for_stmt); has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT; if (NCH(n) == 9 + has_type_comment) { seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment)); if (!seq) return NULL; } node_target = CHILD(n, 1); _target = ast_for_exprlist(c, node_target, Store); if (!_target) return NULL; /* Check the # of children rather than the length of _target, since for x, in ... has 1 element in _target, but still requires a Tuple. */ first = (expr_ty)asdl_seq_GET(_target, 0); if (NCH(node_target) == 1) target = first; else target = Tuple(_target, Store, first->lineno, first->col_offset, node_target->n_end_lineno, node_target->n_end_col_offset, c->c_arena); expression = ast_for_testlist(c, CHILD(n, 3)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment)); if (!suite_seq) return NULL; if (seq != NULL) { get_last_end_pos(seq, &end_lineno, &end_col_offset); } else { get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); } if (has_type_comment) { type_comment = NEW_TYPE_COMMENT(CHILD(n, 5)); if (!type_comment) return NULL; } else type_comment = NULL; if (is_async) return AsyncFor(target, expression, suite_seq, seq, type_comment, LINENO(n0), n0->n_col_offset, end_lineno, end_col_offset, c->c_arena); else return For(target, expression, suite_seq, seq, type_comment, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } static excepthandler_ty ast_for_except_clause(struct compiling *c, const node *exc, node *body) { /* except_clause: 'except' [test ['as' test]] */ int end_lineno, end_col_offset; REQ(exc, except_clause); REQ(body, suite); if (NCH(exc) == 1) { asdl_seq *suite_seq = ast_for_suite(c, body); if (!suite_seq) return NULL; get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc), exc->n_col_offset, end_lineno, end_col_offset, c->c_arena); } else if (NCH(exc) == 2) { expr_ty expression; asdl_seq *suite_seq; expression = ast_for_expr(c, CHILD(exc, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, body); if (!suite_seq) return NULL; get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); return ExceptHandler(expression, NULL, suite_seq, LINENO(exc), exc->n_col_offset, end_lineno, end_col_offset, c->c_arena); } else if (NCH(exc) == 4) { asdl_seq *suite_seq; expr_ty expression; identifier e = NEW_IDENTIFIER(CHILD(exc, 3)); if (!e) return NULL; if (forbidden_name(c, e, CHILD(exc, 3), 0)) return NULL; expression = ast_for_expr(c, CHILD(exc, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, body); if (!suite_seq) return NULL; get_last_end_pos(suite_seq, &end_lineno, &end_col_offset); return ExceptHandler(expression, e, suite_seq, LINENO(exc), exc->n_col_offset, end_lineno, end_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "wrong number of children for 'except' clause: %d", NCH(exc)); return NULL; } static stmt_ty ast_for_try_stmt(struct compiling *c, const node *n) { const int nch = NCH(n); int end_lineno, end_col_offset, n_except = (nch - 3)/3; asdl_seq *body, *handlers = NULL, *orelse = NULL, *finally = NULL; excepthandler_ty last_handler; REQ(n, try_stmt); body = ast_for_suite(c, CHILD(n, 2)); if (body == NULL) return NULL; if (TYPE(CHILD(n, nch - 3)) == NAME) { if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) { if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) { /* we can assume it's an "else", because nch >= 9 for try-else-finally and it would otherwise have a type of except_clause */ orelse = ast_for_suite(c, CHILD(n, nch - 4)); if (orelse == NULL) return NULL; n_except--; } finally = ast_for_suite(c, CHILD(n, nch - 1)); if (finally == NULL) return NULL; n_except--; } else { /* we can assume it's an "else", otherwise it would have a type of except_clause */ orelse = ast_for_suite(c, CHILD(n, nch - 1)); if (orelse == NULL) return NULL; n_except--; } } else if (TYPE(CHILD(n, nch - 3)) != except_clause) { ast_error(c, n, "malformed 'try' statement"); return NULL; } if (n_except > 0) { int i; /* process except statements to create a try ... except */ handlers = _Py_asdl_seq_new(n_except, c->c_arena); if (handlers == NULL) return NULL; for (i = 0; i < n_except; i++) { excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3), CHILD(n, 5 + i * 3)); if (!e) return NULL; asdl_seq_SET(handlers, i, e); } } assert(finally != NULL || asdl_seq_LEN(handlers)); if (finally != NULL) { // finally is always last get_last_end_pos(finally, &end_lineno, &end_col_offset); } else if (orelse != NULL) { // otherwise else is last get_last_end_pos(orelse, &end_lineno, &end_col_offset); } else { // inline the get_last_end_pos logic due to layout mismatch last_handler = (excepthandler_ty) asdl_seq_GET(handlers, n_except - 1); end_lineno = last_handler->end_lineno; end_col_offset = last_handler->end_col_offset; } return Try(body, handlers, orelse, finally, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } /* with_item: test ['as' expr] */ static withitem_ty ast_for_with_item(struct compiling *c, const node *n) { expr_ty context_expr, optional_vars = NULL; REQ(n, with_item); context_expr = ast_for_expr(c, CHILD(n, 0)); if (!context_expr) return NULL; if (NCH(n) == 3) { optional_vars = ast_for_expr(c, CHILD(n, 2)); if (!optional_vars) { return NULL; } if (!set_context(c, optional_vars, Store, n)) { return NULL; } } return withitem(context_expr, optional_vars, c->c_arena); } /* with_stmt: 'with' with_item (',' with_item)* ':' [TYPE_COMMENT] suite */ static stmt_ty ast_for_with_stmt(struct compiling *c, const node *n0, bool is_async) { const node * const n = is_async ? CHILD(n0, 1) : n0; int i, n_items, nch_minus_type, has_type_comment, end_lineno, end_col_offset; asdl_seq *items, *body; string type_comment; if (is_async && c->c_feature_version < 5) { ast_error(c, n, "Async with statements are only supported in Python 3.5 and greater"); return NULL; } REQ(n, with_stmt); has_type_comment = TYPE(CHILD(n, NCH(n) - 2)) == TYPE_COMMENT; nch_minus_type = NCH(n) - has_type_comment; n_items = (nch_minus_type - 2) / 2; items = _Py_asdl_seq_new(n_items, c->c_arena); if (!items) return NULL; for (i = 1; i < nch_minus_type - 2; i += 2) { withitem_ty item = ast_for_with_item(c, CHILD(n, i)); if (!item) return NULL; asdl_seq_SET(items, (i - 1) / 2, item); } body = ast_for_suite(c, CHILD(n, NCH(n) - 1)); if (!body) return NULL; get_last_end_pos(body, &end_lineno, &end_col_offset); if (has_type_comment) { type_comment = NEW_TYPE_COMMENT(CHILD(n, NCH(n) - 2)); if (!type_comment) return NULL; } else type_comment = NULL; if (is_async) return AsyncWith(items, body, type_comment, LINENO(n0), n0->n_col_offset, end_lineno, end_col_offset, c->c_arena); else return With(items, body, type_comment, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } static stmt_ty ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq) { /* classdef: 'class' NAME ['(' arglist ')'] ':' suite */ PyObject *classname; asdl_seq *s; expr_ty call; int end_lineno, end_col_offset; REQ(n, classdef); if (NCH(n) == 4) { /* class NAME ':' suite */ s = ast_for_suite(c, CHILD(n, 3)); if (!s) return NULL; get_last_end_pos(s, &end_lineno, &end_col_offset); classname = NEW_IDENTIFIER(CHILD(n, 1)); if (!classname) return NULL; if (forbidden_name(c, classname, CHILD(n, 3), 0)) return NULL; return ClassDef(classname, NULL, NULL, s, decorator_seq, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } if (TYPE(CHILD(n, 3)) == RPAR) { /* class NAME '(' ')' ':' suite */ s = ast_for_suite(c, CHILD(n, 5)); if (!s) return NULL; get_last_end_pos(s, &end_lineno, &end_col_offset); classname = NEW_IDENTIFIER(CHILD(n, 1)); if (!classname) return NULL; if (forbidden_name(c, classname, CHILD(n, 3), 0)) return NULL; return ClassDef(classname, NULL, NULL, s, decorator_seq, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } /* class NAME '(' arglist ')' ':' suite */ /* build up a fake Call node so we can extract its pieces */ { PyObject *dummy_name; expr_ty dummy; dummy_name = NEW_IDENTIFIER(CHILD(n, 1)); if (!dummy_name) return NULL; dummy = Name(dummy_name, Load, LINENO(n), n->n_col_offset, CHILD(n, 1)->n_end_lineno, CHILD(n, 1)->n_end_col_offset, c->c_arena); call = ast_for_call(c, CHILD(n, 3), dummy, NULL, CHILD(n, 4)); if (!call) return NULL; } s = ast_for_suite(c, CHILD(n, 6)); if (!s) return NULL; get_last_end_pos(s, &end_lineno, &end_col_offset); classname = NEW_IDENTIFIER(CHILD(n, 1)); if (!classname) return NULL; if (forbidden_name(c, classname, CHILD(n, 1), 0)) return NULL; return ClassDef(classname, call->v.Call.args, call->v.Call.keywords, s, decorator_seq, LINENO(n), n->n_col_offset, end_lineno, end_col_offset, c->c_arena); } static stmt_ty ast_for_stmt(struct compiling *c, const node *n) { if (TYPE(n) == stmt) { assert(NCH(n) == 1); n = CHILD(n, 0); } if (TYPE(n) == simple_stmt) { assert(num_stmts(n) == 1); n = CHILD(n, 0); } if (TYPE(n) == small_stmt) { n = CHILD(n, 0); /* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt */ switch (TYPE(n)) { case expr_stmt: return ast_for_expr_stmt(c, n); case del_stmt: return ast_for_del_stmt(c, n); case pass_stmt: return Pass(LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); case flow_stmt: return ast_for_flow_stmt(c, n); case import_stmt: return ast_for_import_stmt(c, n); case global_stmt: return ast_for_global_stmt(c, n); case nonlocal_stmt: return ast_for_nonlocal_stmt(c, n); case assert_stmt: return ast_for_assert_stmt(c, n); default: PyErr_Format(PyExc_SystemError, "unhandled small_stmt: TYPE=%d NCH=%d\n", TYPE(n), NCH(n)); return NULL; } } else { /* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef | decorated | async_stmt */ node *ch = CHILD(n, 0); REQ(n, compound_stmt); switch (TYPE(ch)) { case if_stmt: return ast_for_if_stmt(c, ch); case while_stmt: return ast_for_while_stmt(c, ch); case for_stmt: return ast_for_for_stmt(c, ch, 0); case try_stmt: return ast_for_try_stmt(c, ch); case with_stmt: return ast_for_with_stmt(c, ch, 0); case funcdef: return ast_for_funcdef(c, ch, NULL); case classdef: return ast_for_classdef(c, ch, NULL); case decorated: return ast_for_decorated(c, ch); case async_stmt: return ast_for_async_stmt(c, ch); default: PyErr_Format(PyExc_SystemError, "unhandled compound_stmt: TYPE=%d NCH=%d\n", TYPE(n), NCH(n)); return NULL; } } } static PyObject * parsenumber_raw(struct compiling *c, const char *s) { const char *end; long x; double dx; Py_complex compl; int imflag; assert(s != NULL); errno = 0; end = s + strlen(s) - 1; imflag = *end == 'j' || *end == 'J'; if (s[0] == '0') { x = (long) PyOS_strtoul(s, (char **)&end, 0); if (x < 0 && errno == 0) { return PyLong_FromString(s, (char **)0, 0); } } else x = PyOS_strtol(s, (char **)&end, 0); if (*end == '\0') { if (errno != 0) return PyLong_FromString(s, (char **)0, 0); return PyLong_FromLong(x); } /* XXX Huge floats may silently fail */ if (imflag) { compl.real = 0.; compl.imag = PyOS_string_to_double(s, (char **)&end, NULL); if (compl.imag == -1.0 && PyErr_Occurred()) return NULL; return PyComplex_FromCComplex(compl); } else { dx = PyOS_string_to_double(s, NULL, NULL); if (dx == -1.0 && PyErr_Occurred()) return NULL; return PyFloat_FromDouble(dx); } } static PyObject * parsenumber(struct compiling *c, const char *s) { char *dup, *end; PyObject *res = NULL; assert(s != NULL); if (strchr(s, '_') == NULL) { return parsenumber_raw(c, s); } /* Create a duplicate without underscores. */ dup = PyMem_Malloc(strlen(s) + 1); if (dup == NULL) { return PyErr_NoMemory(); } end = dup; for (; *s; s++) { if (*s != '_') { *end++ = *s; } } *end = '\0'; res = parsenumber_raw(c, dup); PyMem_Free(dup); return res; } static PyObject * decode_utf8(struct compiling *c, const char **sPtr, const char *end) { const char *s, *t; t = s = *sPtr; /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */ while (s < end && (*s & 0x80)) s++; *sPtr = s; return PyUnicode_DecodeUTF8(t, s - t, NULL); } static int warn_invalid_escape_sequence(struct compiling *c, const node *n, unsigned char first_invalid_escape_char) { PyObject *msg = PyUnicode_FromFormat("invalid escape sequence \\%c", first_invalid_escape_char); if (msg == NULL) { return -1; } if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename, LINENO(n), NULL, NULL) < 0) { if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) { /* Replace the SyntaxWarning exception with a SyntaxError to get a more accurate error report */ PyErr_Clear(); ast_error(c, n, "%U", msg); } Py_DECREF(msg); return -1; } Py_DECREF(msg); return 0; } static PyObject * decode_unicode_with_escapes(struct compiling *c, const node *n, const char *s, size_t len) { PyObject *v, *u; char *buf; char *p; const char *end; /* check for integer overflow */ if (len > SIZE_MAX / 6) return NULL; /* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5 "\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */ u = PyBytes_FromStringAndSize((char *)NULL, len * 6); if (u == NULL) return NULL; p = buf = PyBytes_AsString(u); end = s + len; while (s < end) { if (*s == '\\') { *p++ = *s++; if (s >= end || *s & 0x80) { strcpy(p, "u005c"); p += 5; if (s >= end) break; } } if (*s & 0x80) { /* XXX inefficient */ PyObject *w; int kind; void *data; Py_ssize_t len, i; w = decode_utf8(c, &s, end); if (w == NULL) { Py_DECREF(u); return NULL; } kind = PyUnicode_KIND(w); data = PyUnicode_DATA(w); len = PyUnicode_GET_LENGTH(w); for (i = 0; i < len; i++) { Py_UCS4 chr = PyUnicode_READ(kind, data, i); sprintf(p, "\\U%08x", chr); p += 10; } /* Should be impossible to overflow */ assert(p - buf <= PyBytes_GET_SIZE(u)); Py_DECREF(w); } else { *p++ = *s++; } } len = p - buf; s = buf; const char *first_invalid_escape; v = _PyUnicode_DecodeUnicodeEscape(s, len, NULL, &first_invalid_escape); if (v != NULL && first_invalid_escape != NULL) { if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) { /* We have not decref u before because first_invalid_escape points inside u. */ Py_XDECREF(u); Py_DECREF(v); return NULL; } } Py_XDECREF(u); return v; } static PyObject * decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s, size_t len) { const char *first_invalid_escape; PyObject *result = _PyBytes_DecodeEscape(s, len, NULL, 0, NULL, &first_invalid_escape); if (result == NULL) return NULL; if (first_invalid_escape != NULL) { if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) { Py_DECREF(result); return NULL; } } return result; } /* Shift locations for the given node and all its children by adding `lineno` and `col_offset` to existing locations. */ static void fstring_shift_node_locations(node *n, int lineno, int col_offset) { n->n_col_offset = n->n_col_offset + col_offset; n->n_end_col_offset = n->n_end_col_offset + col_offset; for (int i = 0; i < NCH(n); ++i) { if (n->n_lineno && n->n_lineno < CHILD(n, i)->n_lineno) { /* Shifting column offsets unnecessary if there's been newlines. */ col_offset = 0; } fstring_shift_node_locations(CHILD(n, i), lineno, col_offset); } n->n_lineno = n->n_lineno + lineno; n->n_end_lineno = n->n_end_lineno + lineno; } /* Fix locations for the given node and its children. `parent` is the enclosing node. `n` is the node which locations are going to be fixed relative to parent. `expr_str` is the child node's string representation, including braces. */ static void fstring_fix_node_location(const node *parent, node *n, char *expr_str) { char *substr = NULL; char *start; int lines = LINENO(parent) - 1; int cols = parent->n_col_offset; /* Find the full fstring to fix location information in `n`. */ while (parent && parent->n_type != STRING) parent = parent->n_child; if (parent && parent->n_str) { substr = strstr(parent->n_str, expr_str); if (substr) { start = substr; while (start > parent->n_str) { if (start[0] == '\n') break; start--; } cols += (int)(substr - start); /* adjust the start based on the number of newlines encountered before the f-string expression */ for (char* p = parent->n_str; p < substr; p++) { if (*p == '\n') { lines++; } } } } fstring_shift_node_locations(n, lines, cols); } /* Compile this expression in to an expr_ty. Add parens around the expression, in order to allow leading spaces in the expression. */ static expr_ty fstring_compile_expr(const char *expr_start, const char *expr_end, struct compiling *c, const node *n) { PyCompilerFlags cf; node *mod_n; mod_ty mod; char *str; Py_ssize_t len; const char *s; assert(expr_end >= expr_start); assert(*(expr_start-1) == '{'); assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':'); /* If the substring is all whitespace, it's an error. We need to catch this here, and not when we call PyParser_SimpleParseStringFlagsFilename, because turning the expression '' in to '()' would go from being invalid to valid. */ for (s = expr_start; s != expr_end; s++) { char c = *s; /* The Python parser ignores only the following whitespace characters (\r already is converted to \n). */ if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) { break; } } if (s == expr_end) { ast_error(c, n, "f-string: empty expression not allowed"); return NULL; } len = expr_end - expr_start; /* Allocate 3 extra bytes: open paren, close paren, null byte. */ str = PyMem_RawMalloc(len + 3); if (str == NULL) { PyErr_NoMemory(); return NULL; } str[0] = '('; memcpy(str+1, expr_start, len); str[len+1] = ')'; str[len+2] = 0; cf.cf_flags = PyCF_ONLY_AST; cf.cf_feature_version = PY_MINOR_VERSION; mod_n = PyParser_SimpleParseStringFlagsFilename(str, "<fstring>", Py_eval_input, 0); if (!mod_n) { PyMem_RawFree(str); return NULL; } /* Reuse str to find the correct column offset. */ str[0] = '{'; str[len+1] = '}'; fstring_fix_node_location(n, mod_n, str); mod = PyAST_FromNode(mod_n, &cf, "<fstring>", c->c_arena); PyMem_RawFree(str); PyNode_Free(mod_n); if (!mod) return NULL; return mod->v.Expression.body; } /* Return -1 on error. Return 0 if we reached the end of the literal. Return 1 if we haven't reached the end of the literal, but we want the caller to process the literal up to this point. Used for doubled braces. */ static int fstring_find_literal(const char **str, const char *end, int raw, PyObject **literal, int recurse_lvl, struct compiling *c, const node *n) { /* Get any literal string. It ends when we hit an un-doubled left brace (which isn't part of a unicode name escape such as "\N{EULER CONSTANT}"), or the end of the string. */ const char *s = *str; const char *literal_start = s; int result = 0; assert(*literal == NULL); while (s < end) { char ch = *s++; if (!raw && ch == '\\' && s < end) { ch = *s++; if (ch == 'N') { if (s < end && *s++ == '{') { while (s < end && *s++ != '}') { } continue; } break; } if (ch == '{' && warn_invalid_escape_sequence(c, n, ch) < 0) { return -1; } } if (ch == '{' || ch == '}') { /* Check for doubled braces, but only at the top level. If we checked at every level, then f'{0:{3}}' would fail with the two closing braces. */ if (recurse_lvl == 0) { if (s < end && *s == ch) { /* We're going to tell the caller that the literal ends here, but that they should continue scanning. But also skip over the second brace when we resume scanning. */ *str = s + 1; result = 1; goto done; } /* Where a single '{' is the start of a new expression, a single '}' is not allowed. */ if (ch == '}') { *str = s - 1; ast_error(c, n, "f-string: single '}' is not allowed"); return -1; } } /* We're either at a '{', which means we're starting another expression; or a '}', which means we're at the end of this f-string (for a nested format_spec). */ s--; break; } } *str = s; assert(s <= end); assert(s == end || *s == '{' || *s == '}'); done: if (literal_start != s) { if (raw) *literal = PyUnicode_DecodeUTF8Stateful(literal_start, s - literal_start, NULL, NULL); else *literal = decode_unicode_with_escapes(c, n, literal_start, s - literal_start); if (!*literal) return -1; } return result; } /* Forward declaration because parsing is recursive. */ static expr_ty fstring_parse(const char **str, const char *end, int raw, int recurse_lvl, struct compiling *c, const node *n); /* Parse the f-string at *str, ending at end. We know *str starts an expression (so it must be a '{'). Returns the FormattedValue node, which includes the expression, conversion character, and format_spec expression. Note that I don't do a perfect job here: I don't make sure that a closing brace doesn't match an opening paren, for example. It doesn't need to error on all invalid expressions, just correctly find the end of all valid ones. Any errors inside the expression will be caught when we parse it later. */ static int fstring_find_expr(const char **str, const char *end, int raw, int recurse_lvl, expr_ty *expression, struct compiling *c, const node *n) { /* Return -1 on error, else 0. */ const char *expr_start; const char *expr_end; expr_ty simple_expression; expr_ty format_spec = NULL; /* Optional format specifier. */ int conversion = -1; /* The conversion char. -1 if not specified. */ /* 0 if we're not in a string, else the quote char we're trying to match (single or double quote). */ char quote_char = 0; /* If we're inside a string, 1=normal, 3=triple-quoted. */ int string_type = 0; /* Keep track of nesting level for braces/parens/brackets in expressions. */ Py_ssize_t nested_depth = 0; char parenstack[MAXLEVEL]; /* Can only nest one level deep. */ if (recurse_lvl >= 2) { ast_error(c, n, "f-string: expressions nested too deeply"); return -1; } /* The first char must be a left brace, or we wouldn't have gotten here. Skip over it. */ assert(**str == '{'); *str += 1; expr_start = *str; for (; *str < end; (*str)++) { char ch; /* Loop invariants. */ assert(nested_depth >= 0); assert(*str >= expr_start && *str < end); if (quote_char) assert(string_type == 1 || string_type == 3); else assert(string_type == 0); ch = **str; /* Nowhere inside an expression is a backslash allowed. */ if (ch == '\\') { /* Error: can't include a backslash character, inside parens or strings or not. */ ast_error(c, n, "f-string expression part " "cannot include a backslash"); return -1; } if (quote_char) { /* We're inside a string. See if we're at the end. */ /* This code needs to implement the same non-error logic as tok_get from tokenizer.c, at the letter_quote label. To actually share that code would be a nightmare. But, it's unlikely to change and is small, so duplicate it here. Note we don't need to catch all of the errors, since they'll be caught when parsing the expression. We just need to match the non-error cases. Thus we can ignore \n in single-quoted strings, for example. Or non-terminated strings. */ if (ch == quote_char) { /* Does this match the string_type (single or triple quoted)? */ if (string_type == 3) { if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) { /* We're at the end of a triple quoted string. */ *str += 2; string_type = 0; quote_char = 0; continue; } } else { /* We're at the end of a normal string. */ quote_char = 0; string_type = 0; continue; } } } else if (ch == '\'' || ch == '"') { /* Is this a triple quoted string? */ if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) { string_type = 3; *str += 2; } else { /* Start of a normal string. */ string_type = 1; } /* Start looking for the end of the string. */ quote_char = ch; } else if (ch == '[' || ch == '{' || ch == '(') { if (nested_depth >= MAXLEVEL) { ast_error(c, n, "f-string: too many nested parenthesis"); return -1; } parenstack[nested_depth] = ch; nested_depth++; } else if (ch == '#') { /* Error: can't include a comment character, inside parens or not. */ ast_error(c, n, "f-string expression part cannot include '#'"); return -1; } else if (nested_depth == 0 && (ch == '!' || ch == ':' || ch == '}')) { /* First, test for the special case of "!=". Since '=' is not an allowed conversion character, nothing is lost in this test. */ if (ch == '!' && *str+1 < end && *(*str+1) == '=') { /* This isn't a conversion character, just continue. */ continue; } /* Normal way out of this loop. */ break; } else if (ch == ']' || ch == '}' || ch == ')') { if (!nested_depth) { ast_error(c, n, "f-string: unmatched '%c'", ch); return -1; } nested_depth--; int opening = parenstack[nested_depth]; if (!((opening == '(' && ch == ')') || (opening == '[' && ch == ']') || (opening == '{' && ch == '}'))) { ast_error(c, n, "f-string: closing parenthesis '%c' " "does not match opening parenthesis '%c'", ch, opening); return -1; } } else { /* Just consume this char and loop around. */ } } expr_end = *str; /* If we leave this loop in a string or with mismatched parens, we don't care. We'll get a syntax error when compiling the expression. But, we can produce a better error message, so let's just do that.*/ if (quote_char) { ast_error(c, n, "f-string: unterminated string"); return -1; } if (nested_depth) { int opening = parenstack[nested_depth - 1]; ast_error(c, n, "f-string: unmatched '%c'", opening); return -1; } if (*str >= end) goto unexpected_end_of_string; /* Compile the expression as soon as possible, so we show errors related to the expression before errors related to the conversion or format_spec. */ simple_expression = fstring_compile_expr(expr_start, expr_end, c, n); if (!simple_expression) return -1; /* Check for a conversion char, if present. */ if (**str == '!') { *str += 1; if (*str >= end) goto unexpected_end_of_string; conversion = **str; *str += 1; /* Validate the conversion. */ if (!(conversion == 's' || conversion == 'r' || conversion == 'a')) { ast_error(c, n, "f-string: invalid conversion character: " "expected 's', 'r', or 'a'"); return -1; } } /* Check for the format spec, if present. */ if (*str >= end) goto unexpected_end_of_string; if (**str == ':') { *str += 1; if (*str >= end) goto unexpected_end_of_string; /* Parse the format spec. */ format_spec = fstring_parse(str, end, raw, recurse_lvl+1, c, n); if (!format_spec) return -1; } if (*str >= end || **str != '}') goto unexpected_end_of_string; /* We're at a right brace. Consume it. */ assert(*str < end); assert(**str == '}'); *str += 1; /* And now create the FormattedValue node that represents this entire expression with the conversion and format spec. */ *expression = FormattedValue(simple_expression, conversion, format_spec, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); if (!*expression) return -1; return 0; unexpected_end_of_string: ast_error(c, n, "f-string: expecting '}'"); return -1; } /* Return -1 on error. Return 0 if we have a literal (possible zero length) and an expression (zero length if at the end of the string. Return 1 if we have a literal, but no expression, and we want the caller to call us again. This is used to deal with doubled braces. When called multiple times on the string 'a{{b{0}c', this function will return: 1. the literal 'a{' with no expression, and a return value of 1. Despite the fact that there's no expression, the return value of 1 means we're not finished yet. 2. the literal 'b' and the expression '0', with a return value of 0. The fact that there's an expression means we're not finished. 3. literal 'c' with no expression and a return value of 0. The combination of the return value of 0 with no expression means we're finished. */ static int fstring_find_literal_and_expr(const char **str, const char *end, int raw, int recurse_lvl, PyObject **literal, expr_ty *expression, struct compiling *c, const node *n) { int result; assert(*literal == NULL && *expression == NULL); /* Get any literal string. */ result = fstring_find_literal(str, end, raw, literal, recurse_lvl, c, n); if (result < 0) goto error; assert(result == 0 || result == 1); if (result == 1) /* We have a literal, but don't look at the expression. */ return 1; if (*str >= end || **str == '}') /* We're at the end of the string or the end of a nested f-string: no expression. The top-level error case where we expect to be at the end of the string but we're at a '}' is handled later. */ return 0; /* We must now be the start of an expression, on a '{'. */ assert(**str == '{'); if (fstring_find_expr(str, end, raw, recurse_lvl, expression, c, n) < 0) goto error; return 0; error: Py_CLEAR(*literal); return -1; } #define EXPRLIST_N_CACHED 64 typedef struct { /* Incrementally build an array of expr_ty, so be used in an asdl_seq. Cache some small but reasonably sized number of expr_ty's, and then after that start dynamically allocating, doubling the number allocated each time. Note that the f-string f'{0}a{1}' contains 3 expr_ty's: 2 FormattedValue's, and one Constant for the literal 'a'. So you add expr_ty's about twice as fast as you add exressions in an f-string. */ Py_ssize_t allocated; /* Number we've allocated. */ Py_ssize_t size; /* Number we've used. */ expr_ty *p; /* Pointer to the memory we're actually using. Will point to 'data' until we start dynamically allocating. */ expr_ty data[EXPRLIST_N_CACHED]; } ExprList; #ifdef NDEBUG #define ExprList_check_invariants(l) #else static void ExprList_check_invariants(ExprList *l) { /* Check our invariants. Make sure this object is "live", and hasn't been deallocated. */ assert(l->size >= 0); assert(l->p != NULL); if (l->size <= EXPRLIST_N_CACHED) assert(l->data == l->p); } #endif static void ExprList_Init(ExprList *l) { l->allocated = EXPRLIST_N_CACHED; l->size = 0; /* Until we start allocating dynamically, p points to data. */ l->p = l->data; ExprList_check_invariants(l); } static int ExprList_Append(ExprList *l, expr_ty exp) { ExprList_check_invariants(l); if (l->size >= l->allocated) { /* We need to alloc (or realloc) the memory. */ Py_ssize_t new_size = l->allocated * 2; /* See if we've ever allocated anything dynamically. */ if (l->p == l->data) { Py_ssize_t i; /* We're still using the cached data. Switch to alloc-ing. */ l->p = PyMem_RawMalloc(sizeof(expr_ty) * new_size); if (!l->p) return -1; /* Copy the cached data into the new buffer. */ for (i = 0; i < l->size; i++) l->p[i] = l->data[i]; } else { /* Just realloc. */ expr_ty *tmp = PyMem_RawRealloc(l->p, sizeof(expr_ty) * new_size); if (!tmp) { PyMem_RawFree(l->p); l->p = NULL; return -1; } l->p = tmp; } l->allocated = new_size; assert(l->allocated == 2 * l->size); } l->p[l->size++] = exp; ExprList_check_invariants(l); return 0; } static void ExprList_Dealloc(ExprList *l) { ExprList_check_invariants(l); /* If there's been an error, or we've never dynamically allocated, do nothing. */ if (!l->p || l->p == l->data) { /* Do nothing. */ } else { /* We have dynamically allocated. Free the memory. */ PyMem_RawFree(l->p); } l->p = NULL; l->size = -1; } static asdl_seq * ExprList_Finish(ExprList *l, PyArena *arena) { asdl_seq *seq; ExprList_check_invariants(l); /* Allocate the asdl_seq and copy the expressions in to it. */ seq = _Py_asdl_seq_new(l->size, arena); if (seq) { Py_ssize_t i; for (i = 0; i < l->size; i++) asdl_seq_SET(seq, i, l->p[i]); } ExprList_Dealloc(l); return seq; } /* The FstringParser is designed to add a mix of strings and f-strings, and concat them together as needed. Ultimately, it generates an expr_ty. */ typedef struct { PyObject *last_str; ExprList expr_list; int fmode; } FstringParser; #ifdef NDEBUG #define FstringParser_check_invariants(state) #else static void FstringParser_check_invariants(FstringParser *state) { if (state->last_str) assert(PyUnicode_CheckExact(state->last_str)); ExprList_check_invariants(&state->expr_list); } #endif static void FstringParser_Init(FstringParser *state) { state->last_str = NULL; state->fmode = 0; ExprList_Init(&state->expr_list); FstringParser_check_invariants(state); } static void FstringParser_Dealloc(FstringParser *state) { FstringParser_check_invariants(state); Py_XDECREF(state->last_str); ExprList_Dealloc(&state->expr_list); } /* Constants for the following */ static PyObject *u_kind; /* Compute 'kind' field for string Constant (either 'u' or None) */ static PyObject * make_kind(struct compiling *c, const node *n) { char *s = NULL; PyObject *kind = NULL; /* Find the first string literal, if any */ while (TYPE(n) != STRING) { if (NCH(n) == 0) return NULL; n = CHILD(n, 0); } REQ(n, STRING); /* If it starts with 'u', return a PyUnicode "u" string */ s = STR(n); if (s && *s == 'u') { if (!u_kind) { u_kind = PyUnicode_InternFromString("u"); if (!u_kind) return NULL; } kind = u_kind; if (PyArena_AddPyObject(c->c_arena, kind) < 0) { return NULL; } Py_INCREF(kind); } return kind; } /* Make a Constant node, but decref the PyUnicode object being added. */ static expr_ty make_str_node_and_del(PyObject **str, struct compiling *c, const node* n) { PyObject *s = *str; PyObject *kind = NULL; *str = NULL; assert(PyUnicode_CheckExact(s)); if (PyArena_AddPyObject(c->c_arena, s) < 0) { Py_DECREF(s); return NULL; } kind = make_kind(c, n); if (kind == NULL && PyErr_Occurred()) return NULL; return Constant(s, kind, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } /* Add a non-f-string (that is, a regular literal string). str is decref'd. */ static int FstringParser_ConcatAndDel(FstringParser *state, PyObject *str) { FstringParser_check_invariants(state); assert(PyUnicode_CheckExact(str)); if (PyUnicode_GET_LENGTH(str) == 0) { Py_DECREF(str); return 0; } if (!state->last_str) { /* We didn't have a string before, so just remember this one. */ state->last_str = str; } else { /* Concatenate this with the previous string. */ PyUnicode_AppendAndDel(&state->last_str, str); if (!state->last_str) return -1; } FstringParser_check_invariants(state); return 0; } /* Parse an f-string. The f-string is in *str to end, with no 'f' or quotes. */ static int FstringParser_ConcatFstring(FstringParser *state, const char **str, const char *end, int raw, int recurse_lvl, struct compiling *c, const node *n) { FstringParser_check_invariants(state); state->fmode = 1; /* Parse the f-string. */ while (1) { PyObject *literal = NULL; expr_ty expression = NULL; /* If there's a zero length literal in front of the expression, literal will be NULL. If we're at the end of the f-string, expression will be NULL (unless result == 1, see below). */ int result = fstring_find_literal_and_expr(str, end, raw, recurse_lvl, &literal, &expression, c, n); if (result < 0) return -1; /* Add the literal, if any. */ if (!literal) { /* Do nothing. Just leave last_str alone (and possibly NULL). */ } else if (!state->last_str) { /* Note that the literal can be zero length, if the input string is "\\\n" or "\\\r", among others. */ state->last_str = literal; literal = NULL; } else { /* We have a literal, concatenate it. */ assert(PyUnicode_GET_LENGTH(literal) != 0); if (FstringParser_ConcatAndDel(state, literal) < 0) return -1; literal = NULL; } /* We've dealt with the literal now. It can't be leaked on further errors. */ assert(literal == NULL); /* See if we should just loop around to get the next literal and expression, while ignoring the expression this time. This is used for un-doubling braces, as an optimization. */ if (result == 1) continue; if (!expression) /* We're done with this f-string. */ break; /* We know we have an expression. Convert any existing string to a Constant node. */ if (!state->last_str) { /* Do nothing. No previous literal. */ } else { /* Convert the existing last_str literal to a Constant node. */ expr_ty str = make_str_node_and_del(&state->last_str, c, n); if (!str || ExprList_Append(&state->expr_list, str) < 0) return -1; } if (ExprList_Append(&state->expr_list, expression) < 0) return -1; } /* If recurse_lvl is zero, then we must be at the end of the string. Otherwise, we must be at a right brace. */ if (recurse_lvl == 0 && *str < end-1) { ast_error(c, n, "f-string: unexpected end of string"); return -1; } if (recurse_lvl != 0 && **str != '}') { ast_error(c, n, "f-string: expecting '}'"); return -1; } FstringParser_check_invariants(state); return 0; } /* Convert the partial state reflected in last_str and expr_list to an expr_ty. The expr_ty can be a Constant, or a JoinedStr. */ static expr_ty FstringParser_Finish(FstringParser *state, struct compiling *c, const node *n) { asdl_seq *seq; FstringParser_check_invariants(state); /* If we're just a constant string with no expressions, return that. */ if (!state->fmode) { assert(!state->expr_list.size); if (!state->last_str) { /* Create a zero length string. */ state->last_str = PyUnicode_FromStringAndSize(NULL, 0); if (!state->last_str) goto error; } return make_str_node_and_del(&state->last_str, c, n); } /* Create a Constant node out of last_str, if needed. It will be the last node in our expression list. */ if (state->last_str) { expr_ty str = make_str_node_and_del(&state->last_str, c, n); if (!str || ExprList_Append(&state->expr_list, str) < 0) goto error; } /* This has already been freed. */ assert(state->last_str == NULL); seq = ExprList_Finish(&state->expr_list, c->c_arena); if (!seq) goto error; return JoinedStr(seq, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); error: FstringParser_Dealloc(state); return NULL; } /* Given an f-string (with no 'f' or quotes) that's in *str and ends at end, parse it into an expr_ty. Return NULL on error. Adjust str to point past the parsed portion. */ static expr_ty fstring_parse(const char **str, const char *end, int raw, int recurse_lvl, struct compiling *c, const node *n) { FstringParser state; FstringParser_Init(&state); if (FstringParser_ConcatFstring(&state, str, end, raw, recurse_lvl, c, n) < 0) { FstringParser_Dealloc(&state); return NULL; } return FstringParser_Finish(&state, c, n); } /* n is a Python string literal, including the bracketing quote characters, and r, b, u, &/or f prefixes (if any), and embedded escape sequences (if any). parsestr parses it, and sets *result to decoded Python string object. If the string is an f-string, set *fstr and *fstrlen to the unparsed string object. Return 0 if no errors occurred. */ static int parsestr(struct compiling *c, const node *n, int *bytesmode, int *rawmode, PyObject **result, const char **fstr, Py_ssize_t *fstrlen) { size_t len; const char *s = STR(n); int quote = Py_CHARMASK(*s); int fmode = 0; *bytesmode = 0; *rawmode = 0; *result = NULL; *fstr = NULL; if (Py_ISALPHA(quote)) { while (!*bytesmode || !*rawmode) { if (quote == 'b' || quote == 'B') { quote = *++s; *bytesmode = 1; } else if (quote == 'u' || quote == 'U') { quote = *++s; } else if (quote == 'r' || quote == 'R') { quote = *++s; *rawmode = 1; } else if (quote == 'f' || quote == 'F') { quote = *++s; fmode = 1; } else { break; } } } /* fstrings are only allowed in Python 3.6 and greater */ if (fmode && c->c_feature_version < 6) { ast_error(c, n, "Format strings are only supported in Python 3.6 and greater"); return -1; } if (fmode && *bytesmode) { PyErr_BadInternalCall(); return -1; } if (quote != '\'' && quote != '\"') { PyErr_BadInternalCall(); return -1; } /* Skip the leading quote char. */ s++; len = strlen(s); if (len > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return -1; } if (s[--len] != quote) { /* Last quote char must match the first. */ PyErr_BadInternalCall(); return -1; } if (len >= 4 && s[0] == quote && s[1] == quote) { /* A triple quoted string. We've already skipped one quote at the start and one at the end of the string. Now skip the two at the start. */ s += 2; len -= 2; /* And check that the last two match. */ if (s[--len] != quote || s[--len] != quote) { PyErr_BadInternalCall(); return -1; } } if (fmode) { /* Just return the bytes. The caller will parse the resulting string. */ *fstr = s; *fstrlen = len; return 0; } /* Not an f-string. */ /* Avoid invoking escape decoding routines if possible. */ *rawmode = *rawmode || strchr(s, '\\') == NULL; if (*bytesmode) { /* Disallow non-ASCII characters. */ const char *ch; for (ch = s; *ch; ch++) { if (Py_CHARMASK(*ch) >= 0x80) { ast_error(c, n, "bytes can only contain ASCII " "literal characters."); return -1; } } if (*rawmode) *result = PyBytes_FromStringAndSize(s, len); else *result = decode_bytes_with_escapes(c, n, s, len); } else { if (*rawmode) *result = PyUnicode_DecodeUTF8Stateful(s, len, NULL, NULL); else *result = decode_unicode_with_escapes(c, n, s, len); } return *result == NULL ? -1 : 0; } /* Accepts a STRING+ atom, and produces an expr_ty node. Run through each STRING atom, and process it as needed. For bytes, just concatenate them together, and the result will be a Constant node. For normal strings and f-strings, concatenate them together. The result will be a Constant node if there were no f-strings; a FormattedValue node if there's just an f-string (with no leading or trailing literals), or a JoinedStr node if there are multiple f-strings or any literals involved. */ static expr_ty parsestrplus(struct compiling *c, const node *n) { int bytesmode = 0; PyObject *bytes_str = NULL; int i; FstringParser state; FstringParser_Init(&state); for (i = 0; i < NCH(n); i++) { int this_bytesmode; int this_rawmode; PyObject *s; const char *fstr; Py_ssize_t fstrlen = -1; /* Silence a compiler warning. */ REQ(CHILD(n, i), STRING); if (parsestr(c, CHILD(n, i), &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen) != 0) goto error; /* Check that we're not mixing bytes with unicode. */ if (i != 0 && bytesmode != this_bytesmode) { ast_error(c, n, "cannot mix bytes and nonbytes literals"); /* s is NULL if the current string part is an f-string. */ Py_XDECREF(s); goto error; } bytesmode = this_bytesmode; if (fstr != NULL) { int result; assert(s == NULL && !bytesmode); /* This is an f-string. Parse and concatenate it. */ result = FstringParser_ConcatFstring(&state, &fstr, fstr+fstrlen, this_rawmode, 0, c, n); if (result < 0) goto error; } else { /* A string or byte string. */ assert(s != NULL && fstr == NULL); assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s)); if (bytesmode) { /* For bytes, concat as we go. */ if (i == 0) { /* First time, just remember this value. */ bytes_str = s; } else { PyBytes_ConcatAndDel(&bytes_str, s); if (!bytes_str) goto error; } } else { /* This is a regular string. Concatenate it. */ if (FstringParser_ConcatAndDel(&state, s) < 0) goto error; } } } if (bytesmode) { /* Just return the bytes object and we're done. */ if (PyArena_AddPyObject(c->c_arena, bytes_str) < 0) goto error; return Constant(bytes_str, NULL, LINENO(n), n->n_col_offset, n->n_end_lineno, n->n_end_col_offset, c->c_arena); } /* We're not a bytes string, bytes_str should never have been set. */ assert(bytes_str == NULL); return FstringParser_Finish(&state, c, n); error: Py_XDECREF(bytes_str); FstringParser_Dealloc(&state); return NULL; } PyObject * _PyAST_GetDocString(asdl_seq *body) { if (!asdl_seq_LEN(body)) { return NULL; } stmt_ty st = (stmt_ty)asdl_seq_GET(body, 0); if (st->kind != Expr_kind) { return NULL; } expr_ty e = st->v.Expr.value; if (e->kind == Constant_kind && PyUnicode_CheckExact(e->v.Constant.value)) { return e->v.Constant.value; } return NULL; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_1280_0
crossvul-cpp_data_bad_4019_1
/* exif-mnote-data-fuji.c * * Copyright (c) 2002 Lutz Mueller <lutz@users.sourceforge.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. */ #include <stdlib.h> #include <string.h> #include <config.h> #include <libexif/exif-byte-order.h> #include <libexif/exif-utils.h> #include "exif-mnote-data-fuji.h" struct _MNoteFujiDataPrivate { ExifByteOrder order; }; static void exif_mnote_data_fuji_clear (ExifMnoteDataFuji *n) { ExifMnoteData *d = (ExifMnoteData *) n; unsigned int i; if (!n) return; if (n->entries) { for (i = 0; i < n->count; i++) if (n->entries[i].data) { exif_mem_free (d->mem, n->entries[i].data); n->entries[i].data = NULL; } exif_mem_free (d->mem, n->entries); n->entries = NULL; n->count = 0; } } static void exif_mnote_data_fuji_free (ExifMnoteData *n) { if (!n) return; exif_mnote_data_fuji_clear ((ExifMnoteDataFuji *) n); } static char * exif_mnote_data_fuji_get_value (ExifMnoteData *d, unsigned int i, char *val, unsigned int maxlen) { ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d; if (!d || !val) return NULL; if (i > n->count -1) return NULL; /* exif_log (d->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataFuji", "Querying value for tag '%s'...", mnote_fuji_tag_get_name (n->entries[i].tag)); */ return mnote_fuji_entry_get_value (&n->entries[i], val, maxlen); } static void exif_mnote_data_fuji_save (ExifMnoteData *ne, unsigned char **buf, unsigned int *buf_size) { ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) ne; size_t i, o, s, doff; unsigned char *t; size_t ts; if (!n || !buf || !buf_size) return; /* * Allocate enough memory for all entries and the number * of entries. */ *buf_size = 8 + 4 + 2 + n->count * 12 + 4; *buf = exif_mem_alloc (ne->mem, *buf_size); if (!*buf) { *buf_size = 0; return; } /* * Header: "FUJIFILM" and 4 bytes offset to the first entry. * As the first entry will start right thereafter, the offset is 12. */ memcpy (*buf, "FUJIFILM", 8); exif_set_long (*buf + 8, n->order, 12); /* Save the number of entries */ exif_set_short (*buf + 8 + 4, n->order, (ExifShort) n->count); /* Save each entry */ for (i = 0; i < n->count; i++) { o = 8 + 4 + 2 + i * 12; exif_set_short (*buf + o + 0, n->order, (ExifShort) n->entries[i].tag); exif_set_short (*buf + o + 2, n->order, (ExifShort) n->entries[i].format); exif_set_long (*buf + o + 4, n->order, n->entries[i].components); o += 8; s = exif_format_get_size (n->entries[i].format) * n->entries[i].components; if (s > 65536) { /* Corrupt data: EXIF data size is limited to the * maximum size of a JPEG segment (64 kb). */ continue; } if (s > 4) { ts = *buf_size + s; /* Ensure even offsets. Set padding bytes to 0. */ if (s & 1) ts += 1; t = exif_mem_realloc (ne->mem, *buf, ts); if (!t) { return; } *buf = t; *buf_size = ts; doff = *buf_size - s; if (s & 1) { doff--; *(*buf + *buf_size - 1) = '\0'; } exif_set_long (*buf + o, n->order, doff); } else doff = o; /* * Write the data. Fill unneeded bytes with 0. Do not * crash if data is NULL. */ if (!n->entries[i].data) memset (*buf + doff, 0, s); else memcpy (*buf + doff, n->entries[i].data, s); } } static void exif_mnote_data_fuji_load (ExifMnoteData *en, const unsigned char *buf, unsigned int buf_size) { ExifMnoteDataFuji *n = (ExifMnoteDataFuji*) en; ExifLong c; size_t i, tcount, o, datao; if (!n || !buf || !buf_size) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); return; } datao = 6 + n->offset; if ((datao + 12 < datao) || (datao + 12 < 12) || (datao + 12 > buf_size)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); return; } n->order = EXIF_BYTE_ORDER_INTEL; datao += exif_get_long (buf + datao + 8, EXIF_BYTE_ORDER_INTEL); if ((datao + 2 < datao) || (datao + 2 < 2) || (datao + 2 > buf_size)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); return; } /* Read the number of tags */ c = exif_get_short (buf + datao, EXIF_BYTE_ORDER_INTEL); datao += 2; /* Remove any old entries */ exif_mnote_data_fuji_clear (n); /* Reserve enough space for all the possible MakerNote tags */ n->entries = exif_mem_alloc (en->mem, sizeof (MnoteFujiEntry) * c); if (!n->entries) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", sizeof (MnoteFujiEntry) * c); return; } /* Parse all c entries, storing ones that are successfully parsed */ tcount = 0; for (i = c, o = datao; i; --i, o += 12) { size_t s; if ((o + 12 < o) || (o + 12 < 12) || (o + 12 > buf_size)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Short MakerNote"); break; } n->entries[tcount].tag = exif_get_short (buf + o, n->order); n->entries[tcount].format = exif_get_short (buf + o + 2, n->order); n->entries[tcount].components = exif_get_long (buf + o + 4, n->order); n->entries[tcount].order = n->order; exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataFuji", "Loading entry 0x%x ('%s')...", n->entries[tcount].tag, mnote_fuji_tag_get_name (n->entries[tcount].tag)); /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components; n->entries[tcount].size = s; if (s) { size_t dataofs = o + 8; if (s > 4) /* The data in this case is merely a pointer */ dataofs = exif_get_long (buf + dataofs, n->order) + 6 + n->offset; if ((dataofs + s < dataofs) || (dataofs + s < s) || (dataofs + s >= buf_size)) { exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataFuji", "Tag data past end of " "buffer (%u >= %u)", (unsigned)(dataofs + s), buf_size); continue; } n->entries[tcount].data = exif_mem_alloc (en->mem, s); if (!n->entries[tcount].data) { EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", s); continue; } memcpy (n->entries[tcount].data, buf + dataofs, s); } /* Tag was successfully parsed */ ++tcount; } /* Store the count of successfully parsed tags */ n->count = tcount; } static unsigned int exif_mnote_data_fuji_count (ExifMnoteData *n) { return n ? ((ExifMnoteDataFuji *) n)->count : 0; } static unsigned int exif_mnote_data_fuji_get_id (ExifMnoteData *d, unsigned int n) { ExifMnoteDataFuji *note = (ExifMnoteDataFuji *) d; if (!note) return 0; if (note->count <= n) return 0; return note->entries[n].tag; } static const char * exif_mnote_data_fuji_get_name (ExifMnoteData *d, unsigned int i) { ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d; if (!n) return NULL; if (i >= n->count) return NULL; return mnote_fuji_tag_get_name (n->entries[i].tag); } static const char * exif_mnote_data_fuji_get_title (ExifMnoteData *d, unsigned int i) { ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d; if (!n) return NULL; if (i >= n->count) return NULL; return mnote_fuji_tag_get_title (n->entries[i].tag); } static const char * exif_mnote_data_fuji_get_description (ExifMnoteData *d, unsigned int i) { ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d; if (!n) return NULL; if (i >= n->count) return NULL; return mnote_fuji_tag_get_description (n->entries[i].tag); } static void exif_mnote_data_fuji_set_byte_order (ExifMnoteData *d, ExifByteOrder o) { ExifByteOrder o_orig; ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d; unsigned int i; if (!n) return; o_orig = n->order; n->order = o; for (i = 0; i < n->count; i++) { if (n->entries[i].components && (n->entries[i].size/n->entries[i].components < exif_format_get_size (n->entries[i].format))) continue; n->entries[i].order = o; exif_array_set_byte_order (n->entries[i].format, n->entries[i].data, n->entries[i].components, o_orig, o); } } static void exif_mnote_data_fuji_set_offset (ExifMnoteData *n, unsigned int o) { if (n) ((ExifMnoteDataFuji *) n)->offset = o; } int exif_mnote_data_fuji_identify (const ExifData *ed, const ExifEntry *e) { (void) ed; /* unused */ return ((e->size >= 12) && !memcmp (e->data, "FUJIFILM", 8)); } ExifMnoteData * exif_mnote_data_fuji_new (ExifMem *mem) { ExifMnoteData *d; if (!mem) return NULL; d = exif_mem_alloc (mem, sizeof (ExifMnoteDataFuji)); if (!d) return NULL; exif_mnote_data_construct (d, mem); /* Set up function pointers */ d->methods.free = exif_mnote_data_fuji_free; d->methods.set_byte_order = exif_mnote_data_fuji_set_byte_order; d->methods.set_offset = exif_mnote_data_fuji_set_offset; d->methods.load = exif_mnote_data_fuji_load; d->methods.save = exif_mnote_data_fuji_save; d->methods.count = exif_mnote_data_fuji_count; d->methods.get_id = exif_mnote_data_fuji_get_id; d->methods.get_name = exif_mnote_data_fuji_get_name; d->methods.get_title = exif_mnote_data_fuji_get_title; d->methods.get_description = exif_mnote_data_fuji_get_description; d->methods.get_value = exif_mnote_data_fuji_get_value; return d; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4019_1
crossvul-cpp_data_good_5094_0
/* $Id: fpm_status.c 312262 2011-06-18 17:41:56Z felipe $ */ /* (c) 2009 Jerome Loyet */ #include "php.h" #include "SAPI.h" #include <stdio.h> #include <unistd.h> #include <fcntl.h> #ifdef HAVE_TIMES #include <sys/times.h> #endif #include "fpm_config.h" #include "fpm_log.h" #include "fpm_clock.h" #include "fpm_process_ctl.h" #include "fpm_signals.h" #include "fpm_scoreboard.h" #include "fastcgi.h" #include "zlog.h" #ifdef MAX_LINE_LENGTH # define FPM_LOG_BUFFER MAX_LINE_LENGTH #else # define FPM_LOG_BUFFER 1024 #endif static char *fpm_log_format = NULL; static int fpm_log_fd = -1; int fpm_log_open(int reopen) /* {{{ */ { struct fpm_worker_pool_s *wp; int ret = 1; int fd; for (wp = fpm_worker_all_pools; wp; wp = wp->next) { if (!wp->config->access_log) { continue; } ret = 0; fd = open(wp->config->access_log, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); if (0 > fd) { zlog(ZLOG_SYSERROR, "failed to open access log (%s)", wp->config->access_log); return -1; } else { zlog(ZLOG_DEBUG, "open access log (%s)", wp->config->access_log); } if (reopen) { dup2(fd, wp->log_fd); close(fd); fd = wp->log_fd; fpm_pctl_kill_all(SIGQUIT); } else { wp->log_fd = fd; } if (0 > fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC)) { zlog(ZLOG_WARNING, "failed to change attribute of access_log"); } } return ret; } /* }}} */ /* }}} */ int fpm_log_init_child(struct fpm_worker_pool_s *wp) /* {{{ */ { if (!wp || !wp->config) { return -1; } if (wp->config->access_log && *wp->config->access_log) { if (wp->config->access_format) { fpm_log_format = strdup(wp->config->access_format); } } if (fpm_log_fd == -1) { fpm_log_fd = wp->log_fd; } for (wp = fpm_worker_all_pools; wp; wp = wp->next) { if (wp->log_fd > -1 && wp->log_fd != fpm_log_fd) { close(wp->log_fd); wp->log_fd = -1; } } return 0; } /* }}} */ int fpm_log_write(char *log_format) /* {{{ */ { char *s, *b; char buffer[FPM_LOG_BUFFER+1]; int token, test; size_t len, len2; struct fpm_scoreboard_proc_s proc, *proc_p; struct fpm_scoreboard_s *scoreboard; char tmp[129]; char format[129]; time_t now_epoch; #ifdef HAVE_TIMES clock_t tms_total; #endif if (!log_format && (!fpm_log_format || fpm_log_fd == -1)) { return -1; } if (!log_format) { log_format = fpm_log_format; test = 0; } else { test = 1; } now_epoch = time(NULL); if (!test) { scoreboard = fpm_scoreboard_get(); if (!scoreboard) { zlog(ZLOG_WARNING, "unable to get scoreboard while preparing the access log"); return -1; } proc_p = fpm_scoreboard_proc_acquire(NULL, -1, 0); if (!proc_p) { zlog(ZLOG_WARNING, "[pool %s] Unable to acquire shm slot while preparing the access log", scoreboard->pool); return -1; } proc = *proc_p; fpm_scoreboard_proc_release(proc_p); } token = 0; memset(buffer, '\0', sizeof(buffer)); b = buffer; len = 0; s = log_format; while (*s != '\0') { /* Test is we have place for 1 more char. */ if (len >= FPM_LOG_BUFFER) { zlog(ZLOG_NOTICE, "the log buffer is full (%d). The access log request has been truncated.", FPM_LOG_BUFFER); len = FPM_LOG_BUFFER; break; } if (!token && *s == '%') { token = 1; memset(format, '\0', sizeof(format)); /* reset format */ s++; continue; } if (token) { token = 0; len2 = 0; switch (*s) { case '%': /* '%' */ *b = '%'; len2 = 1; break; #ifdef HAVE_TIMES case 'C': /* %CPU */ if (format[0] == '\0' || !strcasecmp(format, "total")) { if (!test) { tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cutime + proc.last_request_cpu.tms_cstime; } } else if (!strcasecmp(format, "user")) { if (!test) { tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_cutime; } } else if (!strcasecmp(format, "system")) { if (!test) { tms_total = proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cstime; } } else { zlog(ZLOG_WARNING, "only 'total', 'user' or 'system' are allowed as a modifier for %%%c ('%s')", *s, format); return -1; } format[0] = '\0'; if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.2f", tms_total / fpm_scoreboard_get_tick() / (proc.cpu_duration.tv_sec + proc.cpu_duration.tv_usec / 1000000.) * 100.); } break; #endif case 'd': /* duration µs */ /* seconds */ if (format[0] == '\0' || !strcasecmp(format, "seconds")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec + proc.duration.tv_usec / 1000000.); } /* miliseconds */ } else if (!strcasecmp(format, "miliseconds") || !strcasecmp(format, "mili")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec * 1000. + proc.duration.tv_usec / 1000.); } /* microseconds */ } else if (!strcasecmp(format, "microseconds") || !strcasecmp(format, "micro")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.duration.tv_sec * 1000000UL + proc.duration.tv_usec); } } else { zlog(ZLOG_WARNING, "only 'seconds', 'mili', 'miliseconds', 'micro' or 'microseconds' are allowed as a modifier for %%%c ('%s')", *s, format); return -1; } format[0] = '\0'; break; case 'e': /* fastcgi env */ if (format[0] == '\0') { zlog(ZLOG_WARNING, "the name of the environment variable must be set between embraces for %%%c", *s); return -1; } if (!test) { char *env = fcgi_getenv((fcgi_request*) SG(server_context), format, strlen(format)); len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", env ? env : "-"); } format[0] = '\0'; break; case 'f': /* script */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.script_filename ? proc.script_filename : "-"); } break; case 'l': /* content length */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.content_length); } break; case 'm': /* method */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.request_method ? proc.request_method : "-"); } break; case 'M': /* memory */ /* seconds */ if (format[0] == '\0' || !strcasecmp(format, "bytes")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.memory); } /* kilobytes */ } else if (!strcasecmp(format, "kilobytes") || !strcasecmp(format, "kilo")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024); } /* megabytes */ } else if (!strcasecmp(format, "megabytes") || !strcasecmp(format, "mega")) { if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024 / 1024); } } else { zlog(ZLOG_WARNING, "only 'bytes', 'kilo', 'kilobytes', 'mega' or 'megabytes' are allowed as a modifier for %%%c ('%s')", *s, format); return -1; } format[0] = '\0'; break; case 'n': /* pool name */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", scoreboard->pool[0] ? scoreboard->pool : "-"); } break; case 'o': /* header output */ if (format[0] == '\0') { zlog(ZLOG_WARNING, "the name of the header must be set between embraces for %%%c", *s); return -1; } if (!test) { sapi_header_struct *h; zend_llist_position pos; sapi_headers_struct *sapi_headers = &SG(sapi_headers); size_t format_len = strlen(format); h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos); while (h) { char *header; if (!h->header_len) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } if (!strstr(h->header, format)) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } /* test if enought char after the header name + ': ' */ if (h->header_len <= format_len + 2) { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } if (h->header[format_len] != ':' || h->header[format_len + 1] != ' ') { h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos); continue; } header = h->header + format_len + 2; len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", header && *header ? header : "-"); /* found, done */ break; } if (!len2) { len2 = 1; *b = '-'; } } format[0] = '\0'; break; case 'p': /* PID */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getpid()); } break; case 'P': /* PID */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getppid()); } break; case 'q': /* query_string */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.query_string); } break; case 'Q': /* '?' */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.query_string ? "?" : ""); } break; case 'r': /* request URI */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.request_uri); } break; case 'R': /* remote IP address */ if (!test) { const char *tmp = fcgi_get_last_client_ip(); len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp ? tmp : "-"); } break; case 's': /* status */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%d", SG(sapi_headers).http_response_code); } break; case 'T': case 't': /* time */ if (!test) { time_t *t; if (*s == 't') { t = &proc.accepted_epoch; } else { t = &now_epoch; } if (format[0] == '\0') { strftime(tmp, sizeof(tmp) - 1, "%d/%b/%Y:%H:%M:%S %z", localtime(t)); } else { strftime(tmp, sizeof(tmp) - 1, format, localtime(t)); } len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp); } format[0] = '\0'; break; case 'u': /* remote user */ if (!test) { len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.auth_user); } break; case '{': /* complex var */ token = 1; { char *start; size_t l; start = ++s; while (*s != '\0') { if (*s == '}') { l = s - start; if (l >= sizeof(format) - 1) { l = sizeof(format) - 1; } memcpy(format, start, l); format[l] = '\0'; break; } s++; } if (s[1] == '\0') { zlog(ZLOG_WARNING, "missing closing embrace in the access.format"); return -1; } } break; default: zlog(ZLOG_WARNING, "Invalid token in the access.format (%%%c)", *s); return -1; } if (*s != '}' && format[0] != '\0') { zlog(ZLOG_WARNING, "embrace is not allowed for modifier %%%c", *s); return -1; } s++; if (!test) { b += len2; len += len2; } if (len >= FPM_LOG_BUFFER) { zlog(ZLOG_NOTICE, "the log buffer is full (%d). The access log request has been truncated.", FPM_LOG_BUFFER); len = FPM_LOG_BUFFER; break; } continue; } if (!test) { // push the normal char to the output buffer *b = *s; b++; len++; } s++; } if (!test && strlen(buffer) > 0) { buffer[len] = '\n'; write(fpm_log_fd, buffer, len + 1); } return 0; } /* }}} */
./CrossVul/dataset_final_sorted/CWE-125/c/good_5094_0
crossvul-cpp_data_good_4493_1
/************************************************************************* * * $Id: triostr.c,v 1.36 2010/01/26 13:02:02 breese Exp $ * * Copyright (C) 2001 Bjorn Reese and Daniel Stenberg. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER. * ************************************************************************/ /************************************************************************* * Include files */ #if defined(HAVE_CONFIG_H) #include <config.h> #endif #include <assert.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <ctype.h> #include "triodef.h" #include "triostr.h" #if defined(TRIO_FUNC_TO_LONG_DOUBLE) #define USE_MATH #endif #if defined(USE_MATH) #include <math.h> #endif /************************************************************************* * Definitions */ #if !defined(TRIO_PUBLIC_STRING) #define TRIO_PUBLIC_STRING TRIO_PUBLIC #endif #if !defined(TRIO_PRIVATE_STRING) #define TRIO_PRIVATE_STRING TRIO_PRIVATE #endif #if !defined(NULL) #define NULL 0 #endif #if !defined(NIL) #define NIL ((char)0) #endif #if !defined(FALSE) #define FALSE (1 == 0) #define TRUE (!FALSE) #endif #if !defined(BOOLEAN_T) #define BOOLEAN_T int #endif #if defined(USE_MATH) #if defined(PREDEF_STANDARD_C99) #if defined(TRIO_COMPILER_DECC) #if (TRIO_COMPILER_DECC - 0 > 80000000) /* * The OSF/1 runtime that comes with the DECC compiler does not support * hexfloats conversion. */ #define USE_STRTOD #define USE_STRTOF #endif #else #define USE_STRTOD #define USE_STRTOF #endif #else #if defined(TRIO_COMPILER_VISUALC) #define USE_STRTOD #endif #endif #endif #if defined(TRIO_PLATFORM_UNIX) #if defined(PREDEF_STANDARD_UNIX95) #define USE_STRCASECMP #define USE_STRNCASECMP #endif #if defined(TRIO_PLATFORM_SUNOS) #define USE_SYS_ERRLIST #else #define USE_STRERROR #endif #if defined(TRIO_PLATFORM_QNX) #define strcasecmp(x, y) stricmp(x, y) #define strncasecmp(x, y, n) strnicmp(x, y, n) #endif #endif #if defined(TRIO_PLATFORM_WIN32) #define USE_STRCASECMP #if defined(TRIO_PLATFORM_WINCE) #define strcasecmp(x, y) _stricmp(x, y) #else #define strcasecmp(x, y) _stricmp(x, y) #endif #endif #if !defined(HAVE_CONFIG_H) #if !(defined(TRIO_PLATFORM_SUNOS)) #define HAVE_TOLOWER #define HAVE_TOUPPER #endif #endif #if defined(USE_MATH) && !defined(TRIO_NO_POWL) #if !defined(HAVE_POWL) #if defined(PREDEF_STANDARD_C99) || defined(PREDEF_STANDARD_UNIX03) #define HAVE_POWL #else #if defined(TRIO_COMPILER_VISUALC) #if defined(powl) #define HAVE_POWL #endif #endif #endif #endif #endif #if defined(HAVE_POWL) #define trio_powl(x, y) powl((x), (y)) #else #define trio_powl(x, y) pow((double)(x), (double)(y)) #endif #if defined(TRIO_FUNC_TO_UPPER) || (defined(TRIO_FUNC_EQUAL) && !defined(USE_STRCASECMP)) || \ (defined(TRIO_FUNC_EQUAL_MAX) && !defined(USE_STRNCASECMP)) || defined(TRIO_FUNC_MATCH) || \ defined(TRIO_FUNC_TO_LONG_DOUBLE) || defined(TRIO_FUNC_UPPER) #define TRIO_FUNC_INTERNAL_TO_UPPER #endif /************************************************************************* * Structures */ struct _trio_string_t { char* content; size_t length; size_t allocated; }; /************************************************************************* * Constants */ #if !defined(TRIO_EMBED_STRING) /* Unused but kept for reference */ /* static TRIO_CONST char rcsid[] = "@(#)$Id: triostr.c,v 1.36 2010/01/26 13:02:02 breese Exp $"; */ #endif /************************************************************************* * Static String Functions */ #if defined(TRIO_DOCUMENTATION) #include "doc/doc_static.h" #endif /** @addtogroup StaticStrings @{ */ /* * internal_duplicate_max */ #if defined(TRIO_FUNC_DUPLICATE) || defined(TRIO_FUNC_DUPLICATE_MAX) || \ defined(TRIO_FUNC_STRING_DUPLICATE) || defined(TRIO_FUNC_XSTRING_DUPLICATE) TRIO_PRIVATE_STRING char* internal_duplicate_max TRIO_ARGS2((source, size), TRIO_CONST char* source, size_t size) { char* target; assert(source); /* Make room for string plus a terminating zero */ size++; target = trio_create(size); if (target) { trio_copy_max(target, size, source); } return target; } #endif /* * internal_string_alloc */ #if defined(TRIO_FUNC_STRING_CREATE) || defined(TRIO_FUNC_STRING_DUPLICATE) || \ defined(TRIO_FUNC_XSTRING_DUPLICATE) TRIO_PRIVATE_STRING trio_string_t* internal_string_alloc(TRIO_NOARGS) { trio_string_t* self; self = (trio_string_t*)TRIO_MALLOC(sizeof(trio_string_t)); if (self) { self->content = NULL; self->length = 0; self->allocated = 0; } return self; } #endif /* * internal_string_grow * * The size of the string will be increased by 'delta' characters. If * 'delta' is zero, the size will be doubled. */ #if defined(TRIO_FUNC_STRING_CREATE) || defined(TRIO_FUNC_STRING_APPEND) || \ defined(TRIO_FUNC_XSTRING_APPEND) || defined(TRIO_FUNC_XSTRING_APPEND_CHAR) TRIO_PRIVATE_STRING BOOLEAN_T internal_string_grow TRIO_ARGS2((self, delta), trio_string_t* self, size_t delta) { BOOLEAN_T status = FALSE; char* new_content; size_t new_size; new_size = (delta == 0) ? ((self->allocated == 0) ? 1 : self->allocated * 2) : self->allocated + delta; new_content = (char*)TRIO_REALLOC(self->content, new_size); if (new_content) { self->content = new_content; self->allocated = new_size; status = TRUE; } return status; } #endif /* * internal_string_grow_to * * The size of the string will be increased to 'length' plus one characters. * If 'length' is less than the original size, the original size will be * used (that is, the size of the string is never decreased). */ #if defined(TRIO_FUNC_STRING_APPEND) || defined(TRIO_FUNC_XSTRING_APPEND) || \ defined(TRIO_FUNC_XSTRING_APPEND_MAX) TRIO_PRIVATE_STRING BOOLEAN_T internal_string_grow_to TRIO_ARGS2((self, length), trio_string_t* self, size_t length) { length++; /* Room for terminating zero */ return (self->allocated < length) ? internal_string_grow(self, length - self->allocated) : TRUE; } #endif #if defined(TRIO_FUNC_INTERNAL_TO_UPPER) TRIO_PRIVATE_STRING TRIO_INLINE int internal_to_upper TRIO_ARGS1((source), int source) { #if defined(HAVE_TOUPPER) return toupper(source); #else /* Does not handle locales or non-contiguous alphabetic characters */ return ((source >= (int)'a') && (source <= (int)'z')) ? source - 'a' + 'A' : source; #endif } #endif /** Create new string. @param size Size of new string. @return Pointer to string, or NULL if allocation failed. */ #if defined(TRIO_FUNC_CREATE) TRIO_PUBLIC_STRING char* trio_create TRIO_ARGS1((size), size_t size) { return (char*)TRIO_MALLOC(size); } #endif /** Destroy string. @param string String to be freed. */ #if defined(TRIO_FUNC_DESTROY) TRIO_PUBLIC_STRING void trio_destroy TRIO_ARGS1((string), char* string) { if (string) { TRIO_FREE(string); } } #endif /** Count the number of characters in a string. @param string String to measure. @return Number of characters in @p string. */ #if defined(TRIO_FUNC_LENGTH) TRIO_PUBLIC_STRING size_t trio_length TRIO_ARGS1((string), TRIO_CONST char* string) { return trio_length_max(string, INT_MAX); } #endif /** Count at most @p max characters in a string. @param string String to measure. @param max Maximum number of characters to count. @return The maximum value of @p max and number of characters in @p string. */ #if defined(TRIO_FUNC_LENGTH_MAX) TRIO_PUBLIC_STRING size_t trio_length_max TRIO_ARGS2((string, max), TRIO_CONST char* string, size_t max) { size_t i; for (i = 0; i < max; ++i) { if (string[i] == 0) break; } return i; } #endif /** Append @p source at the end of @p target. @param target Target string. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chunk with sufficient room to contain the @p target string and @p source string. @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ #if defined(TRIO_FUNC_APPEND) TRIO_PUBLIC_STRING int trio_append TRIO_ARGS2((target, source), char* target, TRIO_CONST char* source) { assert(target); assert(source); return (strcat(target, source) != NULL); } #endif /** Append at most @p max characters from @p source to @p target. @param target Target string. @param max Maximum number of characters to append. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chuck with sufficient room to contain the @p target string and the @p source string (at most @p max characters). @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ #if defined(TRIO_FUNC_APPEND_MAX) TRIO_PUBLIC_STRING int trio_append_max TRIO_ARGS3((target, max, source), char* target, size_t max, TRIO_CONST char* source) { size_t length; assert(target); assert(source); length = trio_length(target); if (max > length) { strncat(target, source, max - length - 1); } return TRUE; } #endif /** Determine if a string contains a substring. @param string String to be searched. @param substring String to be found. @return Boolean value indicating success or failure. */ #if defined(TRIO_FUNC_CONTAINS) TRIO_PUBLIC_STRING int trio_contains TRIO_ARGS2((string, substring), TRIO_CONST char* string, TRIO_CONST char* substring) { assert(string); assert(substring); return (0 != strstr(string, substring)); } #endif /** Copy @p source to @p target. @param target Target string. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chunk with sufficient room to contain the @p source string. @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ #if defined(TRIO_FUNC_COPY) TRIO_PUBLIC_STRING int trio_copy TRIO_ARGS2((target, source), char* target, TRIO_CONST char* source) { assert(target); assert(source); (void)strcpy(target, source); return TRUE; } #endif /** Copy at most @p max - 1 characters from @p source to @p target. @param target Target string. @param max Maximum number of characters to append (one of which is a NUL terminator). In other words @p source must point to at least @p max - 1 bytes, but @p target must point to at least @p max bytes. @param source Source string. @return Boolean value indicating success or failure. @pre @p target must point to a memory chunk with sufficient room to contain the @p source string and a NUL terminator (at most @p max bytes total). @pre No boundary checking is performed, so insufficient memory will result in a buffer overrun. @post @p target will be zero terminated. */ #if defined(TRIO_FUNC_COPY_MAX) TRIO_PUBLIC_STRING int trio_copy_max TRIO_ARGS3((target, max, source), char* target, size_t max, TRIO_CONST char* source) { assert(target); assert(source); assert(max > 0); /* Includes != 0 */ (void)strncpy(target, source, max - 1); target[max - 1] = (char)0; return TRUE; } #endif /** Duplicate @p source. @param source Source string. @return A copy of the @p source string. @post @p target will be zero terminated. */ #if defined(TRIO_FUNC_DUPLICATE) TRIO_PUBLIC_STRING char* trio_duplicate TRIO_ARGS1((source), TRIO_CONST char* source) { return internal_duplicate_max(source, trio_length(source)); } #endif /** Duplicate at most @p max characters of @p source. @param source Source string. @param max Maximum number of characters to duplicate. @return A copy of the @p source string. @post @p target will be zero terminated. */ #if defined(TRIO_FUNC_DUPLICATE_MAX) TRIO_PUBLIC_STRING char* trio_duplicate_max TRIO_ARGS2((source, max), TRIO_CONST char* source, size_t max) { size_t length; assert(source); assert(max > 0); length = trio_length(source); if (length > max) { length = max; } return internal_duplicate_max(source, length); } #endif /** Compare if two strings are equal. @param first First string. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-insensitive comparison. */ #if defined(TRIO_FUNC_EQUAL) TRIO_PUBLIC_STRING int trio_equal TRIO_ARGS2((first, second), TRIO_CONST char* first, TRIO_CONST char* second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { #if defined(USE_STRCASECMP) return (0 == strcasecmp(first, second)); #else while ((*first != NIL) && (*second != NIL)) { if (internal_to_upper(*first) != internal_to_upper(*second)) { break; } first++; second++; } return ((*first == NIL) && (*second == NIL)); #endif } return FALSE; } #endif /** Compare if two strings are equal. @param first First string. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-sensitive comparison. */ #if defined(TRIO_FUNC_EQUAL_CASE) TRIO_PUBLIC_STRING int trio_equal_case TRIO_ARGS2((first, second), TRIO_CONST char* first, TRIO_CONST char* second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { return (0 == strcmp(first, second)); } return FALSE; } #endif /** Compare if two strings up until the first @p max characters are equal. @param first First string. @param max Maximum number of characters to compare. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-sensitive comparison. */ #if defined(TRIO_FUNC_EQUAL_CASE_MAX) TRIO_PUBLIC_STRING int trio_equal_case_max TRIO_ARGS3((first, max, second), TRIO_CONST char* first, size_t max, TRIO_CONST char* second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { return (0 == strncmp(first, second, max)); } return FALSE; } #endif /** Compare if two strings are equal. @param first First string. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Collating characters are considered equal. */ #if defined(TRIO_FUNC_EQUAL_LOCALE) TRIO_PUBLIC_STRING int trio_equal_locale TRIO_ARGS2((first, second), TRIO_CONST char* first, TRIO_CONST char* second) { assert(first); assert(second); #if defined(LC_COLLATE) return (strcoll(first, second) == 0); #else return trio_equal(first, second); #endif } #endif /** Compare if two strings up until the first @p max characters are equal. @param first First string. @param max Maximum number of characters to compare. @param second Second string. @return Boolean indicating whether the two strings are equal or not. Case-insensitive comparison. */ #if defined(TRIO_FUNC_EQUAL_MAX) TRIO_PUBLIC_STRING int trio_equal_max TRIO_ARGS3((first, max, second), TRIO_CONST char* first, size_t max, TRIO_CONST char* second) { assert(first); assert(second); if ((first != NULL) && (second != NULL)) { #if defined(USE_STRNCASECMP) return (0 == strncasecmp(first, second, max)); #else /* Not adequately tested yet */ size_t cnt = 0; while ((*first != NIL) && (*second != NIL) && (cnt <= max)) { if (internal_to_upper(*first) != internal_to_upper(*second)) { break; } first++; second++; cnt++; } return ((cnt == max) || ((*first == NIL) && (*second == NIL))); #endif } return FALSE; } #endif /** Provide a textual description of an error code (errno). @param error_number Error number. @return Textual description of @p error_number. */ #if defined(TRIO_FUNC_ERROR) TRIO_PUBLIC_STRING TRIO_CONST char* trio_error TRIO_ARGS1((error_number), int error_number) { #if defined(USE_STRERROR) return strerror(error_number); #else #if defined(USE_SYS_ERRLIST) extern char* sys_errlist[]; extern int sys_nerr; return ((error_number < 0) || (error_number >= sys_nerr)) ? "unknown" : sys_errlist[error_number]; #else return "unknown"; #endif #endif } #endif /** Format the date/time according to @p format. @param target Target string. @param max Maximum number of characters to format. @param format Formatting string. @param datetime Date/time structure. @return Number of formatted characters. The formatting string accepts the same specifiers as the standard C function strftime. */ #if defined(TRIO_FUNC_FORMAT_DATE_MAX) TRIO_PUBLIC_STRING size_t trio_format_date_max TRIO_ARGS4((target, max, format, datetime), char* target, size_t max, TRIO_CONST char* format, TRIO_CONST struct tm* datetime) { assert(target); assert(format); assert(datetime); assert(max > 0); return strftime(target, max, format, datetime); } #endif /** Calculate a hash value for a string. @param string String to be calculated on. @param type Hash function. @return Calculated hash value. @p type can be one of the following @li @c TRIO_HASH_PLAIN Plain hash function. */ #if defined(TRIO_FUNC_HASH) TRIO_PUBLIC_STRING unsigned long trio_hash TRIO_ARGS2((string, type), TRIO_CONST char* string, int type) { unsigned long value = 0L; char ch; assert(string); switch (type) { case TRIO_HASH_PLAIN: while ((ch = *string++) != NIL) { value *= 31; value += (unsigned long)ch; } break; default: assert(FALSE); break; } return value; } #endif /** Find first occurrence of a character in a string. @param string String to be searched. @param character Character to be found. @return A pointer to the found character, or NULL if character was not found. */ #if defined(TRIO_FUNC_INDEX) TRIO_PUBLIC_STRING char* trio_index TRIO_ARGS2((string, character), TRIO_CONST char* string, int character) { assert(string); return strchr(string, character); } #endif /** Find last occurrence of a character in a string. @param string String to be searched. @param character Character to be found. @return A pointer to the found character, or NULL if character was not found. */ #if defined(TRIO_FUNC_INDEX_LAST) TRIO_PUBLIC_STRING char* trio_index_last TRIO_ARGS2((string, character), TRIO_CONST char* string, int character) { assert(string); return strchr(string, character); } #endif /** Convert the alphabetic letters in the string to lower-case. @param target String to be converted. @return Number of processed characters (converted or not). */ #if defined(TRIO_FUNC_LOWER) TRIO_PUBLIC_STRING int trio_lower TRIO_ARGS1((target), char* target) { assert(target); return trio_span_function(target, target, trio_to_lower); } #endif /** Compare two strings using wildcards. @param string String to be searched. @param pattern Pattern, including wildcards, to search for. @return Boolean value indicating success or failure. Case-insensitive comparison. The following wildcards can be used @li @c * Match any number of characters. @li @c ? Match a single character. */ #if defined(TRIO_FUNC_MATCH) TRIO_PUBLIC_STRING int trio_match TRIO_ARGS2((string, pattern), TRIO_CONST char* string, TRIO_CONST char* pattern) { assert(string); assert(pattern); for (; ('*' != *pattern); ++pattern, ++string) { if (NIL == *string) { return (NIL == *pattern); } if ((internal_to_upper((int)*string) != internal_to_upper((int)*pattern)) && ('?' != *pattern)) { return FALSE; } } /* two-line patch to prevent *too* much recursiveness: */ while ('*' == pattern[1]) pattern++; do { if (trio_match(string, &pattern[1])) { return TRUE; } } while (*string++); return FALSE; } #endif /** Compare two strings using wildcards. @param string String to be searched. @param pattern Pattern, including wildcards, to search for. @return Boolean value indicating success or failure. Case-sensitive comparison. The following wildcards can be used @li @c * Match any number of characters. @li @c ? Match a single character. */ #if defined(TRIO_FUNC_MATCH_CASE) TRIO_PUBLIC_STRING int trio_match_case TRIO_ARGS2((string, pattern), TRIO_CONST char* string, TRIO_CONST char* pattern) { assert(string); assert(pattern); for (; ('*' != *pattern); ++pattern, ++string) { if (NIL == *string) { return (NIL == *pattern); } if ((*string != *pattern) && ('?' != *pattern)) { return FALSE; } } /* two-line patch to prevent *too* much recursiveness: */ while ('*' == pattern[1]) pattern++; do { if (trio_match_case(string, &pattern[1])) { return TRUE; } } while (*string++); return FALSE; } #endif /** Execute a function on each character in string. @param target Target string. @param source Source string. @param Function Function to be executed. @return Number of processed characters. */ #if defined(TRIO_FUNC_SPAN_FUNCTION) TRIO_PUBLIC_STRING size_t trio_span_function TRIO_ARGS3((target, source, Function), char* target, TRIO_CONST char* source, int(*Function) TRIO_PROTO((int))) { size_t count = 0; assert(target); assert(source); assert(Function); while (*source != NIL) { *target++ = Function(*source++); count++; } return count; } #endif /** Search for a substring in a string. @param string String to be searched. @param substring String to be found. @return Pointer to first occurrence of @p substring in @p string, or NULL if no match was found. */ #if defined(TRIO_FUNC_SUBSTRING) TRIO_PUBLIC_STRING char* trio_substring TRIO_ARGS2((string, substring), TRIO_CONST char* string, TRIO_CONST char* substring) { assert(string); assert(substring); return strstr(string, substring); } #endif /** Search for a substring in the first @p max characters of a string. @param string String to be searched. @param max Maximum characters to be searched. @param substring String to be found. @return Pointer to first occurrence of @p substring in @p string, or NULL if no match was found. */ #if defined(TRIO_FUNC_SUBSTRING_MAX) TRIO_PUBLIC_STRING char* trio_substring_max TRIO_ARGS3((string, max, substring), TRIO_CONST char* string, size_t max, TRIO_CONST char* substring) { size_t count; size_t size; char* result = NULL; assert(string); assert(substring); size = trio_length(substring); if (size <= max) { for (count = 0; count <= max - size; count++) { if (trio_equal_max(substring, size, &string[count])) { result = (char*)&string[count]; break; } } } return result; } #endif /** Tokenize string. @param string String to be tokenized. @param delimiters String containing list of delimiting characters. @return Start of new token. @warning @p string will be destroyed. */ #if defined(TRIO_FUNC_TOKENIZE) TRIO_PUBLIC_STRING char* trio_tokenize TRIO_ARGS2((string, delimiters), char* string, TRIO_CONST char* delimiters) { assert(delimiters); return strtok(string, delimiters); } #endif /** Convert string to floating-point number. @param source String to be converted. @param endp Pointer to end of the converted string. @return A floating-point number. The following Extended Backus-Naur form is used @verbatim double ::= [ <sign> ] ( <number> | <number> <decimal_point> <number> | <decimal_point> <number> ) [ <exponential> [ <sign> ] <number> ] number ::= 1*( <digit> ) digit ::= ( '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ) exponential ::= ( 'e' | 'E' ) sign ::= ( '-' | '+' ) decimal_point ::= '.' @endverbatim */ #if defined(TRIO_FUNC_TO_LONG_DOUBLE) /* FIXME: Add EBNF for hex-floats */ TRIO_PUBLIC_STRING trio_long_double_t trio_to_long_double TRIO_ARGS2((source, endp), TRIO_CONST char* source, char** endp) { #if defined(USE_STRTOLD) return strtold(source, endp); #else int isNegative = FALSE; int isExponentNegative = FALSE; trio_long_double_t integer = 0.0; trio_long_double_t fraction = 0.0; unsigned long exponent = 0; trio_long_double_t base; trio_long_double_t fracdiv = 1.0; trio_long_double_t value = 0.0; /* First try hex-floats */ if ((source[0] == '0') && ((source[1] == 'x') || (source[1] == 'X'))) { base = 16.0; source += 2; while (isxdigit((int)*source)) { integer *= base; integer += (isdigit((int)*source) ? (*source - '0') : 10 + (internal_to_upper((int)*source) - 'A')); source++; } if (*source == '.') { source++; while (isxdigit((int)*source)) { fracdiv /= base; fraction += fracdiv * (isdigit((int)*source) ? (*source - '0') : 10 + (internal_to_upper((int)*source) - 'A')); source++; } if ((*source == 'p') || (*source == 'P')) { source++; if ((*source == '+') || (*source == '-')) { isExponentNegative = (*source == '-'); source++; } while (isdigit((int)*source)) { exponent *= 10; exponent += (*source - '0'); source++; } } } /* For later use with exponent */ base = 2.0; } else /* Then try normal decimal floats */ { base = 10.0; isNegative = (*source == '-'); /* Skip sign */ if ((*source == '+') || (*source == '-')) source++; /* Integer part */ while (isdigit((int)*source)) { integer *= base; integer += (*source - '0'); source++; } if (*source == '.') { source++; /* skip decimal point */ while (isdigit((int)*source)) { fracdiv /= base; fraction += (*source - '0') * fracdiv; source++; } } if ((*source == 'e') || (*source == 'E') #if TRIO_MICROSOFT || (*source == 'd') || (*source == 'D') #endif ) { source++; /* Skip exponential indicator */ isExponentNegative = (*source == '-'); if ((*source == '+') || (*source == '-')) source++; while (isdigit((int)*source)) { exponent *= (int)base; exponent += (*source - '0'); source++; } } } value = integer + fraction; if (exponent != 0) { if (isExponentNegative) value /= trio_powl(base, (trio_long_double_t)exponent); else value *= trio_powl(base, (trio_long_double_t)exponent); } if (isNegative) value = -value; if (endp) *endp = (char*)source; return value; #endif } #endif /** Convert string to floating-point number. @param source String to be converted. @param endp Pointer to end of the converted string. @return A floating-point number. See @ref trio_to_long_double. */ #if defined(TRIO_FUNC_TO_DOUBLE) TRIO_PUBLIC_STRING double trio_to_double TRIO_ARGS2((source, endp), TRIO_CONST char* source, char** endp) { #if defined(USE_STRTOD) return strtod(source, endp); #else return (double)trio_to_long_double(source, endp); #endif } #endif /** Convert string to floating-point number. @param source String to be converted. @param endp Pointer to end of the converted string. @return A floating-point number. See @ref trio_to_long_double. */ #if defined(TRIO_FUNC_TO_FLOAT) TRIO_PUBLIC_STRING float trio_to_float TRIO_ARGS2((source, endp), TRIO_CONST char* source, char** endp) { #if defined(USE_STRTOF) return strtof(source, endp); #else return (float)trio_to_long_double(source, endp); #endif } #endif /** Convert string to signed integer. @param string String to be converted. @param endp Pointer to end of converted string. @param base Radix number of number. */ #if defined(TRIO_FUNC_TO_LONG) TRIO_PUBLIC_STRING long trio_to_long TRIO_ARGS3((string, endp, base), TRIO_CONST char* string, char** endp, int base) { assert(string); assert((base >= 2) && (base <= 36)); return strtol(string, endp, base); } #endif /** Convert one alphabetic letter to lower-case. @param source The letter to be converted. @return The converted letter. */ #if defined(TRIO_FUNC_TO_LOWER) TRIO_PUBLIC_STRING int trio_to_lower TRIO_ARGS1((source), int source) { #if defined(HAVE_TOLOWER) return tolower(source); #else /* Does not handle locales or non-contiguous alphabetic characters */ return ((source >= (int)'A') && (source <= (int)'Z')) ? source - 'A' + 'a' : source; #endif } #endif /** Convert string to unsigned integer. @param string String to be converted. @param endp Pointer to end of converted string. @param base Radix number of number. */ #if defined(TRIO_FUNC_TO_UNSIGNED_LONG) TRIO_PUBLIC_STRING unsigned long trio_to_unsigned_long TRIO_ARGS3((string, endp, base), TRIO_CONST char* string, char** endp, int base) { assert(string); assert((base >= 2) && (base <= 36)); return strtoul(string, endp, base); } #endif /** Convert one alphabetic letter to upper-case. @param source The letter to be converted. @return The converted letter. */ #if defined(TRIO_FUNC_TO_UPPER) TRIO_PUBLIC_STRING int trio_to_upper TRIO_ARGS1((source), int source) { return internal_to_upper(source); } #endif /** Convert the alphabetic letters in the string to upper-case. @param target The string to be converted. @return The number of processed characters (converted or not). */ #if defined(TRIO_FUNC_UPPER) TRIO_PUBLIC_STRING int trio_upper TRIO_ARGS1((target), char* target) { assert(target); return trio_span_function(target, target, internal_to_upper); } #endif /** @} End of StaticStrings */ /************************************************************************* * Dynamic String Functions */ #if defined(TRIO_DOCUMENTATION) #include "doc/doc_dynamic.h" #endif /** @addtogroup DynamicStrings @{ */ /** Create a new dynamic string. @param initial_size Initial size of the buffer. @return Newly allocated dynamic string, or NULL if memory allocation failed. */ #if defined(TRIO_FUNC_STRING_CREATE) TRIO_PUBLIC_STRING trio_string_t* trio_string_create TRIO_ARGS1((initial_size), int initial_size) { trio_string_t* self; self = internal_string_alloc(); if (self) { if (internal_string_grow(self, (size_t)((initial_size > 0) ? initial_size : 1))) { self->content[0] = (char)0; self->allocated = initial_size; } else { trio_string_destroy(self); self = NULL; } } return self; } #endif /** Deallocate the dynamic string and its contents. @param self Dynamic string */ #if defined(TRIO_FUNC_STRING_DESTROY) TRIO_PUBLIC_STRING void trio_string_destroy TRIO_ARGS1((self), trio_string_t* self) { assert(self); if (self) { trio_destroy(self->content); TRIO_FREE(self); } } #endif /** Get a pointer to the content. @param self Dynamic string. @param offset Offset into content. @return Pointer to the content. @p Offset can be zero, positive, or negative. If @p offset is zero, then the start of the content will be returned. If @p offset is positive, then a pointer to @p offset number of characters from the beginning of the content is returned. If @p offset is negative, then a pointer to @p offset number of characters from the ending of the string, starting at the terminating zero, is returned. */ #if defined(TRIO_FUNC_STRING_GET) TRIO_PUBLIC_STRING char* trio_string_get TRIO_ARGS2((self, offset), trio_string_t* self, int offset) { char* result = NULL; assert(self); if (self->content != NULL) { if (self->length == 0) { (void)trio_string_length(self); } if (offset >= 0) { if (offset > (int)self->length) { offset = self->length; } } else { offset += self->length + 1; if (offset < 0) { offset = 0; } } result = &(self->content[offset]); } return result; } #endif /** Extract the content. @param self Dynamic String @return Content of dynamic string. The content is removed from the dynamic string. This enables destruction of the dynamic string without deallocation of the content. */ #if defined(TRIO_FUNC_STRING_EXTRACT) TRIO_PUBLIC_STRING char* trio_string_extract TRIO_ARGS1((self), trio_string_t* self) { char* result; assert(self); result = self->content; /* FIXME: Allocate new empty buffer? */ self->content = NULL; self->length = self->allocated = 0; return result; } #endif /** Set the content of the dynamic string. @param self Dynamic String @param buffer The new content. Sets the content of the dynamic string to a copy @p buffer. An existing content will be deallocated first, if necessary. @remark This function will make a copy of @p buffer. You are responsible for deallocating @p buffer yourself. */ #if defined(TRIO_FUNC_XSTRING_SET) TRIO_PUBLIC_STRING void trio_xstring_set TRIO_ARGS2((self, buffer), trio_string_t* self, char* buffer) { assert(self); trio_destroy(self->content); self->content = trio_duplicate(buffer); } #endif /* * trio_string_size */ #if defined(TRIO_FUNC_STRING_SIZE) TRIO_PUBLIC_STRING int trio_string_size TRIO_ARGS1((self), trio_string_t* self) { assert(self); return self->allocated; } #endif /* * trio_string_terminate */ #if defined(TRIO_FUNC_STRING_TERMINATE) TRIO_PUBLIC_STRING void trio_string_terminate TRIO_ARGS1((self), trio_string_t* self) { trio_xstring_append_char(self, 0); } #endif /** Append the second string to the first. @param self Dynamic string to be modified. @param other Dynamic string to copy from. @return Boolean value indicating success or failure. */ #if defined(TRIO_FUNC_STRING_APPEND) TRIO_PUBLIC_STRING int trio_string_append TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { size_t length; assert(self); assert(other); length = self->length + other->length; if (!internal_string_grow_to(self, length)) goto error; trio_copy(&self->content[self->length], other->content); self->length = length; return TRUE; error: return FALSE; } #endif /* * trio_xstring_append */ #if defined(TRIO_FUNC_XSTRING_APPEND) TRIO_PUBLIC_STRING int trio_xstring_append TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { size_t length; assert(self); assert(other); length = self->length + trio_length(other); if (!internal_string_grow_to(self, length)) goto error; trio_copy(&self->content[self->length], other); self->length = length; return TRUE; error: return FALSE; } #endif /* * trio_xstring_append_char */ #if defined(TRIO_FUNC_XSTRING_APPEND_CHAR) TRIO_PUBLIC_STRING int trio_xstring_append_char TRIO_ARGS2((self, character), trio_string_t* self, char character) { assert(self); if ((int)self->length >= trio_string_size(self)) { if (!internal_string_grow(self, 0)) goto error; } self->content[self->length] = character; self->length++; return TRUE; error: return FALSE; } #endif /* * trio_xstring_append_max */ #if defined(TRIO_FUNC_XSTRING_APPEND_MAX) TRIO_PUBLIC_STRING int trio_xstring_append_max TRIO_ARGS3((self, other, max), trio_string_t* self, TRIO_CONST char* other, size_t max) { size_t length; assert(self); assert(other); length = self->length + trio_length_max(other, max); if (!internal_string_grow_to(self, length)) goto error; /* * Pass max + 1 since trio_copy_max copies one character less than * this from the source to make room for a terminating zero. */ trio_copy_max(&self->content[self->length], max + 1, other); self->length = length; return TRUE; error: return FALSE; } #endif /** Search for the first occurrence of second parameter in the first. @param self Dynamic string to be modified. @param other Dynamic string to copy from. @return Boolean value indicating success or failure. */ #if defined(TRIO_FUNC_STRING_CONTAINS) TRIO_PUBLIC_STRING int trio_string_contains TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { assert(self); assert(other); return trio_contains(self->content, other->content); } #endif /* * trio_xstring_contains */ #if defined(TRIO_FUNC_XSTRING_CONTAINS) TRIO_PUBLIC_STRING int trio_xstring_contains TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { assert(self); assert(other); return trio_contains(self->content, other); } #endif /* * trio_string_copy */ #if defined(TRIO_FUNC_STRING_COPY) TRIO_PUBLIC_STRING int trio_string_copy TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { assert(self); assert(other); self->length = 0; return trio_string_append(self, other); } #endif /* * trio_xstring_copy */ #if defined(TRIO_FUNC_XSTRING_COPY) TRIO_PUBLIC_STRING int trio_xstring_copy TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { assert(self); assert(other); self->length = 0; return trio_xstring_append(self, other); } #endif /* * trio_string_duplicate */ #if defined(TRIO_FUNC_STRING_DUPLICATE) TRIO_PUBLIC_STRING trio_string_t* trio_string_duplicate TRIO_ARGS1((other), trio_string_t* other) { trio_string_t* self; assert(other); self = internal_string_alloc(); if (self) { self->content = internal_duplicate_max(other->content, other->length); if (self->content) { self->length = other->length; self->allocated = self->length + 1; } else { self->length = self->allocated = 0; } } return self; } #endif /* * trio_xstring_duplicate */ #if defined(TRIO_FUNC_XSTRING_DUPLICATE) TRIO_PUBLIC_STRING trio_string_t* trio_xstring_duplicate TRIO_ARGS1((other), TRIO_CONST char* other) { trio_string_t* self; assert(other); self = internal_string_alloc(); if (self) { self->content = internal_duplicate_max(other, trio_length(other)); if (self->content) { self->length = trio_length(self->content); self->allocated = self->length + 1; } else { self->length = self->allocated = 0; } } return self; } #endif /* * trio_string_equal */ #if defined(TRIO_FUNC_STRING_EQUAL) TRIO_PUBLIC_STRING int trio_string_equal TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { assert(self); assert(other); return trio_equal(self->content, other->content); } #endif /* * trio_xstring_equal */ #if defined(TRIO_FUNC_XSTRING_EQUAL) TRIO_PUBLIC_STRING int trio_xstring_equal TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { assert(self); assert(other); return trio_equal(self->content, other); } #endif /* * trio_string_equal_max */ #if defined(TRIO_FUNC_STRING_EQUAL_MAX) TRIO_PUBLIC_STRING int trio_string_equal_max TRIO_ARGS3((self, max, other), trio_string_t* self, size_t max, trio_string_t* other) { assert(self); assert(other); return trio_equal_max(self->content, max, other->content); } #endif /* * trio_xstring_equal_max */ #if defined(TRIO_FUNC_XSTRING_EQUAL_MAX) TRIO_PUBLIC_STRING int trio_xstring_equal_max TRIO_ARGS3((self, max, other), trio_string_t* self, size_t max, TRIO_CONST char* other) { assert(self); assert(other); return trio_equal_max(self->content, max, other); } #endif /* * trio_string_equal_case */ #if defined(TRIO_FUNC_STRING_EQUAL_CASE) TRIO_PUBLIC_STRING int trio_string_equal_case TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { assert(self); assert(other); return trio_equal_case(self->content, other->content); } #endif /* * trio_xstring_equal_case */ #if defined(TRIO_FUNC_XSTRING_EQUAL_CASE) TRIO_PUBLIC_STRING int trio_xstring_equal_case TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { assert(self); assert(other); return trio_equal_case(self->content, other); } #endif /* * trio_string_equal_case_max */ #if defined(TRIO_FUNC_STRING_EQUAL_CASE_MAX) TRIO_PUBLIC_STRING int trio_string_equal_case_max TRIO_ARGS3((self, max, other), trio_string_t* self, size_t max, trio_string_t* other) { assert(self); assert(other); return trio_equal_case_max(self->content, max, other->content); } #endif /* * trio_xstring_equal_case_max */ #if defined(TRIO_FUNC_XSTRING_EQUAL_CASE_MAX) TRIO_PUBLIC_STRING int trio_xstring_equal_case_max TRIO_ARGS3((self, max, other), trio_string_t* self, size_t max, TRIO_CONST char* other) { assert(self); assert(other); return trio_equal_case_max(self->content, max, other); } #endif /* * trio_string_format_data_max */ #if defined(TRIO_FUNC_STRING_FORMAT_DATE_MAX) TRIO_PUBLIC_STRING size_t trio_string_format_date_max TRIO_ARGS4((self, max, format, datetime), trio_string_t* self, size_t max, TRIO_CONST char* format, TRIO_CONST struct tm* datetime) { assert(self); return trio_format_date_max(self->content, max, format, datetime); } #endif /* * trio_string_index */ #if defined(TRIO_FUNC_STRING_INDEX) TRIO_PUBLIC_STRING char* trio_string_index TRIO_ARGS2((self, character), trio_string_t* self, int character) { assert(self); return trio_index(self->content, character); } #endif /* * trio_string_index_last */ #if defined(TRIO_FUNC_STRING_INDEX_LAST) TRIO_PUBLIC_STRING char* trio_string_index_last TRIO_ARGS2((self, character), trio_string_t* self, int character) { assert(self); return trio_index_last(self->content, character); } #endif /* * trio_string_length */ #if defined(TRIO_FUNC_STRING_LENGTH) TRIO_PUBLIC_STRING int trio_string_length TRIO_ARGS1((self), trio_string_t* self) { assert(self); if (self->length == 0) { self->length = trio_length(self->content); } return self->length; } #endif /* * trio_string_lower */ #if defined(TRIO_FUNC_STRING_LOWER) TRIO_PUBLIC_STRING int trio_string_lower TRIO_ARGS1((self), trio_string_t* self) { assert(self); return trio_lower(self->content); } #endif /* * trio_string_match */ #if defined(TRIO_FUNC_STRING_MATCH) TRIO_PUBLIC_STRING int trio_string_match TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { assert(self); assert(other); return trio_match(self->content, other->content); } #endif /* * trio_xstring_match */ #if defined(TRIO_FUNC_XSTRING_MATCH) TRIO_PUBLIC_STRING int trio_xstring_match TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { assert(self); assert(other); return trio_match(self->content, other); } #endif /* * trio_string_match_case */ #if defined(TRIO_FUNC_STRING_MATCH_CASE) TRIO_PUBLIC_STRING int trio_string_match_case TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { assert(self); assert(other); return trio_match_case(self->content, other->content); } #endif /* * trio_xstring_match_case */ #if defined(TRIO_FUNC_XSTRING_MATCH_CASE) TRIO_PUBLIC_STRING int trio_xstring_match_case TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { assert(self); assert(other); return trio_match_case(self->content, other); } #endif /* * trio_string_substring */ #if defined(TRIO_FUNC_STRING_SUBSTRING) TRIO_PUBLIC_STRING char* trio_string_substring TRIO_ARGS2((self, other), trio_string_t* self, trio_string_t* other) { assert(self); assert(other); return trio_substring(self->content, other->content); } #endif /* * trio_xstring_substring */ #if defined(TRIO_FUNC_XSTRING_SUBSTRING) TRIO_PUBLIC_STRING char* trio_xstring_substring TRIO_ARGS2((self, other), trio_string_t* self, TRIO_CONST char* other) { assert(self); assert(other); return trio_substring(self->content, other); } #endif /* * trio_string_upper */ #if defined(TRIO_FUNC_STRING_UPPER) TRIO_PUBLIC_STRING int trio_string_upper TRIO_ARGS1((self), trio_string_t* self) { assert(self); return trio_upper(self->content); } #endif /** @} End of DynamicStrings */
./CrossVul/dataset_final_sorted/CWE-125/c/good_4493_1
crossvul-cpp_data_bad_4027_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * RDP Security * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2014 Norbert Federa <norbert.federa@thincast.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "security.h" #include <freerdp/log.h> #include <winpr/crypto.h> #define TAG FREERDP_TAG("core") /* 0x36 repeated 40 times */ static const BYTE pad1[40] = { "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" "\x36\x36\x36\x36\x36\x36\x36\x36" }; /* 0x5C repeated 48 times */ static const BYTE pad2[48] = { "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C" }; static const BYTE fips_reverse_table[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff }; static const BYTE fips_oddparity_table[256] = { 0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07, 0x08, 0x08, 0x0b, 0x0b, 0x0d, 0x0d, 0x0e, 0x0e, 0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16, 0x19, 0x19, 0x1a, 0x1a, 0x1c, 0x1c, 0x1f, 0x1f, 0x20, 0x20, 0x23, 0x23, 0x25, 0x25, 0x26, 0x26, 0x29, 0x29, 0x2a, 0x2a, 0x2c, 0x2c, 0x2f, 0x2f, 0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37, 0x38, 0x38, 0x3b, 0x3b, 0x3d, 0x3d, 0x3e, 0x3e, 0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49, 0x49, 0x4a, 0x4a, 0x4c, 0x4c, 0x4f, 0x4f, 0x51, 0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58, 0x58, 0x5b, 0x5b, 0x5d, 0x5d, 0x5e, 0x5e, 0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67, 0x68, 0x68, 0x6b, 0x6b, 0x6d, 0x6d, 0x6e, 0x6e, 0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76, 0x79, 0x79, 0x7a, 0x7a, 0x7c, 0x7c, 0x7f, 0x7f, 0x80, 0x80, 0x83, 0x83, 0x85, 0x85, 0x86, 0x86, 0x89, 0x89, 0x8a, 0x8a, 0x8c, 0x8c, 0x8f, 0x8f, 0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97, 0x98, 0x98, 0x9b, 0x9b, 0x9d, 0x9d, 0x9e, 0x9e, 0xa1, 0xa1, 0xa2, 0xa2, 0xa4, 0xa4, 0xa7, 0xa7, 0xa8, 0xa8, 0xab, 0xab, 0xad, 0xad, 0xae, 0xae, 0xb0, 0xb0, 0xb3, 0xb3, 0xb5, 0xb5, 0xb6, 0xb6, 0xb9, 0xb9, 0xba, 0xba, 0xbc, 0xbc, 0xbf, 0xbf, 0xc1, 0xc1, 0xc2, 0xc2, 0xc4, 0xc4, 0xc7, 0xc7, 0xc8, 0xc8, 0xcb, 0xcb, 0xcd, 0xcd, 0xce, 0xce, 0xd0, 0xd0, 0xd3, 0xd3, 0xd5, 0xd5, 0xd6, 0xd6, 0xd9, 0xd9, 0xda, 0xda, 0xdc, 0xdc, 0xdf, 0xdf, 0xe0, 0xe0, 0xe3, 0xe3, 0xe5, 0xe5, 0xe6, 0xe6, 0xe9, 0xe9, 0xea, 0xea, 0xec, 0xec, 0xef, 0xef, 0xf1, 0xf1, 0xf2, 0xf2, 0xf4, 0xf4, 0xf7, 0xf7, 0xf8, 0xf8, 0xfb, 0xfb, 0xfd, 0xfd, 0xfe, 0xfe }; static BOOL security_salted_hash(const BYTE* salt, const BYTE* input, int length, const BYTE* salt1, const BYTE* salt2, BYTE* output) { WINPR_DIGEST_CTX* sha1 = NULL; WINPR_DIGEST_CTX* md5 = NULL; BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH]; BOOL result = FALSE; /* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1(Input + Salt + Salt1 + Salt2)) */ /* SHA1_Digest = SHA1(Input + Salt + Salt1 + Salt2) */ if (!(sha1 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1)) goto out; if (!winpr_Digest_Update(sha1, input, length)) /* Input */ goto out; if (!winpr_Digest_Update(sha1, salt, 48)) /* Salt (48 bytes) */ goto out; if (!winpr_Digest_Update(sha1, salt1, 32)) /* Salt1 (32 bytes) */ goto out; if (!winpr_Digest_Update(sha1, salt2, 32)) /* Salt2 (32 bytes) */ goto out; if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest))) goto out; /* SaltedHash(Salt, Input, Salt1, Salt2) = MD5(S + SHA1_Digest) */ if (!(md5 = winpr_Digest_New())) goto out; /* Allow FIPS override for use of MD5 here, this is used for creating hashes of the * premaster_secret and master_secret */ /* used for RDP licensing as described in MS-RDPELE. This is for RDP licensing packets */ /* which will already be encrypted under FIPS, so the use of MD5 here is not for sensitive data * protection. */ if (!winpr_Digest_Init_Allow_FIPS(md5, WINPR_MD_MD5)) goto out; if (!winpr_Digest_Update(md5, salt, 48)) /* Salt (48 bytes) */ goto out; if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */ goto out; if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH)) goto out; result = TRUE; out: winpr_Digest_Free(sha1); winpr_Digest_Free(md5); return result; } static BOOL security_premaster_hash(const char* input, int length, const BYTE* premaster_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* PremasterHash(Input) = SaltedHash(PremasterSecret, Input, ClientRandom, ServerRandom) */ return security_salted_hash(premaster_secret, (BYTE*)input, length, client_random, server_random, output); } BOOL security_master_secret(const BYTE* premaster_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MasterSecret = PremasterHash('A') + PremasterHash('BB') + PremasterHash('CCC') */ return security_premaster_hash("A", 1, premaster_secret, client_random, server_random, &output[0]) && security_premaster_hash("BB", 2, premaster_secret, client_random, server_random, &output[16]) && security_premaster_hash("CCC", 3, premaster_secret, client_random, server_random, &output[32]); } static BOOL security_master_hash(const char* input, int length, const BYTE* master_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MasterHash(Input) = SaltedHash(MasterSecret, Input, ServerRandom, ClientRandom) */ return security_salted_hash(master_secret, (const BYTE*)input, length, server_random, client_random, output); } BOOL security_session_key_blob(const BYTE* master_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MasterHash = MasterHash('A') + MasterHash('BB') + MasterHash('CCC') */ return security_master_hash("A", 1, master_secret, client_random, server_random, &output[0]) && security_master_hash("BB", 2, master_secret, client_random, server_random, &output[16]) && security_master_hash("CCC", 3, master_secret, client_random, server_random, &output[32]); } void security_mac_salt_key(const BYTE* session_key_blob, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* MacSaltKey = First128Bits(SessionKeyBlob) */ memcpy(output, session_key_blob, 16); } static BOOL security_md5_16_32_32(const BYTE* in0, const BYTE* in1, const BYTE* in2, BYTE* output) { WINPR_DIGEST_CTX* md5 = NULL; BOOL result = FALSE; if (!(md5 = winpr_Digest_New())) return FALSE; if (!winpr_Digest_Init(md5, WINPR_MD_MD5)) goto out; if (!winpr_Digest_Update(md5, in0, 16)) goto out; if (!winpr_Digest_Update(md5, in1, 32)) goto out; if (!winpr_Digest_Update(md5, in2, 32)) goto out; if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH)) goto out; result = TRUE; out: winpr_Digest_Free(md5); return result; } static BOOL security_md5_16_32_32_Allow_FIPS(const BYTE* in0, const BYTE* in1, const BYTE* in2, BYTE* output) { WINPR_DIGEST_CTX* md5 = NULL; BOOL result = FALSE; if (!(md5 = winpr_Digest_New())) return FALSE; if (!winpr_Digest_Init_Allow_FIPS(md5, WINPR_MD_MD5)) goto out; if (!winpr_Digest_Update(md5, in0, 16)) goto out; if (!winpr_Digest_Update(md5, in1, 32)) goto out; if (!winpr_Digest_Update(md5, in2, 32)) goto out; if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH)) goto out; result = TRUE; out: winpr_Digest_Free(md5); return result; } BOOL security_licensing_encryption_key(const BYTE* session_key_blob, const BYTE* client_random, const BYTE* server_random, BYTE* output) { /* LicensingEncryptionKey = MD5(Second128Bits(SessionKeyBlob) + ClientRandom + ServerRandom)) * Allow FIPS use of MD5 here, this is just used for creating the licensing encryption key as * described in MS-RDPELE. This is for RDP licensing packets which will already be encrypted * under FIPS, so the use of MD5 here is not for sensitive data protection. */ return security_md5_16_32_32_Allow_FIPS(&session_key_blob[16], client_random, server_random, output); } static void security_UINT32_le(BYTE* output, UINT32 value) { output[0] = (value)&0xFF; output[1] = (value >> 8) & 0xFF; output[2] = (value >> 16) & 0xFF; output[3] = (value >> 24) & 0xFF; } BOOL security_mac_data(const BYTE* mac_salt_key, const BYTE* data, UINT32 length, BYTE* output) { WINPR_DIGEST_CTX* sha1 = NULL; WINPR_DIGEST_CTX* md5 = NULL; BYTE length_le[4]; BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH]; BOOL result = FALSE; /* MacData = MD5(MacSaltKey + pad2 + SHA1(MacSaltKey + pad1 + length + data)) */ security_UINT32_le(length_le, length); /* length must be little-endian */ /* SHA1_Digest = SHA1(MacSaltKey + pad1 + length + data) */ if (!(sha1 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1)) goto out; if (!winpr_Digest_Update(sha1, mac_salt_key, 16)) /* MacSaltKey */ goto out; if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1))) /* pad1 */ goto out; if (!winpr_Digest_Update(sha1, length_le, sizeof(length_le))) /* length */ goto out; if (!winpr_Digest_Update(sha1, data, length)) /* data */ goto out; if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest))) goto out; /* MacData = MD5(MacSaltKey + pad2 + SHA1_Digest) */ if (!(md5 = winpr_Digest_New())) goto out; /* Allow FIPS override for use of MD5 here, this is only used for creating the MACData field of * the */ /* Client Platform Challenge Response packet (from MS-RDPELE section 2.2.2.5). This is for RDP * licensing packets */ /* which will already be encrypted under FIPS, so the use of MD5 here is not for sensitive data * protection. */ if (!winpr_Digest_Init_Allow_FIPS(md5, WINPR_MD_MD5)) goto out; if (!winpr_Digest_Update(md5, mac_salt_key, 16)) /* MacSaltKey */ goto out; if (!winpr_Digest_Update(md5, pad2, sizeof(pad2))) /* pad2 */ goto out; if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */ goto out; if (!winpr_Digest_Final(md5, output, WINPR_MD5_DIGEST_LENGTH)) goto out; result = TRUE; out: winpr_Digest_Free(sha1); winpr_Digest_Free(md5); return result; } BOOL security_mac_signature(rdpRdp* rdp, const BYTE* data, UINT32 length, BYTE* output) { WINPR_DIGEST_CTX* sha1 = NULL; WINPR_DIGEST_CTX* md5 = NULL; BYTE length_le[4]; BYTE md5_digest[WINPR_MD5_DIGEST_LENGTH]; BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH]; BOOL result = FALSE; security_UINT32_le(length_le, length); /* length must be little-endian */ /* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */ if (!(sha1 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1)) goto out; if (!winpr_Digest_Update(sha1, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */ goto out; if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1))) /* pad1 */ goto out; if (!winpr_Digest_Update(sha1, length_le, sizeof(length_le))) /* length */ goto out; if (!winpr_Digest_Update(sha1, data, length)) /* data */ goto out; if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest))) goto out; /* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */ if (!(md5 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(md5, WINPR_MD_MD5)) goto out; if (!winpr_Digest_Update(md5, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */ goto out; if (!winpr_Digest_Update(md5, pad2, sizeof(pad2))) /* pad2 */ goto out; if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */ goto out; if (!winpr_Digest_Final(md5, md5_digest, sizeof(md5_digest))) goto out; memcpy(output, md5_digest, 8); result = TRUE; out: winpr_Digest_Free(sha1); winpr_Digest_Free(md5); return result; } BOOL security_salted_mac_signature(rdpRdp* rdp, const BYTE* data, UINT32 length, BOOL encryption, BYTE* output) { WINPR_DIGEST_CTX* sha1 = NULL; WINPR_DIGEST_CTX* md5 = NULL; BYTE length_le[4]; BYTE use_count_le[4]; BYTE md5_digest[WINPR_MD5_DIGEST_LENGTH]; BYTE sha1_digest[WINPR_SHA1_DIGEST_LENGTH]; BOOL result = FALSE; security_UINT32_le(length_le, length); /* length must be little-endian */ if (encryption) { security_UINT32_le(use_count_le, rdp->encrypt_checksum_use_count); } else { /* * We calculate checksum on plain text, so we must have already * decrypt it, which means decrypt_checksum_use_count is off by one. */ security_UINT32_le(use_count_le, rdp->decrypt_checksum_use_count - 1); } /* SHA1_Digest = SHA1(MACKeyN + pad1 + length + data) */ if (!(sha1 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1)) goto out; if (!winpr_Digest_Update(sha1, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */ goto out; if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1))) /* pad1 */ goto out; if (!winpr_Digest_Update(sha1, length_le, sizeof(length_le))) /* length */ goto out; if (!winpr_Digest_Update(sha1, data, length)) /* data */ goto out; if (!winpr_Digest_Update(sha1, use_count_le, sizeof(use_count_le))) /* encryptionCount */ goto out; if (!winpr_Digest_Final(sha1, sha1_digest, sizeof(sha1_digest))) goto out; /* MACSignature = First64Bits(MD5(MACKeyN + pad2 + SHA1_Digest)) */ if (!(md5 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(md5, WINPR_MD_MD5)) goto out; if (!winpr_Digest_Update(md5, rdp->sign_key, rdp->rc4_key_len)) /* MacKeyN */ goto out; if (!winpr_Digest_Update(md5, pad2, sizeof(pad2))) /* pad2 */ goto out; if (!winpr_Digest_Update(md5, sha1_digest, sizeof(sha1_digest))) /* SHA1_Digest */ goto out; if (!winpr_Digest_Final(md5, md5_digest, sizeof(md5_digest))) goto out; memcpy(output, md5_digest, 8); result = TRUE; out: winpr_Digest_Free(sha1); winpr_Digest_Free(md5); return result; } static BOOL security_A(BYTE* master_secret, const BYTE* client_random, BYTE* server_random, BYTE* output) { return security_premaster_hash("A", 1, master_secret, client_random, server_random, &output[0]) && security_premaster_hash("BB", 2, master_secret, client_random, server_random, &output[16]) && security_premaster_hash("CCC", 3, master_secret, client_random, server_random, &output[32]); } static BOOL security_X(BYTE* master_secret, const BYTE* client_random, BYTE* server_random, BYTE* output) { return security_premaster_hash("X", 1, master_secret, client_random, server_random, &output[0]) && security_premaster_hash("YY", 2, master_secret, client_random, server_random, &output[16]) && security_premaster_hash("ZZZ", 3, master_secret, client_random, server_random, &output[32]); } static void fips_expand_key_bits(BYTE* in, BYTE* out) { BYTE buf[21], c; int i, b, p, r; /* reverse every byte in the key */ for (i = 0; i < 21; i++) buf[i] = fips_reverse_table[in[i]]; /* insert a zero-bit after every 7th bit */ for (i = 0, b = 0; i < 24; i++, b += 7) { p = b / 8; r = b % 8; if (r <= 1) { out[i] = (buf[p] << r) & 0xfe; } else { /* c is accumulator */ c = buf[p] << r; c |= buf[p + 1] >> (8 - r); out[i] = c & 0xfe; } } /* reverse every byte */ /* alter lsb so the byte has odd parity */ for (i = 0; i < 24; i++) out[i] = fips_oddparity_table[fips_reverse_table[out[i]]]; } BOOL security_establish_keys(const BYTE* client_random, rdpRdp* rdp) { BYTE pre_master_secret[48]; BYTE master_secret[48]; BYTE session_key_blob[48]; BYTE* server_random; BYTE salt[] = { 0xD1, 0x26, 0x9E }; /* 40 bits: 3 bytes, 56 bits: 1 byte */ rdpSettings* settings; BOOL status; settings = rdp->settings; server_random = settings->ServerRandom; if (settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { WINPR_DIGEST_CTX* sha1; BYTE client_encrypt_key_t[WINPR_SHA1_DIGEST_LENGTH + 1]; BYTE client_decrypt_key_t[WINPR_SHA1_DIGEST_LENGTH + 1]; if (!(sha1 = winpr_Digest_New())) return FALSE; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1) || !winpr_Digest_Update(sha1, client_random + 16, 16) || !winpr_Digest_Update(sha1, server_random + 16, 16) || !winpr_Digest_Final(sha1, client_encrypt_key_t, sizeof(client_encrypt_key_t))) { winpr_Digest_Free(sha1); return FALSE; } client_encrypt_key_t[20] = client_encrypt_key_t[0]; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1) || !winpr_Digest_Update(sha1, client_random, 16) || !winpr_Digest_Update(sha1, server_random, 16) || !winpr_Digest_Final(sha1, client_decrypt_key_t, sizeof(client_decrypt_key_t))) { winpr_Digest_Free(sha1); return FALSE; } client_decrypt_key_t[20] = client_decrypt_key_t[0]; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1) || !winpr_Digest_Update(sha1, client_decrypt_key_t, WINPR_SHA1_DIGEST_LENGTH) || !winpr_Digest_Update(sha1, client_encrypt_key_t, WINPR_SHA1_DIGEST_LENGTH) || !winpr_Digest_Final(sha1, rdp->fips_sign_key, WINPR_SHA1_DIGEST_LENGTH)) { winpr_Digest_Free(sha1); return FALSE; } winpr_Digest_Free(sha1); if (rdp->settings->ServerMode) { fips_expand_key_bits(client_encrypt_key_t, rdp->fips_decrypt_key); fips_expand_key_bits(client_decrypt_key_t, rdp->fips_encrypt_key); } else { fips_expand_key_bits(client_encrypt_key_t, rdp->fips_encrypt_key); fips_expand_key_bits(client_decrypt_key_t, rdp->fips_decrypt_key); } } memcpy(pre_master_secret, client_random, 24); memcpy(pre_master_secret + 24, server_random, 24); if (!security_A(pre_master_secret, client_random, server_random, master_secret) || !security_X(master_secret, client_random, server_random, session_key_blob)) { return FALSE; } memcpy(rdp->sign_key, session_key_blob, 16); if (rdp->settings->ServerMode) { status = security_md5_16_32_32(&session_key_blob[16], client_random, server_random, rdp->encrypt_key); status &= security_md5_16_32_32(&session_key_blob[32], client_random, server_random, rdp->decrypt_key); } else { /* Allow FIPS use of MD5 here, this is just used for generation of the SessionKeyBlob as * described in MS-RDPELE. */ /* This is for RDP licensing packets which will already be encrypted under FIPS, so the use * of MD5 here is not */ /* for sensitive data protection. */ status = security_md5_16_32_32_Allow_FIPS(&session_key_blob[16], client_random, server_random, rdp->decrypt_key); status &= security_md5_16_32_32_Allow_FIPS(&session_key_blob[32], client_random, server_random, rdp->encrypt_key); } if (!status) return FALSE; if (settings->EncryptionMethods == ENCRYPTION_METHOD_40BIT) { memcpy(rdp->sign_key, salt, 3); memcpy(rdp->decrypt_key, salt, 3); memcpy(rdp->encrypt_key, salt, 3); rdp->rc4_key_len = 8; } else if (settings->EncryptionMethods == ENCRYPTION_METHOD_56BIT) { memcpy(rdp->sign_key, salt, 1); memcpy(rdp->decrypt_key, salt, 1); memcpy(rdp->encrypt_key, salt, 1); rdp->rc4_key_len = 8; } else if (settings->EncryptionMethods == ENCRYPTION_METHOD_128BIT) { rdp->rc4_key_len = 16; } memcpy(rdp->decrypt_update_key, rdp->decrypt_key, 16); memcpy(rdp->encrypt_update_key, rdp->encrypt_key, 16); rdp->decrypt_use_count = 0; rdp->decrypt_checksum_use_count = 0; rdp->encrypt_use_count = 0; rdp->encrypt_checksum_use_count = 0; return TRUE; } static BOOL security_key_update(BYTE* key, BYTE* update_key, int key_len, rdpRdp* rdp) { BYTE sha1h[WINPR_SHA1_DIGEST_LENGTH]; WINPR_DIGEST_CTX* sha1 = NULL; WINPR_DIGEST_CTX* md5 = NULL; WINPR_RC4_CTX* rc4 = NULL; BYTE salt[] = { 0xD1, 0x26, 0x9E }; /* 40 bits: 3 bytes, 56 bits: 1 byte */ BOOL result = FALSE; WLog_DBG(TAG, "updating RDP key"); if (!(sha1 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(sha1, WINPR_MD_SHA1)) goto out; if (!winpr_Digest_Update(sha1, update_key, key_len)) goto out; if (!winpr_Digest_Update(sha1, pad1, sizeof(pad1))) goto out; if (!winpr_Digest_Update(sha1, key, key_len)) goto out; if (!winpr_Digest_Final(sha1, sha1h, sizeof(sha1h))) goto out; if (!(md5 = winpr_Digest_New())) goto out; if (!winpr_Digest_Init(md5, WINPR_MD_MD5)) goto out; if (!winpr_Digest_Update(md5, update_key, key_len)) goto out; if (!winpr_Digest_Update(md5, pad2, sizeof(pad2))) goto out; if (!winpr_Digest_Update(md5, sha1h, sizeof(sha1h))) goto out; if (!winpr_Digest_Final(md5, key, WINPR_MD5_DIGEST_LENGTH)) goto out; if (!(rc4 = winpr_RC4_New(key, key_len))) goto out; if (!winpr_RC4_Update(rc4, key_len, key, key)) goto out; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_40BIT) memcpy(key, salt, 3); else if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_56BIT) memcpy(key, salt, 1); result = TRUE; out: winpr_Digest_Free(sha1); winpr_Digest_Free(md5); winpr_RC4_Free(rc4); return result; } BOOL security_encrypt(BYTE* data, size_t length, rdpRdp* rdp) { BOOL rc = FALSE; EnterCriticalSection(&rdp->critical); if (rdp->encrypt_use_count >= 4096) { if (!security_key_update(rdp->encrypt_key, rdp->encrypt_update_key, rdp->rc4_key_len, rdp)) goto fail; winpr_RC4_Free(rdp->rc4_encrypt_key); rdp->rc4_encrypt_key = winpr_RC4_New(rdp->encrypt_key, rdp->rc4_key_len); if (!rdp->rc4_encrypt_key) goto fail; rdp->encrypt_use_count = 0; } if (!winpr_RC4_Update(rdp->rc4_encrypt_key, length, data, data)) goto fail; rdp->encrypt_use_count++; rdp->encrypt_checksum_use_count++; rc = TRUE; fail: LeaveCriticalSection(&rdp->critical); return rc; } BOOL security_decrypt(BYTE* data, size_t length, rdpRdp* rdp) { if (rdp->rc4_decrypt_key == NULL) return FALSE; if (rdp->decrypt_use_count >= 4096) { if (!security_key_update(rdp->decrypt_key, rdp->decrypt_update_key, rdp->rc4_key_len, rdp)) return FALSE; winpr_RC4_Free(rdp->rc4_decrypt_key); rdp->rc4_decrypt_key = winpr_RC4_New(rdp->decrypt_key, rdp->rc4_key_len); if (!rdp->rc4_decrypt_key) return FALSE; rdp->decrypt_use_count = 0; } if (!winpr_RC4_Update(rdp->rc4_decrypt_key, length, data, data)) return FALSE; rdp->decrypt_use_count += 1; rdp->decrypt_checksum_use_count++; return TRUE; } BOOL security_hmac_signature(const BYTE* data, size_t length, BYTE* output, rdpRdp* rdp) { BYTE buf[WINPR_SHA1_DIGEST_LENGTH]; BYTE use_count_le[4]; WINPR_HMAC_CTX* hmac; BOOL result = FALSE; security_UINT32_le(use_count_le, rdp->encrypt_use_count); if (!(hmac = winpr_HMAC_New())) return FALSE; if (!winpr_HMAC_Init(hmac, WINPR_MD_SHA1, rdp->fips_sign_key, WINPR_SHA1_DIGEST_LENGTH)) goto out; if (!winpr_HMAC_Update(hmac, data, length)) goto out; if (!winpr_HMAC_Update(hmac, use_count_le, 4)) goto out; if (!winpr_HMAC_Final(hmac, buf, WINPR_SHA1_DIGEST_LENGTH)) goto out; memmove(output, buf, 8); result = TRUE; out: winpr_HMAC_Free(hmac); return result; } BOOL security_fips_encrypt(BYTE* data, size_t length, rdpRdp* rdp) { BOOL rc = FALSE; size_t olen; EnterCriticalSection(&rdp->critical); if (!winpr_Cipher_Update(rdp->fips_encrypt, data, length, data, &olen)) goto fail; rdp->encrypt_use_count++; rc = TRUE; fail: LeaveCriticalSection(&rdp->critical); return rc; } BOOL security_fips_decrypt(BYTE* data, size_t length, rdpRdp* rdp) { size_t olen; if (!winpr_Cipher_Update(rdp->fips_decrypt, data, length, data, &olen)) return FALSE; return TRUE; } BOOL security_fips_check_signature(const BYTE* data, size_t length, const BYTE* sig, rdpRdp* rdp) { BYTE buf[WINPR_SHA1_DIGEST_LENGTH]; BYTE use_count_le[4]; WINPR_HMAC_CTX* hmac; BOOL result = FALSE; security_UINT32_le(use_count_le, rdp->decrypt_use_count); if (!(hmac = winpr_HMAC_New())) return FALSE; if (!winpr_HMAC_Init(hmac, WINPR_MD_SHA1, rdp->fips_sign_key, WINPR_SHA1_DIGEST_LENGTH)) goto out; if (!winpr_HMAC_Update(hmac, data, length)) goto out; if (!winpr_HMAC_Update(hmac, use_count_le, 4)) goto out; if (!winpr_HMAC_Final(hmac, buf, WINPR_SHA1_DIGEST_LENGTH)) goto out; rdp->decrypt_use_count++; if (!memcmp(sig, buf, 8)) result = TRUE; out: winpr_HMAC_Free(hmac); return result; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_4027_0
crossvul-cpp_data_good_950_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/fourier.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { ChannelType channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register PixelPacket *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y, MagickMax(Ar_image->columns,Cr_image->columns),1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y, MagickMax(Ai_image->columns,Ci_image->columns),1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y, MagickMax(Br_image->columns,Cr_image->columns),1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y, MagickMax(Bi_image->columns,Ci_image->columns),1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const PixelPacket *) NULL) || (Ai == (const PixelPacket *) NULL) || (Br == (const PixelPacket *) NULL) || (Bi == (const PixelPacket *) NULL) || (Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { switch (op) { case AddComplexOperator: { Cr->red=Ar->red+Br->red; Ci->red=Ai->red+Bi->red; Cr->green=Ar->green+Br->green; Ci->green=Ai->green+Bi->green; Cr->blue=Ar->blue+Br->blue; Ci->blue=Ai->blue+Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity+Br->opacity; Ci->opacity=Ai->opacity+Bi->opacity; } break; } case ConjugateComplexOperator: default: { Cr->red=Ar->red; Ci->red=(-Bi->red); Cr->green=Ar->green; Ci->green=(-Bi->green); Cr->blue=Ar->blue; Ci->blue=(-Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity; Ci->opacity=(-Bi->opacity); } break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr); Cr->red=gamma*(Ar->red*Br->red+Ai->red*Bi->red); Ci->red=gamma*(Ai->red*Br->red-Ar->red*Bi->red); gamma=PerceptibleReciprocal(Br->green*Br->green+Bi->green*Bi->green+ snr); Cr->green=gamma*(Ar->green*Br->green+Ai->green*Bi->green); Ci->green=gamma*(Ai->green*Br->green-Ar->green*Bi->green); gamma=PerceptibleReciprocal(Br->blue*Br->blue+Bi->blue*Bi->blue+snr); Cr->blue=gamma*(Ar->blue*Br->blue+Ai->blue*Bi->blue); Ci->blue=gamma*(Ai->blue*Br->blue-Ar->blue*Bi->blue); if (images->matte != MagickFalse) { gamma=PerceptibleReciprocal(Br->opacity*Br->opacity+Bi->opacity* Bi->opacity+snr); Cr->opacity=gamma*(Ar->opacity*Br->opacity+Ai->opacity* Bi->opacity); Ci->opacity=gamma*(Ai->opacity*Br->opacity-Ar->opacity* Bi->opacity); } break; } case MagnitudePhaseComplexOperator: { Cr->red=sqrt(Ar->red*Ar->red+Ai->red*Ai->red); Ci->red=atan2(Ai->red,Ar->red)/(2.0*MagickPI)+0.5; Cr->green=sqrt(Ar->green*Ar->green+Ai->green*Ai->green); Ci->green=atan2(Ai->green,Ar->green)/(2.0*MagickPI)+0.5; Cr->blue=sqrt(Ar->blue*Ar->blue+Ai->blue*Ai->blue); Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5; if (images->matte != MagickFalse) { Cr->opacity=sqrt(Ar->opacity*Ar->opacity+Ai->opacity*Ai->opacity); Ci->opacity=atan2(Ai->opacity,Ar->opacity)/(2.0*MagickPI)+0.5; } break; } case MultiplyComplexOperator: { Cr->red=QuantumScale*(Ar->red*Br->red-Ai->red*Bi->red); Ci->red=QuantumScale*(Ai->red*Br->red+Ar->red*Bi->red); Cr->green=QuantumScale*(Ar->green*Br->green-Ai->green*Bi->green); Ci->green=QuantumScale*(Ai->green*Br->green+Ar->green*Bi->green); Cr->blue=QuantumScale*(Ar->blue*Br->blue-Ai->blue*Bi->blue); Ci->blue=QuantumScale*(Ai->blue*Br->blue+Ar->blue*Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=QuantumScale*(Ar->opacity*Br->opacity-Ai->opacity* Bi->opacity); Ci->opacity=QuantumScale*(Ai->opacity*Br->opacity+Ar->opacity* Bi->opacity); } break; } case RealImaginaryComplexOperator: { Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5)); Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5)); Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5)); Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5)); Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5)); Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5)); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5)); Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5)); } break; } case SubtractComplexOperator: { Cr->red=Ar->red-Br->red; Ci->red=Ai->red-Bi->red; Cr->green=Ar->green-Br->green; Ci->green=Ai->green-Bi->green; Cr->blue=Ar->blue-Br->blue; Ci->blue=Ai->blue-Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity-Br->opacity; Ci->opacity=Ai->opacity-Bi->opacity; } break; } } Ar++; Ai++; Br++; Bi++; Cr++; Ci++; } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* magnitude_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { source_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { source_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { source_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize Fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsGrayImage(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayChannels,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image,RedChannel, modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->matte != MagickFalse) thread_status=ForwardFourierTransformChannel(image, OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Inverse Fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { magnitude_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { magnitude_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { magnitude_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { phase_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { phase_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { phase_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; double *source_pixels; const char *value; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* source_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } } i++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsGrayImage(magnitude_image,exception); if (is_gray != MagickFalse) is_gray=IsGrayImage(phase_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayChannels,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->matte != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_950_1
crossvul-cpp_data_bad_2643_0
/* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* The functions from print-esp.c used in this file are only defined when both * OpenSSL and evp.h are detected. Employ the same preprocessor device here. */ #ifndef HAVE_OPENSSL_EVP_H #undef HAVE_LIBCRYPTO #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ip6.h" #include "ipproto.h" /* refer to RFC 2408 */ typedef u_char cookie_t[8]; typedef u_char msgid_t[4]; #define PORT_ISAKMP 500 /* 3.1 ISAKMP Header Format (IKEv1 and IKEv2) 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Initiator ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Responder ! ! Cookie ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Message ID ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp { cookie_t i_ck; /* Initiator Cookie */ cookie_t r_ck; /* Responder Cookie */ uint8_t np; /* Next Payload Type */ uint8_t vers; #define ISAKMP_VERS_MAJOR 0xf0 #define ISAKMP_VERS_MAJOR_SHIFT 4 #define ISAKMP_VERS_MINOR 0x0f #define ISAKMP_VERS_MINOR_SHIFT 0 uint8_t etype; /* Exchange Type */ uint8_t flags; /* Flags */ msgid_t msgid; uint32_t len; /* Length */ }; /* Next Payload Type */ #define ISAKMP_NPTYPE_NONE 0 /* NONE*/ #define ISAKMP_NPTYPE_SA 1 /* Security Association */ #define ISAKMP_NPTYPE_P 2 /* Proposal */ #define ISAKMP_NPTYPE_T 3 /* Transform */ #define ISAKMP_NPTYPE_KE 4 /* Key Exchange */ #define ISAKMP_NPTYPE_ID 5 /* Identification */ #define ISAKMP_NPTYPE_CERT 6 /* Certificate */ #define ISAKMP_NPTYPE_CR 7 /* Certificate Request */ #define ISAKMP_NPTYPE_HASH 8 /* Hash */ #define ISAKMP_NPTYPE_SIG 9 /* Signature */ #define ISAKMP_NPTYPE_NONCE 10 /* Nonce */ #define ISAKMP_NPTYPE_N 11 /* Notification */ #define ISAKMP_NPTYPE_D 12 /* Delete */ #define ISAKMP_NPTYPE_VID 13 /* Vendor ID */ #define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */ #define IKEv1_MAJOR_VERSION 1 #define IKEv1_MINOR_VERSION 0 #define IKEv2_MAJOR_VERSION 2 #define IKEv2_MINOR_VERSION 0 /* Flags */ #define ISAKMP_FLAG_E 0x01 /* Encryption Bit */ #define ISAKMP_FLAG_C 0x02 /* Commit Bit */ #define ISAKMP_FLAG_extra 0x04 /* IKEv2 */ #define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */ #define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */ #define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */ /* 3.2 Payload Generic Header 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ! Next Payload ! RESERVED ! Payload Length ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_gen { uint8_t np; /* Next Payload */ uint8_t critical; /* bit 7 - critical, rest is RESERVED */ uint16_t len; /* Payload Length */ }; /* 3.3 Data Attributes 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ !A! Attribute Type ! AF=0 Attribute Length ! !F! ! AF=1 Attribute Value ! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . AF=0 Attribute Value . . AF=1 Not Transmitted . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ struct isakmp_data { uint16_t type; /* defined by DOI-spec, and Attribute Format */ uint16_t lorv; /* if f equal 1, Attribute Length */ /* if f equal 0, Attribute Value */ /* if f equal 1, Attribute Value */ }; /* 3.4 Security Association Payload */ /* MAY NOT be used, because of being defined in ipsec-doi. */ /* If the current payload is the last in the message, then the value of the next payload field will be 0. This field MUST NOT contain the values for the Proposal or Transform payloads as they are considered part of the security association negotiation. For example, this field would contain the value "10" (Nonce payload) in the first message of a Base Exchange (see Section 4.4) and the value "0" in the first message of an Identity Protect Exchange (see Section 4.5). */ struct ikev1_pl_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; /* 3.5 Proposal Payload */ /* The value of the next payload field MUST only contain the value "2" or "0". If there are additional Proposal payloads in the message, then this field will be 2. If the current Proposal payload is the last within the security association proposal, then this field will be 0. */ struct ikev1_pl_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ /* SPI */ }; /* 3.6 Transform Payload */ /* The value of the next payload field MUST only contain the value "3" or "0". If there are additional Transform payloads in the proposal, then this field will be 3. If the current Transform payload is the last within the proposal, then this field will be 0. */ struct ikev1_pl_t { struct isakmp_gen h; uint8_t t_no; /* Transform # */ uint8_t t_id; /* Transform-Id */ uint16_t reserved; /* RESERVED2 */ /* SA Attributes */ }; /* 3.7 Key Exchange Payload */ struct ikev1_pl_ke { struct isakmp_gen h; /* Key Exchange Data */ }; /* 3.8 Identification Payload */ /* MUST NOT to be used, because of being defined in ipsec-doi. */ struct ikev1_pl_id { struct isakmp_gen h; union { uint8_t id_type; /* ID Type */ uint32_t doi_data; /* DOI Specific ID Data */ } d; /* Identification Data */ }; /* 3.9 Certificate Payload */ struct ikev1_pl_cert { struct isakmp_gen h; uint8_t encode; /* Cert Encoding */ char cert; /* Certificate Data */ /* This field indicates the type of certificate or certificate-related information contained in the Certificate Data field. */ }; /* 3.10 Certificate Request Payload */ struct ikev1_pl_cr { struct isakmp_gen h; uint8_t num_cert; /* # Cert. Types */ /* Certificate Types (variable length) -- Contains a list of the types of certificates requested, sorted in order of preference. Each individual certificate type is 1 octet. This field is NOT requiredo */ /* # Certificate Authorities (1 octet) */ /* Certificate Authorities (variable length) */ }; /* 3.11 Hash Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_hash { struct isakmp_gen h; /* Hash Data */ }; /* 3.12 Signature Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_sig { struct isakmp_gen h; /* Signature Data */ }; /* 3.13 Nonce Payload */ /* may not be used, because of having only data. */ struct ikev1_pl_nonce { struct isakmp_gen h; /* Nonce Data */ }; /* 3.14 Notification Payload */ struct ikev1_pl_n { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ /* SPI */ /* Notification Data */ }; /* 3.14.1 Notify Message Types */ /* NOTIFY MESSAGES - ERROR TYPES */ #define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1 #define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2 #define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3 #define ISAKMP_NTYPE_INVALID_COOKIE 4 #define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5 #define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6 #define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7 #define ISAKMP_NTYPE_INVALID_FLAGS 8 #define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9 #define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10 #define ISAKMP_NTYPE_INVALID_SPI 11 #define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12 #define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13 #define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14 #define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15 #define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16 #define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17 #define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18 #define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19 #define ISAKMP_NTYPE_INVALID_CERTIFICATE 20 #define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21 #define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22 #define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23 #define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24 #define ISAKMP_NTYPE_INVALID_SIGNATURE 25 #define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26 /* 3.15 Delete Payload */ struct ikev1_pl_d { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint8_t prot_id; /* Protocol-Id */ uint8_t spi_size; /* SPI Size */ uint16_t num_spi; /* # of SPIs */ /* SPI(es) */ }; struct ikev1_ph1tab { struct ikev1_ph1 *head; struct ikev1_ph1 *tail; int len; }; struct isakmp_ph2tab { struct ikev1_ph2 *head; struct ikev1_ph2 *tail; int len; }; /* IKEv2 (RFC4306) */ /* 3.3 Security Association Payload -- generic header */ /* 3.3.1. Proposal Substructure */ struct ikev2_p { struct isakmp_gen h; uint8_t p_no; /* Proposal # */ uint8_t prot_id; /* Protocol */ uint8_t spi_size; /* SPI Size */ uint8_t num_t; /* Number of Transforms */ }; /* 3.3.2. Transform Substructure */ struct ikev2_t { struct isakmp_gen h; uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/ uint8_t res2; /* reserved byte */ uint16_t t_id; /* Transform ID */ }; enum ikev2_t_type { IV2_T_ENCR = 1, IV2_T_PRF = 2, IV2_T_INTEG= 3, IV2_T_DH = 4, IV2_T_ESN = 5 }; /* 3.4. Key Exchange Payload */ struct ikev2_ke { struct isakmp_gen h; uint16_t ke_group; uint16_t ke_res1; /* KE data */ }; /* 3.5. Identification Payloads */ enum ikev2_id_type { ID_IPV4_ADDR=1, ID_FQDN=2, ID_RFC822_ADDR=3, ID_IPV6_ADDR=5, ID_DER_ASN1_DN=9, ID_DER_ASN1_GN=10, ID_KEY_ID=11 }; struct ikev2_id { struct isakmp_gen h; uint8_t type; /* ID type */ uint8_t res1; uint16_t res2; /* SPI */ /* Notification Data */ }; /* 3.10 Notification Payload */ struct ikev2_n { struct isakmp_gen h; uint8_t prot_id; /* Protocol-ID */ uint8_t spi_size; /* SPI Size */ uint16_t type; /* Notify Message Type */ }; enum ikev2_n_type { IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1, IV2_NOTIFY_INVALID_IKE_SPI = 4, IV2_NOTIFY_INVALID_MAJOR_VERSION = 5, IV2_NOTIFY_INVALID_SYNTAX = 7, IV2_NOTIFY_INVALID_MESSAGE_ID = 9, IV2_NOTIFY_INVALID_SPI =11, IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14, IV2_NOTIFY_INVALID_KE_PAYLOAD =17, IV2_NOTIFY_AUTHENTICATION_FAILED =24, IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34, IV2_NOTIFY_NO_ADDITIONAL_SAS =35, IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36, IV2_NOTIFY_FAILED_CP_REQUIRED =37, IV2_NOTIFY_INVALID_SELECTORS =39, IV2_NOTIFY_INITIAL_CONTACT =16384, IV2_NOTIFY_SET_WINDOW_SIZE =16385, IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386, IV2_NOTIFY_IPCOMP_SUPPORTED =16387, IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388, IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389, IV2_NOTIFY_COOKIE =16390, IV2_NOTIFY_USE_TRANSPORT_MODE =16391, IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392, IV2_NOTIFY_REKEY_SA =16393, IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394, IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395 }; struct notify_messages { uint16_t type; char *msg; }; /* 3.8 Notification Payload */ struct ikev2_auth { struct isakmp_gen h; uint8_t auth_method; /* Protocol-ID */ uint8_t reserved[3]; /* authentication data */ }; enum ikev2_auth_type { IV2_RSA_SIG = 1, IV2_SHARED = 2, IV2_DSS_SIG = 3 }; /* refer to RFC 2409 */ #if 0 /* isakmp sa structure */ struct oakley_sa { uint8_t proto_id; /* OAKLEY */ vchar_t *spi; /* spi */ uint8_t dhgrp; /* DH; group */ uint8_t auth_t; /* method of authentication */ uint8_t prf_t; /* type of prf */ uint8_t hash_t; /* type of hash */ uint8_t enc_t; /* type of cipher */ uint8_t life_t; /* type of duration of lifetime */ uint32_t ldur; /* life duration */ }; #endif /* refer to RFC 2407 */ #define IPSEC_DOI 1 /* 4.2 IPSEC Situation Definition */ #define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001 #define IPSECDOI_SIT_SECRECY 0x00000002 #define IPSECDOI_SIT_INTEGRITY 0x00000004 /* 4.4.1 IPSEC Security Protocol Identifiers */ /* 4.4.2 IPSEC ISAKMP Transform Values */ #define IPSECDOI_PROTO_ISAKMP 1 #define IPSECDOI_KEY_IKE 1 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_AH 2 /* 4.4.3 IPSEC AH Transform Values */ #define IPSECDOI_AH_MD5 2 #define IPSECDOI_AH_SHA 3 #define IPSECDOI_AH_DES 4 #define IPSECDOI_AH_SHA2_256 5 #define IPSECDOI_AH_SHA2_384 6 #define IPSECDOI_AH_SHA2_512 7 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPSEC_ESP 3 /* 4.4.4 IPSEC ESP Transform Identifiers */ #define IPSECDOI_ESP_DES_IV64 1 #define IPSECDOI_ESP_DES 2 #define IPSECDOI_ESP_3DES 3 #define IPSECDOI_ESP_RC5 4 #define IPSECDOI_ESP_IDEA 5 #define IPSECDOI_ESP_CAST 6 #define IPSECDOI_ESP_BLOWFISH 7 #define IPSECDOI_ESP_3IDEA 8 #define IPSECDOI_ESP_DES_IV32 9 #define IPSECDOI_ESP_RC4 10 #define IPSECDOI_ESP_NULL 11 #define IPSECDOI_ESP_RIJNDAEL 12 #define IPSECDOI_ESP_AES 12 /* 4.4.1 IPSEC Security Protocol Identifiers */ #define IPSECDOI_PROTO_IPCOMP 4 /* 4.4.5 IPSEC IPCOMP Transform Identifiers */ #define IPSECDOI_IPCOMP_OUI 1 #define IPSECDOI_IPCOMP_DEFLATE 2 #define IPSECDOI_IPCOMP_LZS 3 /* 4.5 IPSEC Security Association Attributes */ #define IPSECDOI_ATTR_SA_LTYPE 1 /* B */ #define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1 #define IPSECDOI_ATTR_SA_LTYPE_SEC 1 #define IPSECDOI_ATTR_SA_LTYPE_KB 2 #define IPSECDOI_ATTR_SA_LDUR 2 /* V */ #define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */ #define IPSECDOI_ATTR_GRP_DESC 3 /* B */ #define IPSECDOI_ATTR_ENC_MODE 4 /* B */ /* default value: host dependent */ #define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1 #define IPSECDOI_ATTR_ENC_MODE_TRNS 2 #define IPSECDOI_ATTR_AUTH 5 /* B */ /* 0 means not to use authentication. */ #define IPSECDOI_ATTR_AUTH_HMAC_MD5 1 #define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2 #define IPSECDOI_ATTR_AUTH_DES_MAC 3 #define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/ /* * When negotiating ESP without authentication, the Auth * Algorithm attribute MUST NOT be included in the proposal. * When negotiating ESP without confidentiality, the Auth * Algorithm attribute MUST be included in the proposal and * the ESP transform ID must be ESP_NULL. */ #define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */ #define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */ #define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */ #define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */ /* 4.6.1 Security Association Payload */ struct ipsecdoi_sa { struct isakmp_gen h; uint32_t doi; /* Domain of Interpretation */ uint32_t sit; /* Situation */ }; struct ipsecdoi_secrecy_h { uint16_t len; uint16_t reserved; }; /* 4.6.2.1 Identification Type Values */ struct ipsecdoi_id { struct isakmp_gen h; uint8_t type; /* ID Type */ uint8_t proto_id; /* Protocol ID */ uint16_t port; /* Port */ /* Identification Data */ }; #define IPSECDOI_ID_IPV4_ADDR 1 #define IPSECDOI_ID_FQDN 2 #define IPSECDOI_ID_USER_FQDN 3 #define IPSECDOI_ID_IPV4_ADDR_SUBNET 4 #define IPSECDOI_ID_IPV6_ADDR 5 #define IPSECDOI_ID_IPV6_ADDR_SUBNET 6 #define IPSECDOI_ID_IPV4_ADDR_RANGE 7 #define IPSECDOI_ID_IPV6_ADDR_RANGE 8 #define IPSECDOI_ID_DER_ASN1_DN 9 #define IPSECDOI_ID_DER_ASN1_GN 10 #define IPSECDOI_ID_KEY_ID 11 /* 4.6.3 IPSEC DOI Notify Message Types */ /* Notify Messages - Status Types */ #define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576 #define IPSECDOI_NTYPE_REPLAY_STATUS 24577 #define IPSECDOI_NTYPE_INITIAL_CONTACT 24578 #define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \ netdissect_options *ndo, u_char tpay, \ const struct isakmp_gen *ext, \ u_int item_len, \ const u_char *end_pointer, \ uint32_t phase,\ uint32_t doi0, \ uint32_t proto0, int depth) DECLARE_PRINTER(v1_sa); DECLARE_PRINTER(v1_p); DECLARE_PRINTER(v1_t); DECLARE_PRINTER(v1_ke); DECLARE_PRINTER(v1_id); DECLARE_PRINTER(v1_cert); DECLARE_PRINTER(v1_cr); DECLARE_PRINTER(v1_sig); DECLARE_PRINTER(v1_hash); DECLARE_PRINTER(v1_nonce); DECLARE_PRINTER(v1_n); DECLARE_PRINTER(v1_d); DECLARE_PRINTER(v1_vid); DECLARE_PRINTER(v2_sa); DECLARE_PRINTER(v2_ke); DECLARE_PRINTER(v2_ID); DECLARE_PRINTER(v2_cert); DECLARE_PRINTER(v2_cr); DECLARE_PRINTER(v2_auth); DECLARE_PRINTER(v2_nonce); DECLARE_PRINTER(v2_n); DECLARE_PRINTER(v2_d); DECLARE_PRINTER(v2_vid); DECLARE_PRINTER(v2_TS); DECLARE_PRINTER(v2_cp); DECLARE_PRINTER(v2_eap); static const u_char *ikev2_e_print(netdissect_options *ndo, struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth); static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *, const u_char *, uint32_t, uint32_t, uint32_t, int); static const u_char *ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth); static char *numstr(int); static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base); #define MAXINITIATORS 20 static int ninitiator = 0; union inaddr_u { struct in_addr in4; struct in6_addr in6; }; static struct { cookie_t initiator; u_int version; union inaddr_u iaddr; union inaddr_u raddr; } cookiecache[MAXINITIATORS]; /* protocol id */ static const char *protoidstr[] = { NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp", }; /* isakmp->np */ static const char *npstr[] = { "none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */ "sig", "nonce", "n", "d", "vid", /* 9 - 13 */ "pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */ "pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */ "pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */ "pay29", "pay30", "pay31", "pay32", /* 29- 32 */ "v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */ "v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */ "v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */ "v2eap", /* 48 */ }; /* isakmp->np */ static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len, const u_char *end_pointer, uint32_t phase, uint32_t doi0, uint32_t proto0, int depth) = { NULL, ikev1_sa_print, ikev1_p_print, ikev1_t_print, ikev1_ke_print, ikev1_id_print, ikev1_cert_print, ikev1_cr_print, ikev1_hash_print, ikev1_sig_print, ikev1_nonce_print, ikev1_n_print, ikev1_d_print, ikev1_vid_print, /* 13 */ NULL, NULL, NULL, NULL, NULL, /* 14- 18 */ NULL, NULL, NULL, NULL, NULL, /* 19- 23 */ NULL, NULL, NULL, NULL, NULL, /* 24- 28 */ NULL, NULL, NULL, NULL, /* 29- 32 */ ikev2_sa_print, /* 33 */ ikev2_ke_print, /* 34 */ ikev2_ID_print, /* 35 */ ikev2_ID_print, /* 36 */ ikev2_cert_print, /* 37 */ ikev2_cr_print, /* 38 */ ikev2_auth_print, /* 39 */ ikev2_nonce_print, /* 40 */ ikev2_n_print, /* 41 */ ikev2_d_print, /* 42 */ ikev2_vid_print, /* 43 */ ikev2_TS_print, /* 44 */ ikev2_TS_print, /* 45 */ NULL, /* ikev2_e_print,*/ /* 46 - special */ ikev2_cp_print, /* 47 */ ikev2_eap_print, /* 48 */ }; /* isakmp->etype */ static const char *etypestr[] = { /* IKEv1 exchange types */ "none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */ "oakley-quick", "oakley-newgroup", /* 32-33 */ /* IKEv2 exchange types */ "ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */ }; #define STR_OR_ID(x, tab) \ (((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x)) #define PROTOIDSTR(x) STR_OR_ID(x, protoidstr) #define NPSTR(x) STR_OR_ID(x, npstr) #define ETYPESTR(x) STR_OR_ID(x, etypestr) #define CHECKLEN(p, np) \ if (ep < (const u_char *)(p)) { \ ND_PRINT((ndo," [|%s]", NPSTR(np))); \ goto done; \ } #define NPFUNC(x) \ (((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \ ? npfunc[(x)] : NULL) static int iszero(const u_char *p, size_t l) { while (l--) { if (*p++) return 0; } return 1; } /* find cookie from initiator cache */ static int cookie_find(cookie_t *in) { int i; for (i = 0; i < MAXINITIATORS; i++) { if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0) return i; } return -1; } /* record initiator */ static void cookie_record(cookie_t *in, const u_char *bp2) { int i; const struct ip *ip; const struct ip6_hdr *ip6; i = cookie_find(in); if (0 <= i) { ninitiator = (i + 1) % MAXINITIATORS; return; } ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: cookiecache[ninitiator].version = 4; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr)); break; case 6: ip6 = (const struct ip6_hdr *)bp2; cookiecache[ninitiator].version = 6; UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr)); UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr)); break; default: return; } UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in)); ninitiator = (ninitiator + 1) % MAXINITIATORS; } #define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1) #define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0) static int cookie_sidecheck(int i, const u_char *bp2, int initiator) { const struct ip *ip; const struct ip6_hdr *ip6; ip = (const struct ip *)bp2; switch (IP_V(ip)) { case 4: if (cookiecache[i].version != 4) return 0; if (initiator) { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0) return 1; } break; case 6: if (cookiecache[i].version != 6) return 0; ip6 = (const struct ip6_hdr *)bp2; if (initiator) { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0) return 1; } else { if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0) return 1; } break; default: break; } return 0; } static void hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { const uint8_t *p; size_t i; p = loc; for (i = 0; i < len; i++) ND_PRINT((ndo,"%02x", p[i] & 0xff)); } static int rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len) { ND_TCHECK2(*loc, len); hexprint(ndo, loc, len); return 1; trunc: return 0; } /* * returns false if we run out of data buffer */ static int ike_show_somedata(netdissect_options *ndo, const u_char *cp, const u_char *ep) { /* there is too much data, just show some of it */ const u_char *end = ep - 20; int elen = 20; int len = ep - cp; if(len > 10) { len = 10; } /* really shouldn't happen because of above */ if(end < cp + len) { end = cp+len; elen = ep - end; } ND_PRINT((ndo," data=(")); if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc; ND_PRINT((ndo, "...")); if(elen) { if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc; } ND_PRINT((ndo,")")); return 1; trunc: return 0; } struct attrmap { const char *type; u_int nvalue; const char *value[30]; /*XXX*/ }; static const u_char * ikev1_attrmap_print(netdissect_options *ndo, const u_char *p, const u_char *ep, const struct attrmap *map, size_t nmap) { int totlen; uint32_t t, v; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; if (map && t < nmap && map[t].type) ND_PRINT((ndo,"type=%s ", map[t].type)); else ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); v = EXTRACT_16BITS(&p[2]); if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) ND_PRINT((ndo,"%s", map[t].value[v])); else rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } static const u_char * ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0, int depth) { const struct ikev1_pl_sa *p; struct ikev1_pl_sa sa; uint32_t doi, sit, ident; const u_char *cp, *np; int t; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA))); p = (const struct ikev1_pl_sa *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&sa, ext, sizeof(sa)); doi = ntohl(sa.doi); sit = ntohl(sa.sit); if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit))); return (const u_char *)(p + 1); } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," situation=")); t = 0; if (sit & 0x01) { ND_PRINT((ndo,"identity")); t++; } if (sit & 0x02) { ND_PRINT((ndo,"%ssecrecy", t ? "+" : "")); t++; } if (sit & 0x04) ND_PRINT((ndo,"%sintegrity", t ? "+" : "")); np = (const u_char *)ext + sizeof(sa); if (sit != 0x01) { ND_TCHECK2(*(ext + 1), sizeof(ident)); UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident)); ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident))); np += sizeof(ident); } ext = (const struct isakmp_gen *)np; ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA))); return NULL; } static const u_char * ikev1_p_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase, uint32_t doi0, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_p *p; struct ikev1_pl_p prop; const u_char *cp; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P))); p = (const struct ikev1_pl_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ND_PRINT((ndo," #%d protoid=%s transform=%d", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t)); if (prop.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size)) goto trunc; } ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size); ND_TCHECK(*ext); cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0, prop.prot_id, depth); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const char *ikev1_p_map[] = { NULL, "ike", }; static const char *ikev2_t_type_map[]={ NULL, "encr", "prf", "integ", "dh", "esn" }; static const char *ah_p_map[] = { NULL, "(reserved)", "md5", "sha", "1des", "sha2-256", "sha2-384", "sha2-512", }; static const char *prf_p_map[] = { NULL, "hmac-md5", "hmac-sha", "hmac-tiger", "aes128_xcbc" }; static const char *integ_p_map[] = { NULL, "hmac-md5", "hmac-sha", "dec-mac", "kpdk-md5", "aes-xcbc" }; static const char *esn_p_map[] = { "no-esn", "esn" }; static const char *dh_p_map[] = { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }; static const char *esp_p_map[] = { NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast", "blowfish", "3idea", "1des-iv32", "rc4", "null", "aes" }; static const char *ipcomp_p_map[] = { NULL, "oui", "deflate", "lzs", }; static const struct attrmap ipsec_t_map[] = { { NULL, 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "life", 0, { NULL } }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "enc mode", 3, { NULL, "tunnel", "transport", }, }, { "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, }, { "keylen", 0, { NULL } }, { "rounds", 0, { NULL } }, { "dictsize", 0, { NULL } }, { "privalg", 0, { NULL } }, }; static const struct attrmap encr_t_map[] = { { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/ { NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/ { "keylen", 14, { NULL }}, }; static const struct attrmap oakley_t_map[] = { { NULL, 0, { NULL } }, { "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5", "3des", "cast", "aes", }, }, { "hash", 7, { NULL, "md5", "sha1", "tiger", "sha2-256", "sha2-384", "sha2-512", }, }, { "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc", "rsa enc revised", }, }, { "group desc", 18, { NULL, "modp768", "modp1024", /* group 2 */ "EC2N 2^155", /* group 3 */ "EC2N 2^185", /* group 4 */ "modp1536", /* group 5 */ "iana-grp06", "iana-grp07", /* reserved */ "iana-grp08", "iana-grp09", "iana-grp10", "iana-grp11", "iana-grp12", "iana-grp13", "modp2048", /* group 14 */ "modp3072", /* group 15 */ "modp4096", /* group 16 */ "modp6144", /* group 17 */ "modp8192", /* group 18 */ }, }, { "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, }, { "group prime", 0, { NULL } }, { "group gen1", 0, { NULL } }, { "group gen2", 0, { NULL } }, { "group curve A", 0, { NULL } }, { "group curve B", 0, { NULL } }, { "lifetype", 3, { NULL, "sec", "kb", }, }, { "lifeduration", 0, { NULL } }, { "prf", 0, { NULL } }, { "keylen", 0, { NULL } }, { "field", 0, { NULL } }, { "order", 0, { NULL } }, }; static const u_char * ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; } static const u_char * ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } static const u_char * ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } static const u_char * ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } static const u_char * ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } static const u_char * ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } static const u_char * ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," n len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE))); return NULL; } static const u_char * ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { ND_PRINT((ndo," orig=(")); switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); break; case ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN: if (ikev1_sub_print(ndo, ISAKMP_NPTYPE_SA, (const struct isakmp_gen *)cp, ep, phase, doi, proto, depth) == NULL) return NULL; break; default: /* NULL is dummy */ isakmp_print(ndo, cp, item_len - sizeof(*p) - n.spi_size, NULL); } ND_PRINT((ndo,")")); } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev1_d_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_d *p; struct ikev1_pl_d d; const uint8_t *q; uint32_t doi; uint32_t proto; int i; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D))); p = (const struct ikev1_pl_d *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&d, ext, sizeof(d)); doi = ntohl(d.doi); proto = d.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%u", doi)); ND_PRINT((ndo," proto=%u", proto)); } else { ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); } ND_PRINT((ndo," spilen=%u", d.spi_size)); ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi))); ND_PRINT((ndo," spi=")); q = (const uint8_t *)(p + 1); for (i = 0; i < ntohs(d.num_spi); i++) { if (i != 0) ND_PRINT((ndo,",")); if (!rawprint(ndo, (const uint8_t *)q, d.spi_size)) goto trunc; q += d.spi_size; } return q; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D))); return NULL; } static const u_char * ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } /************************************************************/ /* */ /* IKE v2 - rfc4306 - dissector */ /* */ /************************************************************/ static void ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical) { ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : "")); } static const u_char * ikev2_gen_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_t_print(netdissect_options *ndo, int tcount, const struct isakmp_gen *ext, u_int item_len, const u_char *ep) { const struct ikev2_t *p; struct ikev2_t t; uint16_t t_id; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; p = (const struct ikev2_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical); t_id = ntohs(t.t_id); map = NULL; nmap = 0; switch (t.t_type) { case IV2_T_ENCR: idstr = STR_OR_ID(t_id, esp_p_map); map = encr_t_map; nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]); break; case IV2_T_PRF: idstr = STR_OR_ID(t_id, prf_p_map); break; case IV2_T_INTEG: idstr = STR_OR_ID(t_id, integ_p_map); break; case IV2_T_DH: idstr = STR_OR_ID(t_id, dh_p_map); break; case IV2_T_ESN: idstr = STR_OR_ID(t_id, esn_p_map); break; default: idstr = NULL; break; } if (idstr) ND_PRINT((ndo," #%u type=%s id=%s ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), idstr)); else ND_PRINT((ndo," #%u type=%s id=%u ", tcount, STR_OR_ID(t.t_type, ikev2_t_type_map), t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } static const u_char * ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_, const struct isakmp_gen *ext, u_int oprop_length, const u_char *ep, int depth) { const struct ikev2_p *p; struct ikev2_p prop; u_int prop_length; const u_char *cp; int i; int tcount; u_char np; struct isakmp_gen e; u_int item_len; p = (const struct ikev2_p *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&prop, ext, sizeof(prop)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical); /* * ikev2_sa_print() guarantees that this is >= 4. */ prop_length = oprop_length - 4; ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u", prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t, oprop_length)); cp = (const u_char *)(p + 1); if (prop.spi_size) { if (prop_length < prop.spi_size) goto toolong; ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size)) goto trunc; cp += prop.spi_size; prop_length -= prop.spi_size; } /* * Print the transforms. */ tcount = 0; for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) { tcount++; ext = (const struct isakmp_gen *)cp; if (prop_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (prop_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_T) { cp = ikev2_t_print(ndo, tcount, ext, item_len, ep); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; prop_length -= item_len; } return cp; toolong: /* * Skip the rest of the proposal. */ cp += prop_length; ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P))); return NULL; } static const u_char * ikev2_sa_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext1, u_int osa_length, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth) { const struct isakmp_gen *ext; struct isakmp_gen e; u_int sa_length; const u_char *cp; int i; int pcount; u_char np; u_int item_len; ND_TCHECK(*ext1); UNALIGNED_MEMCPY(&e, ext1, sizeof(e)); ikev2_pay_print(ndo, "sa", e.critical); /* * ikev2_sub0_print() guarantees that this is >= 4. */ osa_length= ntohs(e.len); sa_length = osa_length - 4; ND_PRINT((ndo," len=%d", sa_length)); /* * Print the payloads. */ cp = (const u_char *)(ext1 + 1); pcount = 0; for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) { pcount++; ext = (const struct isakmp_gen *)cp; if (sa_length < sizeof(*ext)) goto toolong; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) goto trunc; if (sa_length < item_len) goto toolong; ND_TCHECK2(*cp, item_len); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); if (np == ISAKMP_NPTYPE_P) { cp = ikev2_p_print(ndo, np, pcount, ext, item_len, ep, depth); if (cp == NULL) { /* error, already reported */ return NULL; } } else { ND_PRINT((ndo, "%s", NPSTR(np))); cp += item_len; } ND_PRINT((ndo,")")); depth--; sa_length -= item_len; } return cp; toolong: /* * Skip the rest of the SA. */ cp += sa_length; ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cert_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_cr_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); ND_PRINT((ndo," len=%d method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (1 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < len) { if(!ike_show_somedata(ndo, authdata, ep)) goto trunc; } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_nonce_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, "nonce", e.critical); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," nonce=(")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < ntohs(e.len)) { if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } /* notify payloads */ static const u_char * ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showdata, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showdata = 0; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; showdata= 0; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if(3 < ndo->ndo_vflag) { showdata = 1; } if ((showdata || (showsomedata && ep-cp < 30)) && cp < ep) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if(showsomedata && cp < ep) { if(!ike_show_somedata(ndo, cp, ep)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } static const u_char * ikev2_d_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_TS_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_e_print(netdissect_options *ndo, #ifndef HAVE_LIBCRYPTO _U_ #endif struct isakmp *base, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t phase, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t doi, #ifndef HAVE_LIBCRYPTO _U_ #endif uint32_t proto, #ifndef HAVE_LIBCRYPTO _U_ #endif int depth) { struct isakmp_gen e; const u_char *dat; volatile int dlen; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); dlen = ntohs(e.len)-4; ND_PRINT((ndo," len=%d", dlen)); if (2 < ndo->ndo_vflag && 4 < dlen) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen)) goto trunc; } dat = (const u_char *)(ext+1); ND_TCHECK2(*dat, dlen); #ifdef HAVE_LIBCRYPTO /* try to decypt it! */ if(esp_print_decrypt_buffer_by_ikev2(ndo, base->flags & ISAKMP_FLAG_I, base->i_ck, base->r_ck, dat, dat+dlen)) { ext = (const struct isakmp_gen *)ndo->ndo_packetp; /* got it decrypted, print stuff inside. */ ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend, phase, doi, proto, depth+1); } #endif /* always return NULL, because E must be at end, and NP refers * to what was inside. */ return NULL; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } static const u_char * ikev2_cp_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ikev2_eap_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { return ikev2_gen_print(ndo, tpay, ext); } static const u_char * ike_sub0_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev1_sub_print(netdissect_options *ndo, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static char * numstr(int x) { static char buf[20]; snprintf(buf, sizeof(buf), "#%d", x); return buf; } static void ikev1_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int i; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo," phase %d", phase)); else ND_PRINT((ndo," phase %d/others", phase)); i = cookie_find(&base->i_ck); if (i < 0) { if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) { /* the first packet */ ND_PRINT((ndo," I")); if (bp2) cookie_record(&base->i_ck, bp2); } else ND_PRINT((ndo," ?")); } else { if (bp2 && cookie_isinitiator(i, bp2)) ND_PRINT((ndo," I")); else if (bp2 && cookie_isresponder(i, bp2)) ND_PRINT((ndo," R")); else ND_PRINT((ndo," ?")); } ND_PRINT((ndo," %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "", base->flags & ISAKMP_FLAG_C ? "C" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo,":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np); np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } static const u_char * ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; struct isakmp_gen e; u_int item_len; cp = (const u_char *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); /* * Since we can't have a payload length of less than 4 bytes, * we need to bail out here if the generic header is nonsensical * or truncated, otherwise we could loop forever processing * zero-length items or otherwise misdissect the packet. */ item_len = ntohs(e.len); if (item_len <= 4) return NULL; if (np == ISAKMP_NPTYPE_v2E) { cp = ikev2_e_print(ndo, base, np, ext, item_len, ep, phase, doi, proto, depth); } else if (NPFUNC(np)) { /* * XXX - what if item_len is too short, or too long, * for this payload type? */ cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth); } else { ND_PRINT((ndo,"%s", NPSTR(np))); cp += item_len; } return cp; trunc: ND_PRINT((ndo," [|isakmp]")); return NULL; } static const u_char * ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,"\n")); for (i = 0; i < depth; i++) ND_PRINT((ndo," ")); ND_PRINT((ndo,"(")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,")")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(np))); return NULL; } static void ikev2_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2 _U_, struct isakmp *base) { const struct isakmp *p; const u_char *ep; u_char np; int phase; p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2; if (phase == 1) ND_PRINT((ndo, " parent_sa")); else ND_PRINT((ndo, " child_sa ")); ND_PRINT((ndo, " %s", ETYPESTR(base->etype))); if (base->flags) { ND_PRINT((ndo, "[%s%s%s]", base->flags & ISAKMP_FLAG_I ? "I" : "", base->flags & ISAKMP_FLAG_V ? "V" : "", base->flags & ISAKMP_FLAG_R ? "R" : "")); } if (ndo->ndo_vflag) { const struct isakmp_gen *ext; ND_PRINT((ndo, ":")); /* regardless of phase... */ if (base->flags & ISAKMP_FLAG_E) { /* * encrypted, nothing we can do right now. * we hope to decrypt the packet in the future... */ ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np))); goto done; } CHECKLEN(p + 1, base->np) np = base->np; ext = (const struct isakmp_gen *)(p + 1); ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0); } done: if (ndo->ndo_vflag) { if (ntohl(base->len) != length) { ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)", (uint32_t)ntohl(base->len), length)); } } } void isakmp_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { const struct isakmp *p; struct isakmp base; const u_char *ep; int major, minor; #ifdef HAVE_LIBCRYPTO /* initialize SAs */ if (ndo->ndo_sa_list_head == NULL) { if (ndo->ndo_espsecret) esp_print_decodesecret(ndo); } #endif p = (const struct isakmp *)bp; ep = ndo->ndo_snapend; if ((const struct isakmp *)ep < p + 1) { ND_PRINT((ndo,"[|isakmp]")); return; } UNALIGNED_MEMCPY(&base, p, sizeof(base)); ND_PRINT((ndo,"isakmp")); major = (base.vers & ISAKMP_VERS_MAJOR) >> ISAKMP_VERS_MAJOR_SHIFT; minor = (base.vers & ISAKMP_VERS_MINOR) >> ISAKMP_VERS_MINOR_SHIFT; if (ndo->ndo_vflag) { ND_PRINT((ndo," %d.%d", major, minor)); } if (ndo->ndo_vflag) { ND_PRINT((ndo," msgid ")); hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid)); } if (1 < ndo->ndo_vflag) { ND_PRINT((ndo," cookie ")); hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck)); ND_PRINT((ndo,"->")); hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck)); } ND_PRINT((ndo,":")); switch(major) { case IKEv1_MAJOR_VERSION: ikev1_print(ndo, bp, length, bp2, &base); break; case IKEv2_MAJOR_VERSION: ikev2_print(ndo, bp, length, bp2, &base); break; } } void isakmp_rfc3948_print(netdissect_options *ndo, const u_char *bp, u_int length, const u_char *bp2) { if(length == 1 && bp[0]==0xff) { ND_PRINT((ndo, "isakmp-nat-keep-alive")); return; } if(length < 4) { goto trunc; } /* * see if this is an IKE packet */ if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) { ND_PRINT((ndo, "NONESP-encap: ")); isakmp_print(ndo, bp+4, length-4, bp2); return; } /* must be an ESP packet */ { int nh, enh, padlen; int advance; ND_PRINT((ndo, "UDP-encap: ")); advance = esp_print(ndo, bp, length, bp2, &enh, &padlen); if(advance <= 0) return; bp += advance; length -= advance + padlen; nh = enh & 0xff; ip_print_inner(ndo, bp, length, nh, bp2); return; } trunc: ND_PRINT((ndo,"[|isakmp]")); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2643_0
crossvul-cpp_data_bad_2588_2
/* * hmp.c -- Midi Wavetable Processing library * * Copyright (C) WildMIDI Developers 2001-2016 * * This file is part of WildMIDI. * * WildMIDI is free software: you can redistribute and/or modify the player * under the terms of the GNU General Public License and you can redistribute * and/or modify the library under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation, either version 3 of * the licenses, or(at your option) any later version. * * WildMIDI is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and * the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License and the * GNU Lesser General Public License along with WildMIDI. If not, see * <http://www.gnu.org/licenses/>. */ #include "config.h" #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "common.h" #include "wm_error.h" #include "wildmidi_lib.h" #include "internal_midi.h" #include "reverb.h" #include "f_hmp.h" /* Turns hmp file data into an event stream */ struct _mdi * _WM_ParseNewHmp(uint8_t *hmp_data, uint32_t hmp_size) { uint8_t is_hmp2 = 0; uint32_t zero_cnt = 0; uint32_t i = 0; uint32_t hmp_file_length = 0; uint32_t hmp_chunks = 0; uint32_t hmp_divisions = 0; uint32_t hmp_unknown = 0; uint32_t hmp_bpm = 0; uint32_t hmp_song_time = 0; struct _mdi *hmp_mdi; uint8_t **hmp_chunk; uint32_t *chunk_length; uint32_t *chunk_ofs; uint32_t *chunk_delta; uint8_t *chunk_end; uint32_t chunk_num = 0; uint32_t hmp_track = 0; // uint32_t j = 0; uint32_t smallest_delta = 0; uint32_t subtract_delta = 0; // uint32_t chunks_finished = 0; uint32_t end_of_chunks = 0; uint32_t var_len_shift = 0; float tempo_f = 500000.0; float samples_per_delta_f = 0.0; // uint8_t hmp_event = 0; // uint8_t hmp_channel = 0; uint32_t sample_count = 0; float sample_count_f = 0; float sample_remainder = 0; if (memcmp(hmp_data, "HMIMIDIP", 8)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0); return NULL; } hmp_data += 8; hmp_size -= 8; if (!memcmp(hmp_data, "013195", 6)) { hmp_data += 6; hmp_size -= 6; is_hmp2 = 1; } // should be a bunch of \0's if (is_hmp2) { zero_cnt = 18; } else { zero_cnt = 24; } for (i = 0; i < zero_cnt; i++) { if (hmp_data[i] != 0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, NULL, 0); return NULL; } } hmp_data += zero_cnt; hmp_size -= zero_cnt; hmp_file_length = *hmp_data++; hmp_file_length += (*hmp_data++ << 8); hmp_file_length += (*hmp_data++ << 16); hmp_file_length += (*hmp_data++ << 24); hmp_size -= 4; UNUSED(hmp_file_length); // Next 12 bytes are normally \0 so skipping over them hmp_data += 12; hmp_size -= 12; hmp_chunks = *hmp_data++; hmp_chunks += (*hmp_data++ << 8); hmp_chunks += (*hmp_data++ << 16); hmp_chunks += (*hmp_data++ << 24); hmp_size -= 4; // Still decyphering what this is hmp_unknown = *hmp_data++; hmp_unknown += (*hmp_data++ << 8); hmp_unknown += (*hmp_data++ << 16); hmp_unknown += (*hmp_data++ << 24); hmp_size -= 4; UNUSED(hmp_unknown); // Defaulting: experimenting has found this to be the ideal value hmp_divisions = 60; // Beats per minute hmp_bpm = *hmp_data++; hmp_bpm += (*hmp_data++ << 8); hmp_bpm += (*hmp_data++ << 16); hmp_bpm += (*hmp_data++ << 24); hmp_size -= 4; /* Slow but needed for accuracy */ if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / hmp_bpm) + 0.5f; } else { tempo_f = (float) (60000000 / hmp_bpm); } samples_per_delta_f = _WM_GetSamplesPerTick(hmp_divisions, tempo_f); //DEBUG //fprintf(stderr, "DEBUG: Samples Per Delta Tick: %f\r\n",samples_per_delta_f); // FIXME: This value is incorrect hmp_song_time = *hmp_data++; hmp_song_time += (*hmp_data++ << 8); hmp_song_time += (*hmp_data++ << 16); hmp_song_time += (*hmp_data++ << 24); hmp_size -= 4; // DEBUG //fprintf(stderr,"DEBUG: ??DIVISIONS??: %u, BPM: %u, ??SONG TIME??: %u:%.2u\r\n",hmp_divisions, hmp_bpm, (hmp_song_time / 60), (hmp_song_time % 60)); UNUSED(hmp_song_time); if (is_hmp2) { hmp_data += 840; hmp_size -= 840; } else { hmp_data += 712; hmp_size -= 712; } hmp_mdi = _WM_initMDI(); _WM_midi_setup_divisions(hmp_mdi, hmp_divisions); _WM_midi_setup_tempo(hmp_mdi, (uint32_t)tempo_f); hmp_chunk = malloc(sizeof(uint8_t *) * hmp_chunks); chunk_length = malloc(sizeof(uint32_t) * hmp_chunks); chunk_delta = malloc(sizeof(uint32_t) * hmp_chunks); chunk_ofs = malloc(sizeof(uint32_t) * hmp_chunks); chunk_end = malloc(sizeof(uint8_t) * hmp_chunks); smallest_delta = 0xffffffff; // store chunk info for use, and check chunk lengths for (i = 0; i < hmp_chunks; i++) { hmp_chunk[i] = hmp_data; chunk_ofs[i] = 0; chunk_num = *hmp_data++; chunk_num += (*hmp_data++ << 8); chunk_num += (*hmp_data++ << 16); chunk_num += (*hmp_data++ << 24); chunk_ofs[i] += 4; UNUSED(chunk_num); chunk_length[i] = *hmp_data++; chunk_length[i] += (*hmp_data++ << 8); chunk_length[i] += (*hmp_data++ << 16); chunk_length[i] += (*hmp_data++ << 24); chunk_ofs[i] += 4; if (chunk_length[i] > hmp_size) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMP, "file too short", 0); goto _hmp_end; } hmp_size -= chunk_length[i]; hmp_track = *hmp_data++; hmp_track += (*hmp_data++ << 8); hmp_track += (*hmp_data++ << 16); hmp_track += (*hmp_data++ << 24); chunk_ofs[i] += 4; UNUSED(hmp_track); // Start of Midi Data chunk_delta[i] = 0; var_len_shift = 0; if (*hmp_data < 0x80) { do { chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift); var_len_shift += 7; chunk_ofs[i]++; } while (*hmp_data < 0x80); } chunk_delta[i] = chunk_delta[i] | ((*hmp_data++ & 0x7F) << var_len_shift); chunk_ofs[i]++; if (chunk_delta[i] < smallest_delta) { smallest_delta = chunk_delta[i]; } // goto start of next chunk hmp_data = hmp_chunk[i] + chunk_length[i]; hmp_chunk[i] += chunk_ofs[i]++; chunk_end[i] = 0; } subtract_delta = smallest_delta; sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count; hmp_mdi->extra_info.approx_total_samples += sample_count; while (end_of_chunks < hmp_chunks) { smallest_delta = 0; // DEBUG // fprintf(stderr,"DEBUG: Delta Ticks: %u\r\n",subtract_delta); for (i = 0; i < hmp_chunks; i++) { if (chunk_end[i]) continue; if (chunk_delta[i]) { chunk_delta[i] -= subtract_delta; if (chunk_delta[i]) { if ((!smallest_delta) || (smallest_delta > chunk_delta[i])) { smallest_delta = chunk_delta[i]; } continue; } } do { if (((hmp_chunk[i][0] & 0xf0) == 0xb0 ) && ((hmp_chunk[i][1] == 110) || (hmp_chunk[i][1] == 111)) && (hmp_chunk[i][2] > 0x7f)) { // Reserved for loop markers // TODO: still deciding what to do about these hmp_chunk[i] += 3; } else { uint32_t setup_ret = 0; if ((setup_ret = _WM_SetupMidiEvent(hmp_mdi, hmp_chunk[i], 0)) == 0) { goto _hmp_end; } if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x2f) && (hmp_chunk[i][2] == 0x00)) { /* End of Chunk */ end_of_chunks++; chunk_end[i] = 1; hmp_chunk[i] += 3; goto NEXT_CHUNK; } else if ((hmp_chunk[i][0] == 0xff) && (hmp_chunk[i][1] == 0x51) && (hmp_chunk[i][2] == 0x03)) { /* Tempo */ tempo_f = (float)((hmp_chunk[i][3] << 16) + (hmp_chunk[i][4] << 8)+ hmp_chunk[i][5]); if (tempo_f == 0.0) tempo_f = 500000.0; // DEBUG fprintf(stderr,"DEBUG: Tempo change %f\r\n", tempo_f); } hmp_chunk[i] += setup_ret; } var_len_shift = 0; chunk_delta[i] = 0; if (*hmp_chunk[i] < 0x80) { do { chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift); var_len_shift += 7; hmp_chunk[i]++; } while (*hmp_chunk[i] < 0x80); } chunk_delta[i] = chunk_delta[i] + ((*hmp_chunk[i] & 0x7F) << var_len_shift); hmp_chunk[i]++; } while (!chunk_delta[i]); if ((!smallest_delta) || (smallest_delta > chunk_delta[i])) { smallest_delta = chunk_delta[i]; } NEXT_CHUNK: continue; } subtract_delta = smallest_delta; sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; hmp_mdi->events[hmp_mdi->event_count - 1].samples_to_next += sample_count; hmp_mdi->extra_info.approx_total_samples += sample_count; // DEBUG // fprintf(stderr,"DEBUG: Sample Count %u\r\n",sample_count); } if ((hmp_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0); goto _hmp_end; } hmp_mdi->extra_info.current_sample = 0; hmp_mdi->current_event = &hmp_mdi->events[0]; hmp_mdi->samples_to_mix = 0; hmp_mdi->note = NULL; _WM_ResetToStart(hmp_mdi); _hmp_end: free(hmp_chunk); free(chunk_length); free(chunk_delta); free(chunk_ofs); free(chunk_end); if (hmp_mdi->reverb) return (hmp_mdi); _WM_freeMDI(hmp_mdi); return NULL; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_2588_2
crossvul-cpp_data_bad_5515_1
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Andrei Zmievski <andrei@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_WDDX #include "ext/xml/expat_compat.h" #include "php_wddx.h" #include "php_wddx_api.h" #define PHP_XML_INTERNAL #include "ext/xml/php_xml.h" #include "ext/standard/php_incomplete_class.h" #include "ext/standard/base64.h" #include "ext/standard/info.h" #include "ext/standard/php_smart_str.h" #include "ext/standard/html.h" #include "ext/standard/php_string.h" #include "ext/date/php_date.h" #include "zend_globals.h" #define WDDX_BUF_LEN 256 #define PHP_CLASS_NAME_VAR "php_class_name" #define EL_ARRAY "array" #define EL_BINARY "binary" #define EL_BOOLEAN "boolean" #define EL_CHAR "char" #define EL_CHAR_CODE "code" #define EL_NULL "null" #define EL_NUMBER "number" #define EL_PACKET "wddxPacket" #define EL_STRING "string" #define EL_STRUCT "struct" #define EL_VALUE "value" #define EL_VAR "var" #define EL_NAME "name" #define EL_VERSION "version" #define EL_RECORDSET "recordset" #define EL_FIELD "field" #define EL_DATETIME "dateTime" #define php_wddx_deserialize(a,b) \ php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b)) #define SET_STACK_VARNAME \ if (stack->varname) { \ ent.varname = estrdup(stack->varname); \ efree(stack->varname); \ stack->varname = NULL; \ } else \ ent.varname = NULL; \ static int le_wddx; typedef struct { zval *data; enum { ST_ARRAY, ST_BOOLEAN, ST_NULL, ST_NUMBER, ST_STRING, ST_BINARY, ST_STRUCT, ST_RECORDSET, ST_FIELD, ST_DATETIME } type; char *varname; } st_entry; typedef struct { int top, max; char *varname; zend_bool done; void **elements; } wddx_stack; static void php_wddx_process_data(void *user_data, const XML_Char *s, int len); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1) ZEND_ARG_INFO(0, var) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1) ZEND_ARG_INFO(0, packet_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2) ZEND_ARG_INFO(0, packet_id) ZEND_ARG_VARIADIC_INFO(0, var_names) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1) ZEND_ARG_INFO(0, packet) ZEND_END_ARG_INFO() /* }}} */ /* {{{ wddx_functions[] */ const zend_function_entry wddx_functions[] = { PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value) PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars) PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start) PHP_FE(wddx_packet_end, arginfo_wddx_packet_end) PHP_FE(wddx_add_vars, arginfo_wddx_add_vars) PHP_FE(wddx_deserialize, arginfo_wddx_deserialize) PHP_FE_END }; /* }}} */ PHP_MINIT_FUNCTION(wddx); PHP_MINFO_FUNCTION(wddx); /* {{{ dynamically loadable module stuff */ #ifdef COMPILE_DL_WDDX ZEND_GET_MODULE(wddx) #endif /* COMPILE_DL_WDDX */ /* }}} */ /* {{{ wddx_module_entry */ zend_module_entry wddx_module_entry = { STANDARD_MODULE_HEADER, "wddx", wddx_functions, PHP_MINIT(wddx), NULL, NULL, NULL, PHP_MINFO(wddx), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; /* }}} */ /* {{{ wddx_stack_init */ static int wddx_stack_init(wddx_stack *stack) { stack->top = 0; stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0); stack->max = STACK_BLOCK_SIZE; stack->varname = NULL; stack->done = 0; return SUCCESS; } /* }}} */ /* {{{ wddx_stack_push */ static int wddx_stack_push(wddx_stack *stack, void *element, int size) { if (stack->top >= stack->max) { /* we need to allocate more memory */ stack->elements = (void **) erealloc(stack->elements, (sizeof(void **) * (stack->max += STACK_BLOCK_SIZE))); } stack->elements[stack->top] = (void *) emalloc(size); memcpy(stack->elements[stack->top], element, size); return stack->top++; } /* }}} */ /* {{{ wddx_stack_top */ static int wddx_stack_top(wddx_stack *stack, void **element) { if (stack->top > 0) { *element = stack->elements[stack->top - 1]; return SUCCESS; } else { *element = NULL; return FAILURE; } } /* }}} */ /* {{{ wddx_stack_is_empty */ static int wddx_stack_is_empty(wddx_stack *stack) { if (stack->top == 0) { return 1; } else { return 0; } } /* }}} */ /* {{{ wddx_stack_destroy */ static int wddx_stack_destroy(wddx_stack *stack) { register int i; if (stack->elements) { for (i = 0; i < stack->top; i++) { if (((st_entry *)stack->elements[i])->data && ((st_entry *)stack->elements[i])->type != ST_FIELD) { zval_ptr_dtor(&((st_entry *)stack->elements[i])->data); } if (((st_entry *)stack->elements[i])->varname) { efree(((st_entry *)stack->elements[i])->varname); } efree(stack->elements[i]); } efree(stack->elements); } return SUCCESS; } /* }}} */ /* {{{ release_wddx_packet_rsrc */ static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { smart_str *str = (smart_str *)rsrc->ptr; smart_str_free(str); efree(str); } /* }}} */ #include "ext/session/php_session.h" #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) /* {{{ PS_SERIALIZER_ENCODE_FUNC */ PS_SERIALIZER_ENCODE_FUNC(wddx) { wddx_packet *packet; PS_ENCODE_VARS; packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); PS_ENCODE_LOOP( php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC); ); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); *newstr = php_wddx_gather(packet); php_wddx_destructor(packet); if (newlen) { *newlen = strlen(*newstr); } return SUCCESS; } /* }}} */ /* {{{ PS_SERIALIZER_DECODE_FUNC */ PS_SERIALIZER_DECODE_FUNC(wddx) { zval *retval; zval **ent; char *key; uint key_length; char tmp[128]; ulong idx; int hash_type; int ret; if (vallen == 0) { return SUCCESS; } MAKE_STD_ZVAL(retval); if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) { if (Z_TYPE_P(retval) != IS_ARRAY) { zval_ptr_dtor(&retval); return FAILURE; } for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval)); zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS; zend_hash_move_forward(Z_ARRVAL_P(retval))) { hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL); switch (hash_type) { case HASH_KEY_IS_LONG: key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC); PS_ADD_VAR(key); } } } zval_ptr_dtor(&retval); return ret; } /* }}} */ #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(wddx) { le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_session_register_serializer("wddx", PS_SERIALIZER_ENCODE_NAME(wddx), PS_SERIALIZER_DECODE_NAME(wddx)); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(wddx) { php_info_print_table_start(); #if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) php_info_print_table_header(2, "WDDX Support", "enabled" ); php_info_print_table_row(2, "WDDX Session Serializer", "enabled" ); #else php_info_print_table_row(2, "WDDX Support", "enabled" ); #endif php_info_print_table_end(); } /* }}} */ /* {{{ php_wddx_packet_start */ void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len) { php_wddx_add_chunk_static(packet, WDDX_PACKET_S); if (comment) { char *escaped; size_t escaped_len; TSRMLS_FETCH(); escaped = php_escape_html_entities( comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_static(packet, WDDX_HEADER_S); php_wddx_add_chunk_static(packet, WDDX_COMMENT_S); php_wddx_add_chunk_ex(packet, escaped, escaped_len); php_wddx_add_chunk_static(packet, WDDX_COMMENT_E); php_wddx_add_chunk_static(packet, WDDX_HEADER_E); str_efree(escaped); } else { php_wddx_add_chunk_static(packet, WDDX_HEADER); } php_wddx_add_chunk_static(packet, WDDX_DATA_S); } /* }}} */ /* {{{ php_wddx_packet_end */ void php_wddx_packet_end(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_DATA_E); php_wddx_add_chunk_static(packet, WDDX_PACKET_E); } /* }}} */ #define FLUSH_BUF() \ if (l > 0) { \ php_wddx_add_chunk_ex(packet, buf, l); \ l = 0; \ } /* {{{ php_wddx_serialize_string */ static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC) { php_wddx_add_chunk_static(packet, WDDX_STRING_S); if (Z_STRLEN_P(var) > 0) { char *buf; size_t buf_len; buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC); php_wddx_add_chunk_ex(packet, buf, buf_len); str_efree(buf); } php_wddx_add_chunk_static(packet, WDDX_STRING_E); } /* }}} */ /* {{{ php_wddx_serialize_number */ static void php_wddx_serialize_number(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; zval tmp; tmp = *var; zval_copy_ctor(&tmp); convert_to_string(&tmp); snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp)); zval_dtor(&tmp); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ /* {{{ php_wddx_serialize_boolean */ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE); } /* }}} */ /* {{{ php_wddx_serialize_unset */ static void php_wddx_serialize_unset(wddx_packet *packet) { php_wddx_add_chunk_static(packet, WDDX_NULL); } /* }}} */ /* {{{ php_wddx_serialize_object */ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) { /* OBJECTS_FIXME */ zval **ent, *fname, **varname; zval *retval = NULL; const char *key; ulong idx; char tmp_buf[WDDX_BUF_LEN]; HashTable *objhash, *sleephash; zend_class_entry *ce; PHP_CLASS_ATTRIBUTES; TSRMLS_FETCH(); PHP_SET_CLASS_ATTRIBUTES(obj); ce = Z_OBJCE_P(obj); if (!ce || ce->serialize || ce->unserialize) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be serialized", class_name); PHP_CLEANUP_CLASS_ATTRIBUTES(); return; } MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__sleep", 1); /* * We try to call __sleep() method on object. It's supposed to return an * array of property names to be serialized. */ if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) { if (retval && (sleephash = HASH_OF(retval))) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(sleephash); zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS; zend_hash_move_forward(sleephash)) { if (Z_TYPE_PP(varname) != IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize."); continue; } if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) { php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } } else { uint key_len; php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR); php_wddx_add_chunk(packet, tmp_buf); php_wddx_add_chunk_static(packet, WDDX_STRING_S); php_wddx_add_chunk_ex(packet, class_name, name_len); php_wddx_add_chunk_static(packet, WDDX_STRING_E); php_wddx_add_chunk_static(packet, WDDX_VAR_E); objhash = HASH_OF(obj); for (zend_hash_internal_pointer_reset(objhash); zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS; zend_hash_move_forward(objhash)) { if (*ent == obj) { continue; } if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) { const char *class_name, *prop_name; zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } PHP_CLEANUP_CLASS_ATTRIBUTES(); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } /* }}} */ /* {{{ php_wddx_serialize_array */ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) { zval **ent; char *key; uint key_len; int is_struct = 0, ent_type; ulong idx; HashTable *target_hash; char tmp_buf[WDDX_BUF_LEN]; ulong ind = 0; int type; TSRMLS_FETCH(); target_hash = HASH_OF(arr); for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { type = zend_hash_get_current_key(target_hash, &key, &idx, 0); if (type == HASH_KEY_IS_STRING) { is_struct = 1; break; } if (idx != ind) { is_struct = 1; break; } ind++; } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } for (zend_hash_internal_pointer_reset(target_hash); zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS; zend_hash_move_forward(target_hash)) { if (*ent == arr) { continue; } if (is_struct) { ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL); if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else { php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC); } } if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); } else { php_wddx_add_chunk_static(packet, WDDX_ARRAY_E); } } /* }}} */ /* {{{ php_wddx_serialize_var */ void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); str_efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } } /* }}} */ /* {{{ php_wddx_add_var */ static void php_wddx_add_var(wddx_packet *packet, zval *name_var) { zval **val; HashTable *target_hash; TSRMLS_FETCH(); if (Z_TYPE_P(name_var) == IS_STRING) { if (!EG(active_symbol_table)) { zend_rebuild_symbol_table(TSRMLS_C); } if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var), Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) { php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC); } } else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) { int is_array = Z_TYPE_P(name_var) == IS_ARRAY; target_hash = HASH_OF(name_var); if (is_array && target_hash->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected"); return; } zend_hash_internal_pointer_reset(target_hash); while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) { if (is_array) { target_hash->nApplyCount++; } php_wddx_add_var(packet, *val); if (is_array) { target_hash->nApplyCount--; } zend_hash_move_forward(target_hash); } } } /* }}} */ /* {{{ php_wddx_push_element */ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } /* }}} */ /* {{{ php_wddx_pop_element */ static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } if (pce != &PHP_IC_ENTRY && ((*pce)->serialize || (*pce)->unserialize)) { zval_ptr_dtor(&ent2->data); ent2->data = NULL; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be unserialized", Z_STRVAL_P(ent1->data)); } else { /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } /* }}} */ /* {{{ php_wddx_process_data */ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; if (Z_TYPE_P(ent->data) == IS_STRING) { tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1); memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data)); memcpy(tmp + Z_STRLEN_P(ent->data), s, len); len += Z_STRLEN_P(ent->data); efree(Z_STRVAL_P(ent->data)); Z_TYPE_P(ent->data) = IS_LONG; } else { tmp = emalloc(len + 1); memcpy(tmp, s, len); } tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { ZVAL_STRINGL(ent->data, tmp, len, 0); } else { efree(tmp); } } break; default: break; } } } /* }}} */ /* {{{ php_wddx_deserialize_ex */ int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); if(ent->data == NULL) { retval = FAILURE; } else { *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } /* }}} */ /* {{{ proto string wddx_serialize_value(mixed var [, string comment]) Creates a new packet and serializes the given value */ PHP_FUNCTION(wddx_serialize_value) { zval *var; char *comment = NULL; int comment_len = 0; wddx_packet *packet; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...]) Creates a new packet and serializes given variables into a struct */ PHP_FUNCTION(wddx_serialize_vars) { int num_args, i; wddx_packet *packet; zval ***args = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, NULL, 0); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, *args[i]); } php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); efree(args); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ php_wddx_constructor */ wddx_packet *php_wddx_constructor(void) { smart_str *packet; packet = (smart_str *)emalloc(sizeof(smart_str)); packet->c = NULL; return packet; } /* }}} */ /* {{{ php_wddx_destructor */ void php_wddx_destructor(wddx_packet *packet) { smart_str_free(packet); efree(packet); } /* }}} */ /* {{{ proto resource wddx_packet_start([string comment]) Starts a WDDX packet with optional comment and returns the packet id */ PHP_FUNCTION(wddx_packet_start) { char *comment = NULL; int comment_len = 0; wddx_packet *packet; comment = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) { return; } packet = php_wddx_constructor(); php_wddx_packet_start(packet, comment, comment_len); php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx); } /* }}} */ /* {{{ proto string wddx_packet_end(resource packet_id) Ends specified WDDX packet and returns the string containing the packet */ PHP_FUNCTION(wddx_packet_end) { zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) { return; } ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx); php_wddx_add_chunk_static(packet, WDDX_STRUCT_E); php_wddx_packet_end(packet); ZVAL_STRINGL(return_value, packet->c, packet->len, 1); zend_list_delete(Z_LVAL_P(packet_id)); } /* }}} */ /* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...]) Serializes given variables and adds them to packet given by packet_id */ PHP_FUNCTION(wddx_add_vars) { int num_args, i; zval ***args = NULL; zval *packet_id; wddx_packet *packet = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) { return; } if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) { efree(args); RETURN_FALSE; } if (!packet) { efree(args); RETURN_FALSE; } for (i=0; i<num_args; i++) { if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) { convert_to_string_ex(args[i]); } php_wddx_add_var(packet, (*args[i])); } efree(args); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed wddx_deserialize(mixed packet) Deserializes given packet and returns a PHP value */ PHP_FUNCTION(wddx_deserialize) { zval *packet; char *payload; int payload_len; php_stream *stream = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) { return; } if (Z_TYPE_P(packet) == IS_STRING) { payload = Z_STRVAL_P(packet); payload_len = Z_STRLEN_P(packet); } else if (Z_TYPE_P(packet) == IS_RESOURCE) { php_stream_from_zval(stream, &packet); if (stream) { payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream"); return; } if (payload_len == 0) { return; } php_wddx_deserialize_ex(payload, payload_len, return_value); if (stream) { pefree(payload, 0); } } /* }}} */ #endif /* HAVE_LIBEXPAT */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-125/c/bad_5515_1
crossvul-cpp_data_bad_3328_3
/* Copyright (c) 2014. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdlib.h> #include <ctype.h> #include <yara/globals.h> #include <yara/limits.h> #include <yara/utils.h> #include <yara/re.h> #include <yara/types.h> #include <yara/error.h> #include <yara/libyara.h> #include <yara/scan.h> typedef struct _CALLBACK_ARGS { YR_STRING* string; YR_SCAN_CONTEXT* context; uint8_t* data; size_t data_size; size_t data_base; int forward_matches; int full_word; } CALLBACK_ARGS; int _yr_scan_compare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length) return 0; while (i < string_length && *s1++ == *s2++) i++; return (int) ((i == string_length) ? i : 0); } int _yr_scan_icompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length) return 0; while (i < string_length && yr_lowercase[*s1++] == yr_lowercase[*s2++]) i++; return (int) ((i == string_length) ? i : 0); } int _yr_scan_wcompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length * 2) return 0; while (i < string_length && *s1 == *s2) { s1+=2; s2++; i++; } return (int) ((i == string_length) ? i * 2 : 0); } int _yr_scan_wicompare( uint8_t* data, size_t data_size, uint8_t* string, size_t string_length) { uint8_t* s1 = data; uint8_t* s2 = string; size_t i = 0; if (data_size < string_length * 2) return 0; while (i < string_length && yr_lowercase[*s1] == yr_lowercase[*s2]) { s1+=2; s2++; i++; } return (int) ((i == string_length) ? i * 2 : 0); } void _yr_scan_update_match_chain_length( int tidx, YR_STRING* string, YR_MATCH* match_to_update, int chain_length) { YR_MATCH* match; if (match_to_update->chain_length == chain_length) return; match_to_update->chain_length = chain_length; if (string->chained_to == NULL) return; match = string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { int64_t ending_offset = match->offset + match->match_length; if (ending_offset + string->chain_gap_max >= match_to_update->offset && ending_offset + string->chain_gap_min <= match_to_update->offset) { _yr_scan_update_match_chain_length( tidx, string->chained_to, match, chain_length + 1); } match = match->next; } } int _yr_scan_add_match_to_list( YR_MATCH* match, YR_MATCHES* matches_list, int replace_if_exists) { YR_MATCH* insertion_point = matches_list->tail; if (matches_list->count == MAX_STRING_MATCHES) return ERROR_TOO_MANY_MATCHES; while (insertion_point != NULL) { if (match->offset == insertion_point->offset) { if (replace_if_exists) { insertion_point->match_length = match->match_length; insertion_point->data_length = match->data_length; insertion_point->data = match->data; } return ERROR_SUCCESS; } if (match->offset > insertion_point->offset) break; insertion_point = insertion_point->prev; } match->prev = insertion_point; if (insertion_point != NULL) { match->next = insertion_point->next; insertion_point->next = match; } else { match->next = matches_list->head; matches_list->head = match; } matches_list->count++; if (match->next != NULL) match->next->prev = match; else matches_list->tail = match; return ERROR_SUCCESS; } void _yr_scan_remove_match_from_list( YR_MATCH* match, YR_MATCHES* matches_list) { if (match->prev != NULL) match->prev->next = match->next; if (match->next != NULL) match->next->prev = match->prev; if (matches_list->head == match) matches_list->head = match->next; if (matches_list->tail == match) matches_list->tail = match->prev; matches_list->count--; match->next = NULL; match->prev = NULL; } int _yr_scan_verify_chained_string_match( YR_STRING* matching_string, YR_SCAN_CONTEXT* context, uint8_t* match_data, uint64_t match_base, uint64_t match_offset, int32_t match_length) { YR_STRING* string; YR_MATCH* match; YR_MATCH* next_match; YR_MATCH* new_match; uint64_t lower_offset; uint64_t ending_offset; int32_t full_chain_length; int tidx = context->tidx; int add_match = FALSE; if (matching_string->chained_to == NULL) { add_match = TRUE; } else { if (matching_string->unconfirmed_matches[tidx].head != NULL) lower_offset = matching_string->unconfirmed_matches[tidx].head->offset; else lower_offset = match_offset; match = matching_string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { next_match = match->next; ending_offset = match->offset + match->match_length; if (ending_offset + matching_string->chain_gap_max < lower_offset) { _yr_scan_remove_match_from_list( match, &matching_string->chained_to->unconfirmed_matches[tidx]); } else { if (ending_offset + matching_string->chain_gap_max >= match_offset && ending_offset + matching_string->chain_gap_min <= match_offset) { add_match = TRUE; break; } } match = next_match; } } if (add_match) { if (STRING_IS_CHAIN_TAIL(matching_string)) { // Chain tails must be chained to some other string assert(matching_string->chained_to != NULL); match = matching_string->chained_to->unconfirmed_matches[tidx].head; while (match != NULL) { ending_offset = match->offset + match->match_length; if (ending_offset + matching_string->chain_gap_max >= match_offset && ending_offset + matching_string->chain_gap_min <= match_offset) { _yr_scan_update_match_chain_length( tidx, matching_string->chained_to, match, 1); } match = match->next; } full_chain_length = 0; string = matching_string; while(string->chained_to != NULL) { full_chain_length++; string = string->chained_to; } // "string" points now to the head of the strings chain match = string->unconfirmed_matches[tidx].head; while (match != NULL) { next_match = match->next; if (match->chain_length == full_chain_length) { _yr_scan_remove_match_from_list( match, &string->unconfirmed_matches[tidx]); match->match_length = (int32_t) \ (match_offset - match->offset + match_length); match->data_length = yr_min(match->match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( context->matches_arena, match_data - match_offset + match->offset, match->data_length, (void**) &match->data)); FAIL_ON_ERROR(_yr_scan_add_match_to_list( match, &string->matches[tidx], FALSE)); } match = next_match; } } else { if (matching_string->matches[tidx].count == 0 && matching_string->unconfirmed_matches[tidx].count == 0) { // If this is the first match for the string, put the string in the // list of strings whose flags needs to be cleared after the scan. FAIL_ON_ERROR(yr_arena_write_data( context->matching_strings_arena, &matching_string, sizeof(matching_string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); new_match->base = match_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->chain_length = 0; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &matching_string->unconfirmed_matches[tidx], FALSE)); } } return ERROR_SUCCESS; } int _yr_scan_match_callback( uint8_t* match_data, int32_t match_length, int flags, void* args) { CALLBACK_ARGS* callback_args = (CALLBACK_ARGS*) args; YR_STRING* string = callback_args->string; YR_MATCH* new_match; int result = ERROR_SUCCESS; int tidx = callback_args->context->tidx; size_t match_offset = match_data - callback_args->data; // total match length is the sum of backward and forward matches. match_length += callback_args->forward_matches; if (callback_args->full_word) { if (flags & RE_FLAGS_WIDE) { if (match_offset >= 2 && *(match_data - 1) == 0 && isalnum(*(match_data - 2))) return ERROR_SUCCESS; if (match_offset + match_length + 1 < callback_args->data_size && *(match_data + match_length + 1) == 0 && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } else { if (match_offset >= 1 && isalnum(*(match_data - 1))) return ERROR_SUCCESS; if (match_offset + match_length < callback_args->data_size && isalnum(*(match_data + match_length))) return ERROR_SUCCESS; } } if (STRING_IS_CHAIN_PART(string)) { result = _yr_scan_verify_chained_string_match( string, callback_args->context, match_data, callback_args->data_base, match_offset, match_length); } else { if (string->matches[tidx].count == 0) { // If this is the first match for the string, put the string in the // list of strings whose flags needs to be cleared after the scan. FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matching_strings_arena, &string, sizeof(string), NULL)); } FAIL_ON_ERROR(yr_arena_allocate_memory( callback_args->context->matches_arena, sizeof(YR_MATCH), (void**) &new_match)); new_match->data_length = yr_min(match_length, MAX_MATCH_DATA); FAIL_ON_ERROR(yr_arena_write_data( callback_args->context->matches_arena, match_data, new_match->data_length, (void**) &new_match->data)); if (result == ERROR_SUCCESS) { new_match->base = callback_args->data_base; new_match->offset = match_offset; new_match->match_length = match_length; new_match->prev = NULL; new_match->next = NULL; FAIL_ON_ERROR(_yr_scan_add_match_to_list( new_match, &string->matches[tidx], STRING_IS_GREEDY_REGEXP(string))); } } return result; } typedef int (*RE_EXEC_FUNC)( uint8_t* code, uint8_t* input, size_t input_size, int flags, RE_MATCH_CALLBACK_FUNC callback, void* callback_args); int _yr_scan_verify_re_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { CALLBACK_ARGS callback_args; RE_EXEC_FUNC exec; int forward_matches = -1; int backward_matches = -1; int flags = 0; if (STRING_IS_GREEDY_REGEXP(ac_match->string)) flags |= RE_FLAGS_GREEDY; if (STRING_IS_NO_CASE(ac_match->string)) flags |= RE_FLAGS_NO_CASE; if (STRING_IS_DOT_ALL(ac_match->string)) flags |= RE_FLAGS_DOT_ALL; if (STRING_IS_FAST_REGEXP(ac_match->string)) exec = yr_re_fast_exec; else exec = yr_re_exec; if (STRING_IS_ASCII(ac_match->string)) { forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags, NULL, NULL); } if (STRING_IS_WIDE(ac_match->string) && forward_matches == -1) { flags |= RE_FLAGS_WIDE; forward_matches = exec( ac_match->forward_code, data + offset, data_size - offset, offset > 0 ? flags | RE_FLAGS_NOT_AT_START : flags, NULL, NULL); } switch(forward_matches) { case -1: return ERROR_SUCCESS; case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } if (forward_matches == 0 && ac_match->backward_code == NULL) return ERROR_SUCCESS; callback_args.string = ac_match->string; callback_args.context = context; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(ac_match->string); if (ac_match->backward_code != NULL) { backward_matches = exec( ac_match->backward_code, data + offset, offset, flags | RE_FLAGS_BACKWARDS | RE_FLAGS_EXHAUSTIVE, _yr_scan_match_callback, (void*) &callback_args); switch(backward_matches) { case -2: return ERROR_INSUFFICIENT_MEMORY; case -3: return ERROR_TOO_MANY_MATCHES; case -4: return ERROR_TOO_MANY_RE_FIBERS; case -5: return ERROR_INTERNAL_FATAL_ERROR; } } else { FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); } return ERROR_SUCCESS; } int _yr_scan_verify_literal_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { int flags = 0; int forward_matches = 0; CALLBACK_ARGS callback_args; YR_STRING* string = ac_match->string; if (STRING_FITS_IN_ATOM(string)) { forward_matches = ac_match->backtrack; } else if (STRING_IS_NO_CASE(string)) { if (STRING_IS_ASCII(string)) { forward_matches = _yr_scan_icompare( data + offset, data_size - offset, string->string, string->length); } if (STRING_IS_WIDE(string) && forward_matches == 0) { forward_matches = _yr_scan_wicompare( data + offset, data_size - offset, string->string, string->length); } } else { if (STRING_IS_ASCII(string)) { forward_matches = _yr_scan_compare( data + offset, data_size - offset, string->string, string->length); } if (STRING_IS_WIDE(string) && forward_matches == 0) { forward_matches = _yr_scan_wcompare( data + offset, data_size - offset, string->string, string->length); } } if (forward_matches == 0) return ERROR_SUCCESS; if (forward_matches == string->length * 2) flags |= RE_FLAGS_WIDE; if (STRING_IS_NO_CASE(string)) flags |= RE_FLAGS_NO_CASE; callback_args.context = context; callback_args.string = string; callback_args.data = data; callback_args.data_size = data_size; callback_args.data_base = data_base; callback_args.forward_matches = forward_matches; callback_args.full_word = STRING_IS_FULL_WORD(string); FAIL_ON_ERROR(_yr_scan_match_callback( data + offset, 0, flags, &callback_args)); return ERROR_SUCCESS; } int yr_scan_verify_match( YR_SCAN_CONTEXT* context, YR_AC_MATCH* ac_match, uint8_t* data, size_t data_size, size_t data_base, size_t offset) { YR_STRING* string = ac_match->string; #ifdef PROFILING_ENABLED clock_t start = clock(); #endif if (data_size - offset <= 0) return ERROR_SUCCESS; if (context->flags & SCAN_FLAGS_FAST_MODE && STRING_IS_SINGLE_MATCH(string) && string->matches[context->tidx].head != NULL) return ERROR_SUCCESS; if (STRING_IS_FIXED_OFFSET(string) && string->fixed_offset != data_base + offset) return ERROR_SUCCESS; if (STRING_IS_LITERAL(string)) { FAIL_ON_ERROR(_yr_scan_verify_literal_match( context, ac_match, data, data_size, data_base, offset)); } else { FAIL_ON_ERROR(_yr_scan_verify_re_match( context, ac_match, data, data_size, data_base, offset)); } #ifdef PROFILING_ENABLED string->clock_ticks += clock() - start; #endif return ERROR_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/c/bad_3328_3
crossvul-cpp_data_good_457_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2018 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // open_utils.c // This module provides all the code required to open an existing WavPack file // for reading by using a reader callback mechanism (NOT a filename). This // includes the code required to find and parse WavPack blocks, process any // included metadata, and queue up the bitstreams containing the encoded audio // data. It does not the actual code to unpack audio data and this was done so // that programs that just want to query WavPack files for information (like, // for example, taggers) don't need to link in a lot of unnecessary code. #include <stdlib.h> #include <string.h> #include "wavpack_local.h" // This function is identical to WavpackOpenFileInput() except that instead // of providing a filename to open, the caller provides a pointer to a set of // reader callbacks and instances of up to two streams. The first of these // streams is required and contains the regular WavPack data stream; the second // contains the "correction" file if desired. Unlike the standard open // function which handles the correction file transparently, in this case it // is the responsibility of the caller to be aware of correction files. static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper); WavpackContext *WavpackOpenFileInputEx64 (WavpackStreamReader64 *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset) { WavpackContext *wpc = (WavpackContext *)malloc (sizeof (WavpackContext)); WavpackStream *wps; int num_blocks = 0; unsigned char first_byte; uint32_t bcount; if (!wpc) { if (error) strcpy (error, "can't allocate memory"); return NULL; } CLEAR (*wpc); wpc->wv_in = wv_id; wpc->wvc_in = wvc_id; wpc->reader = reader; wpc->total_samples = -1; wpc->norm_offset = norm_offset; wpc->max_streams = OLD_MAX_STREAMS; // use this until overwritten with actual number wpc->open_flags = flags; wpc->filelen = wpc->reader->get_length (wpc->wv_in); #ifndef NO_TAGS if ((flags & (OPEN_TAGS | OPEN_EDIT_TAGS)) && wpc->reader->can_seek (wpc->wv_in)) { load_tag (wpc); wpc->reader->set_pos_abs (wpc->wv_in, 0); if ((flags & OPEN_EDIT_TAGS) && !editable_tag (&wpc->m_tag)) { if (error) strcpy (error, "can't edit tags located at the beginning of files!"); return WavpackCloseFile (wpc); } } #endif if (wpc->reader->read_bytes (wpc->wv_in, &first_byte, 1) != 1) { if (error) strcpy (error, "can't read all of WavPack file!"); return WavpackCloseFile (wpc); } wpc->reader->push_back_byte (wpc->wv_in, first_byte); if (first_byte == 'R') { #ifdef ENABLE_LEGACY return open_file3 (wpc, error); #else if (error) strcpy (error, "this legacy WavPack file is deprecated, use version 4.80.0 to transcode"); return WavpackCloseFile (wpc); #endif } wpc->streams = (WavpackStream **)(malloc ((wpc->num_streams = 1) * sizeof (wpc->streams [0]))); if (!wpc->streams) { if (error) strcpy (error, "can't allocate memory"); return WavpackCloseFile (wpc); } wpc->streams [0] = wps = (WavpackStream *)malloc (sizeof (WavpackStream)); if (!wps) { if (error) strcpy (error, "can't allocate memory"); return WavpackCloseFile (wpc); } CLEAR (*wps); while (!wps->wphdr.block_samples) { wpc->filepos = wpc->reader->get_pos (wpc->wv_in); bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr); if (bcount == (uint32_t) -1 || (!wps->wphdr.block_samples && num_blocks++ > 16)) { if (error) strcpy (error, "not compatible with this version of WavPack file!"); return WavpackCloseFile (wpc); } wpc->filepos += bcount; wps->blockbuff = (unsigned char *)malloc (wps->wphdr.ckSize + 8); if (!wps->blockbuff) { if (error) strcpy (error, "can't allocate memory"); return WavpackCloseFile (wpc); } memcpy (wps->blockbuff, &wps->wphdr, 32); if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != wps->wphdr.ckSize - 24) { if (error) strcpy (error, "can't read all of WavPack file!"); return WavpackCloseFile (wpc); } // if block does not verify, flag error, free buffer, and continue if (!WavpackVerifySingleBlock (wps->blockbuff, !(flags & OPEN_NO_CHECKSUM))) { wps->wphdr.block_samples = 0; free (wps->blockbuff); wps->blockbuff = NULL; wpc->crc_errors++; continue; } wps->init_done = FALSE; if (wps->wphdr.block_samples) { if (flags & OPEN_STREAMING) SET_BLOCK_INDEX (wps->wphdr, 0); else if (wpc->total_samples == -1) { if (GET_BLOCK_INDEX (wps->wphdr) || GET_TOTAL_SAMPLES (wps->wphdr) == -1) { wpc->initial_index = GET_BLOCK_INDEX (wps->wphdr); SET_BLOCK_INDEX (wps->wphdr, 0); if (wpc->reader->can_seek (wpc->wv_in)) { int64_t final_index = -1; seek_eof_information (wpc, &final_index, FALSE); if (final_index != -1) wpc->total_samples = final_index - wpc->initial_index; } } else wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr); } } else if (wpc->total_samples == -1 && !GET_BLOCK_INDEX (wps->wphdr) && GET_TOTAL_SAMPLES (wps->wphdr)) wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr); if (wpc->wvc_in && wps->wphdr.block_samples && (wps->wphdr.flags & HYBRID_FLAG)) { unsigned char ch; if (wpc->reader->read_bytes (wpc->wvc_in, &ch, 1) == 1) { wpc->reader->push_back_byte (wpc->wvc_in, ch); wpc->file2len = wpc->reader->get_length (wpc->wvc_in); wpc->wvc_flag = TRUE; } } if (wpc->wvc_flag && !read_wvc_block (wpc)) { if (error) strcpy (error, "not compatible with this version of correction file!"); return WavpackCloseFile (wpc); } if (!wps->init_done && !unpack_init (wpc)) { if (error) strcpy (error, wpc->error_message [0] ? wpc->error_message : "not compatible with this version of WavPack file!"); return WavpackCloseFile (wpc); } wps->init_done = TRUE; } wpc->config.flags &= ~0xff; wpc->config.flags |= wps->wphdr.flags & 0xff; if (!wpc->config.num_channels) { wpc->config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; wpc->config.channel_mask = 0x5 - wpc->config.num_channels; } if ((flags & OPEN_2CH_MAX) && !(wps->wphdr.flags & FINAL_BLOCK)) wpc->reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; if (wps->wphdr.flags & DSD_FLAG) { #ifdef ENABLE_DSD if (flags & OPEN_DSD_NATIVE) { wpc->config.bytes_per_sample = 1; wpc->config.bits_per_sample = 8; } else if (flags & OPEN_DSD_AS_PCM) { wpc->decimation_context = decimate_dsd_init (wpc->reduced_channels ? wpc->reduced_channels : wpc->config.num_channels); wpc->config.bytes_per_sample = 3; wpc->config.bits_per_sample = 24; } else { if (error) strcpy (error, "not configured to handle DSD WavPack files!"); return WavpackCloseFile (wpc); } #else if (error) strcpy (error, "not configured to handle DSD WavPack files!"); return WavpackCloseFile (wpc); #endif } else { wpc->config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1; wpc->config.float_norm_exp = wps->float_norm_exp; wpc->config.bits_per_sample = (wpc->config.bytes_per_sample * 8) - ((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB); } if (!wpc->config.sample_rate) { if (!wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK) wpc->config.sample_rate = 44100; else wpc->config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB]; } return wpc; } // This function returns the major version number of the WavPack program // (or library) that created the open file. Currently, this can be 1 to 5. // Minor versions are not recorded in WavPack files. int WavpackGetVersion (WavpackContext *wpc) { if (wpc) { #ifdef ENABLE_LEGACY if (wpc->stream3) return get_version3 (wpc); #endif return wpc->version_five ? 5 : 4; } return 0; } // Return the file format specified in the call to WavpackSetFileInformation() // when the file was created. For all files created prior to WavPack 5.0 this // will 0 (WP_FORMAT_WAV). unsigned char WavpackGetFileFormat (WavpackContext *wpc) { return wpc->file_format; } // Return a string representing the recommended file extension for the open // WavPack file. For all files created prior to WavPack 5.0 this will be "wav", // even for raw files with no RIFF into. This string is specified in the // call to WavpackSetFileInformation() when the file was created. char *WavpackGetFileExtension (WavpackContext *wpc) { if (wpc && wpc->file_extension [0]) return wpc->file_extension; else return "wav"; } // This function initializes everything required to unpack a WavPack block // and must be called before unpack_samples() is called to obtain audio data. // It is assumed that the WavpackHeader has been read into the wps->wphdr // (in the current WavpackStream) and that the entire block has been read at // wps->blockbuff. If a correction file is available (wpc->wvc_flag = TRUE) // then the corresponding correction block must be read into wps->block2buff // and its WavpackHeader has overwritten the header at wps->wphdr. This is // where all the metadata blocks are scanned including those that contain // bitstream data. static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr); static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd); static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end); int unpack_init (WavpackContext *wpc) { WavpackStream *wps = wpc->streams [wpc->current_stream]; unsigned char *blockptr, *block2ptr; WavpackMetadata wpmd; wps->num_terms = 0; wps->mute_error = FALSE; wps->crc = wps->crc_x = 0xffffffff; wps->dsd.ready = 0; CLEAR (wps->wvbits); CLEAR (wps->wvcbits); CLEAR (wps->wvxbits); CLEAR (wps->decorr_passes); CLEAR (wps->dc); CLEAR (wps->w); if (!(wps->wphdr.flags & MONO_FLAG) && wpc->config.num_channels && wps->wphdr.block_samples && (wpc->reduced_channels == 1 || wpc->config.num_channels == 1)) { wps->mute_error = TRUE; return FALSE; } if ((wps->wphdr.flags & UNKNOWN_FLAGS) || (wps->wphdr.flags & MONO_DATA) == MONO_DATA) { wps->mute_error = TRUE; return FALSE; } blockptr = wps->blockbuff + sizeof (WavpackHeader); while (read_metadata_buff (&wpmd, wps->blockbuff, &blockptr)) if (!process_metadata (wpc, &wpmd)) { wps->mute_error = TRUE; return FALSE; } if (wps->wphdr.block_samples && wpc->wvc_flag && wps->block2buff) { block2ptr = wps->block2buff + sizeof (WavpackHeader); while (read_metadata_buff (&wpmd, wps->block2buff, &block2ptr)) if (!process_metadata (wpc, &wpmd)) { wps->mute_error = TRUE; return FALSE; } } if (wps->wphdr.block_samples && ((wps->wphdr.flags & DSD_FLAG) ? !wps->dsd.ready : !bs_is_open (&wps->wvbits))) { if (bs_is_open (&wps->wvcbits)) strcpy (wpc->error_message, "can't unpack correction files alone!"); wps->mute_error = TRUE; return FALSE; } if (wps->wphdr.block_samples && !bs_is_open (&wps->wvxbits)) { if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits) wpc->lossy_blocks = TRUE; if ((wps->wphdr.flags & FLOAT_DATA) && wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME)) wpc->lossy_blocks = TRUE; } if (wps->wphdr.block_samples) wps->sample_index = GET_BLOCK_INDEX (wps->wphdr); return TRUE; } //////////////////////////////// matadata handlers /////////////////////////////// // These functions handle specific metadata types and are called directly // during WavPack block parsing by process_metadata() at the bottom. // This function initializes the main bitstream for audio samples, which must // be in the "wv" file. static int init_wv_bitstream (WavpackStream *wps, WavpackMetadata *wpmd) { if (!wpmd->byte_length || (wpmd->byte_length & 1)) return FALSE; bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length); return TRUE; } // This function initializes the "correction" bitstream for audio samples, // which currently must be in the "wvc" file. static int init_wvc_bitstream (WavpackStream *wps, WavpackMetadata *wpmd) { if (!wpmd->byte_length || (wpmd->byte_length & 1)) return FALSE; bs_open_read (&wps->wvcbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length); return TRUE; } // This function initializes the "extra" bitstream for audio samples which // contains the information required to losslessly decompress 32-bit float data // or integer data that exceeds 24 bits. This bitstream is in the "wv" file // for pure lossless data or the "wvc" file for hybrid lossless. This data // would not be used for hybrid lossy mode. There is also a 32-bit CRC stored // in the first 4 bytes of these blocks. static int init_wvx_bitstream (WavpackStream *wps, WavpackMetadata *wpmd) { unsigned char *cp = (unsigned char *)wpmd->data; if (wpmd->byte_length <= 4 || (wpmd->byte_length & 1)) return FALSE; wps->crc_wvx = *cp++; wps->crc_wvx |= (int32_t) *cp++ << 8; wps->crc_wvx |= (int32_t) *cp++ << 16; wps->crc_wvx |= (int32_t) *cp++ << 24; bs_open_read (&wps->wvxbits, cp, (unsigned char *) wpmd->data + wpmd->byte_length); return TRUE; } // Read the int32 data from the specified metadata into the specified stream. // This data is used for integer data that has more than 24 bits of magnitude // or, in some cases, used to eliminate redundant bits from any audio stream. static int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; char *byteptr = (char *)wpmd->data; if (bytecnt != 4) return FALSE; wps->int32_sent_bits = *byteptr++; wps->int32_zeros = *byteptr++; wps->int32_ones = *byteptr++; wps->int32_dups = *byteptr; return TRUE; } static int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; char *byteptr = (char *)wpmd->data; if (bytecnt != 4) return FALSE; wps->float_flags = *byteptr++; wps->float_shift = *byteptr++; wps->float_max_exp = *byteptr++; wps->float_norm_exp = *byteptr; return TRUE; } // Read multichannel information from metadata. The first byte is the total // number of channels and the following bytes represent the channel_mask // as described for Microsoft WAVEFORMATEX. static int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length, shift = 0, mask_bits; unsigned char *byteptr = (unsigned char *)wpmd->data; uint32_t mask = 0; if (!bytecnt || bytecnt > 7) return FALSE; if (!wpc->config.num_channels) { // if bytecnt is 6 or 7 we are using new configuration with "unlimited" streams if (bytecnt >= 6) { wpc->config.num_channels = (byteptr [0] | ((byteptr [2] & 0xf) << 8)) + 1; wpc->max_streams = (byteptr [1] | ((byteptr [2] & 0xf0) << 4)) + 1; if (wpc->config.num_channels < wpc->max_streams) return FALSE; byteptr += 3; mask = *byteptr++; mask |= (uint32_t) *byteptr++ << 8; mask |= (uint32_t) *byteptr++ << 16; if (bytecnt == 7) // this was introduced in 5.0 mask |= (uint32_t) *byteptr << 24; } else { wpc->config.num_channels = *byteptr++; while (--bytecnt) { mask |= (uint32_t) *byteptr++ << shift; shift += 8; } } if (wpc->config.num_channels > wpc->max_streams * 2) return FALSE; wpc->config.channel_mask = mask; for (mask_bits = 0; mask; mask >>= 1) if ((mask & 1) && ++mask_bits > wpc->config.num_channels) return FALSE; } return TRUE; } // Read multichannel identity information from metadata. Data is an array of // unsigned characters representing any channels in the file that DO NOT // match one the 18 Microsoft standard channels (and are represented in the // channel mask). A value of 0 is not allowed and 0xff means an unknown or // undefined channel identity. static int read_channel_identities (WavpackContext *wpc, WavpackMetadata *wpmd) { if (!wpc->channel_identities) { wpc->channel_identities = (unsigned char *)malloc (wpmd->byte_length + 1); memcpy (wpc->channel_identities, wpmd->data, wpmd->byte_length); wpc->channel_identities [wpmd->byte_length] = 0; } return TRUE; } // Read configuration information from metadata. static int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = (unsigned char *)wpmd->data; if (bytecnt >= 3) { wpc->config.flags &= 0xff; wpc->config.flags |= (int32_t) *byteptr++ << 8; wpc->config.flags |= (int32_t) *byteptr++ << 16; wpc->config.flags |= (int32_t) *byteptr++ << 24; bytecnt -= 3; if (bytecnt && (wpc->config.flags & CONFIG_EXTRA_MODE)) { wpc->config.xmode = *byteptr++; bytecnt--; } // we used an extra config byte here for the 5.0.0 alpha, so still // honor it now (but this has been replaced with NEW_CONFIG) if (bytecnt) { wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr; wpc->version_five = 1; } } return TRUE; } // Read "new" configuration information from metadata. static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = (unsigned char *)wpmd->data; wpc->version_five = 1; // just having this block signals version 5.0 wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0; if (wpc->channel_reordering) { free (wpc->channel_reordering); wpc->channel_reordering = NULL; } // if there's any data, the first two bytes are file_format and qmode flags if (bytecnt >= 2) { wpc->file_format = *byteptr++; wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++; bytecnt -= 2; // another byte indicates a channel layout if (bytecnt) { int nchans, i; wpc->channel_layout = (int32_t) *byteptr++ << 16; bytecnt--; // another byte means we have a channel count for the layout and maybe a reordering if (bytecnt) { wpc->channel_layout += nchans = *byteptr++; bytecnt--; // any more means there's a reordering string if (bytecnt) { if (bytecnt > nchans) return FALSE; wpc->channel_reordering = (unsigned char *)malloc (nchans); // note that redundant reordering info is not stored, so we fill in the rest if (wpc->channel_reordering) { for (i = 0; i < nchans; ++i) if (bytecnt) { wpc->channel_reordering [i] = *byteptr++; if (wpc->channel_reordering [i] >= nchans) // make sure index is in range wpc->channel_reordering [i] = 0; bytecnt--; } else wpc->channel_reordering [i] = i; } } } else wpc->channel_layout += wpc->config.num_channels; } } return TRUE; } // Read non-standard sampling rate from metadata. static int read_sample_rate (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = (unsigned char *)wpmd->data; if (bytecnt == 3 || bytecnt == 4) { wpc->config.sample_rate = (int32_t) *byteptr++; wpc->config.sample_rate |= (int32_t) *byteptr++ << 8; wpc->config.sample_rate |= (int32_t) *byteptr++ << 16; // for sampling rates > 16777215 (non-audio probably, or ...) if (bytecnt == 4) wpc->config.sample_rate |= (int32_t) (*byteptr & 0x7f) << 24; } return TRUE; } // Read wrapper data from metadata. Currently, this consists of the RIFF // header and trailer that wav files contain around the audio data but could // be used for other formats as well. Because WavPack files contain all the // information required for decoding and playback, this data can probably // be ignored except when an exact wavefile restoration is needed. static int read_wrapper_data (WavpackContext *wpc, WavpackMetadata *wpmd) { if ((wpc->open_flags & OPEN_WRAPPER) && wpc->wrapper_bytes < MAX_WRAPPER_BYTES && wpmd->byte_length) { wpc->wrapper_data = (unsigned char *)realloc (wpc->wrapper_data, wpc->wrapper_bytes + wpmd->byte_length); if (!wpc->wrapper_data) return FALSE; memcpy (wpc->wrapper_data + wpc->wrapper_bytes, wpmd->data, wpmd->byte_length); wpc->wrapper_bytes += wpmd->byte_length; } return TRUE; } static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr) { WavpackHeader *wphdr = (WavpackHeader *) blockbuff; unsigned char *buffend = blockbuff + wphdr->ckSize + 8; if (buffend - *buffptr < 2) return FALSE; wpmd->id = *(*buffptr)++; wpmd->byte_length = *(*buffptr)++ << 1; if (wpmd->id & ID_LARGE) { wpmd->id &= ~ID_LARGE; if (buffend - *buffptr < 2) return FALSE; wpmd->byte_length += *(*buffptr)++ << 9; wpmd->byte_length += *(*buffptr)++ << 17; } if (wpmd->id & ID_ODD_SIZE) { if (!wpmd->byte_length) // odd size and zero length makes no sense return FALSE; wpmd->id &= ~ID_ODD_SIZE; wpmd->byte_length--; } if (wpmd->byte_length) { if (buffend - *buffptr < wpmd->byte_length + (wpmd->byte_length & 1)) { wpmd->data = NULL; return FALSE; } wpmd->data = *buffptr; (*buffptr) += wpmd->byte_length + (wpmd->byte_length & 1); } else wpmd->data = NULL; return TRUE; } static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd) { WavpackStream *wps = wpc->streams [wpc->current_stream]; switch (wpmd->id) { case ID_DUMMY: return TRUE; case ID_DECORR_TERMS: return read_decorr_terms (wps, wpmd); case ID_DECORR_WEIGHTS: return read_decorr_weights (wps, wpmd); case ID_DECORR_SAMPLES: return read_decorr_samples (wps, wpmd); case ID_ENTROPY_VARS: return read_entropy_vars (wps, wpmd); case ID_HYBRID_PROFILE: return read_hybrid_profile (wps, wpmd); case ID_SHAPING_WEIGHTS: return read_shaping_info (wps, wpmd); case ID_FLOAT_INFO: return read_float_info (wps, wpmd); case ID_INT32_INFO: return read_int32_info (wps, wpmd); case ID_CHANNEL_INFO: return read_channel_info (wpc, wpmd); case ID_CHANNEL_IDENTITIES: return read_channel_identities (wpc, wpmd); case ID_CONFIG_BLOCK: return read_config_info (wpc, wpmd); case ID_NEW_CONFIG_BLOCK: return read_new_config_info (wpc, wpmd); case ID_SAMPLE_RATE: return read_sample_rate (wpc, wpmd); case ID_WV_BITSTREAM: return init_wv_bitstream (wps, wpmd); case ID_WVC_BITSTREAM: return init_wvc_bitstream (wps, wpmd); case ID_WVX_BITSTREAM: return init_wvx_bitstream (wps, wpmd); case ID_DSD_BLOCK: #ifdef ENABLE_DSD return init_dsd_block (wpc, wpmd); #else strcpy (wpc->error_message, "not configured to handle DSD WavPack files!"); return FALSE; #endif case ID_ALT_HEADER: case ID_ALT_TRAILER: if (!(wpc->open_flags & OPEN_ALT_TYPES)) return TRUE; case ID_RIFF_HEADER: case ID_RIFF_TRAILER: return read_wrapper_data (wpc, wpmd); case ID_ALT_MD5_CHECKSUM: if (!(wpc->open_flags & OPEN_ALT_TYPES)) return TRUE; case ID_MD5_CHECKSUM: if (wpmd->byte_length == 16) { memcpy (wpc->config.md5_checksum, wpmd->data, 16); wpc->config.flags |= CONFIG_MD5_CHECKSUM; wpc->config.md5_read = 1; } return TRUE; case ID_ALT_EXTENSION: if (wpmd->byte_length && wpmd->byte_length < sizeof (wpc->file_extension)) { memcpy (wpc->file_extension, wpmd->data, wpmd->byte_length); wpc->file_extension [wpmd->byte_length] = 0; } return TRUE; // we don't actually verify the checksum here (it's done right after the // block is read), but it's a good indicator of version 5 files case ID_BLOCK_CHECKSUM: wpc->version_five = 1; return TRUE; default: return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE; } } //////////////////////////////// bitstream management /////////////////////////////// // Open the specified BitStream and associate with the specified buffer. static void bs_read (Bitstream *bs); static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end) { bs->error = bs->sr = bs->bc = 0; bs->ptr = ((bs->buf = (uint16_t *)buffer_start) - 1); bs->end = (uint16_t *)buffer_end; bs->wrap = bs_read; } // This function is only called from the getbit() and getbits() macros when // the BitStream has been exhausted and more data is required. Sinve these // bistreams no longer access files, this function simple sets an error and // resets the buffer. static void bs_read (Bitstream *bs) { bs->ptr = bs->buf; bs->error = 1; } // This function is called to close the bitstream. It returns the number of // full bytes actually read as bits. uint32_t bs_close_read (Bitstream *bs) { uint32_t bytes_read; if (bs->bc < sizeof (*(bs->ptr)) * 8) bs->ptr++; bytes_read = (uint32_t)(bs->ptr - bs->buf) * sizeof (*(bs->ptr)); if (!(bytes_read & 1)) ++bytes_read; CLEAR (*bs); return bytes_read; } // Normally the trailing wrapper will not be available when a WavPack file is first // opened for reading because it is stored in the final block of the file. This // function forces a seek to the end of the file to pick up any trailing wrapper // stored there (then use WavPackGetWrapper**() to obtain). This can obviously only // be used for seekable files (not pipes) and is not available for pre-4.0 WavPack // files. void WavpackSeekTrailingWrapper (WavpackContext *wpc) { if ((wpc->open_flags & OPEN_WRAPPER) && wpc->reader->can_seek (wpc->wv_in) && !wpc->stream3) seek_eof_information (wpc, NULL, TRUE); } // Get any MD5 checksum stored in the metadata (should be called after reading // last sample or an extra seek will occur). A return value of FALSE indicates // that no MD5 checksum was stored. int WavpackGetMD5Sum (WavpackContext *wpc, unsigned char data [16]) { if (wpc->config.flags & CONFIG_MD5_CHECKSUM) { if (!wpc->config.md5_read && wpc->reader->can_seek (wpc->wv_in)) seek_eof_information (wpc, NULL, FALSE); if (wpc->config.md5_read) { memcpy (data, wpc->config.md5_checksum, 16); return TRUE; } } return FALSE; } // Read from current file position until a valid 32-byte WavPack 4.0 header is // found and read into the specified pointer. The number of bytes skipped is // returned. If no WavPack header is found within 1 meg, then a -1 is returned // to indicate the error. No additional bytes are read past the header and it // is returned in the processor's native endian mode. Seeking is not required. uint32_t read_next_header (WavpackStreamReader64 *reader, void *id, WavpackHeader *wphdr) { unsigned char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp; uint32_t bytes_skipped = 0; int bleft; while (1) { if (sp < ep) { bleft = (int)(ep - sp); memmove (buffer, sp, bleft); } else bleft = 0; if (reader->read_bytes (id, buffer + bleft, sizeof (*wphdr) - bleft) != sizeof (*wphdr) - bleft) return -1; sp = buffer; if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' && !(*++sp & 1) && sp [2] < 16 && !sp [3] && (sp [2] || sp [1] || *sp >= 24) && sp [5] == 4 && sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff) && sp [18] < 3 && !sp [19]) { memcpy (wphdr, buffer, sizeof (*wphdr)); WavpackLittleEndianToNative (wphdr, WavpackHeaderFormat); return bytes_skipped; } while (sp < ep && *sp != 'w') sp++; if ((bytes_skipped += (uint32_t)(sp - buffer)) > 1024 * 1024) return -1; } } // Compare the regular wv file block header to a potential matching wvc // file block header and return action code based on analysis: // // 0 = use wvc block (assuming rest of block is readable) // 1 = bad match; try to read next wvc block // -1 = bad match; ignore wvc file for this block and backup fp (if // possible) and try to use this block next time static int match_wvc_header (WavpackHeader *wv_hdr, WavpackHeader *wvc_hdr) { if (GET_BLOCK_INDEX (*wv_hdr) == GET_BLOCK_INDEX (*wvc_hdr) && wv_hdr->block_samples == wvc_hdr->block_samples) { int wvi = 0, wvci = 0; if (wv_hdr->flags == wvc_hdr->flags) return 0; if (wv_hdr->flags & INITIAL_BLOCK) wvi -= 1; if (wv_hdr->flags & FINAL_BLOCK) wvi += 1; if (wvc_hdr->flags & INITIAL_BLOCK) wvci -= 1; if (wvc_hdr->flags & FINAL_BLOCK) wvci += 1; return (wvci - wvi < 0) ? 1 : -1; } if (((GET_BLOCK_INDEX (*wvc_hdr) - GET_BLOCK_INDEX (*wv_hdr)) << 24) < 0) return 1; else return -1; } // Read the wvc block that matches the regular wv block that has been // read for the current stream. If an exact match is not found then // we either keep reading or back up and (possibly) use the block // later. The skip_wvc flag is set if not matching wvc block is found // so that we can still decode using only the lossy version (although // we flag this as an error). A return of FALSE indicates a serious // error (not just that we missed one wvc block). int read_wvc_block (WavpackContext *wpc) { WavpackStream *wps = wpc->streams [wpc->current_stream]; int64_t bcount, file2pos; WavpackHeader orig_wphdr; WavpackHeader wphdr; int compare_result; while (1) { file2pos = wpc->reader->get_pos (wpc->wvc_in); bcount = read_next_header (wpc->reader, wpc->wvc_in, &wphdr); if (bcount == (uint32_t) -1) { wps->wvc_skip = TRUE; wpc->crc_errors++; return FALSE; } memcpy (&orig_wphdr, &wphdr, 32); // save original header for verify step if (wpc->open_flags & OPEN_STREAMING) SET_BLOCK_INDEX (wphdr, wps->sample_index = 0); else SET_BLOCK_INDEX (wphdr, GET_BLOCK_INDEX (wphdr) - wpc->initial_index); if (wphdr.flags & INITIAL_BLOCK) wpc->file2pos = file2pos + bcount; compare_result = match_wvc_header (&wps->wphdr, &wphdr); if (!compare_result) { wps->block2buff = (unsigned char *)malloc (wphdr.ckSize + 8); if (!wps->block2buff) return FALSE; if (wpc->reader->read_bytes (wpc->wvc_in, wps->block2buff + 32, wphdr.ckSize - 24) != wphdr.ckSize - 24) { free (wps->block2buff); wps->block2buff = NULL; wps->wvc_skip = TRUE; wpc->crc_errors++; return FALSE; } memcpy (wps->block2buff, &orig_wphdr, 32); // don't use corrupt blocks if (!WavpackVerifySingleBlock (wps->block2buff, !(wpc->open_flags & OPEN_NO_CHECKSUM))) { free (wps->block2buff); wps->block2buff = NULL; wps->wvc_skip = TRUE; wpc->crc_errors++; return TRUE; } wps->wvc_skip = FALSE; memcpy (wps->block2buff, &wphdr, 32); memcpy (&wps->wphdr, &wphdr, 32); return TRUE; } else if (compare_result == -1) { wps->wvc_skip = TRUE; wpc->reader->set_pos_rel (wpc->wvc_in, -32, SEEK_CUR); wpc->crc_errors++; return TRUE; } } } // This function is used to seek to end of a file to obtain certain information // that is stored there at the file creation time because it is not known at // the start. This includes the MD5 sum and and trailing part of the file // wrapper, and in some rare cases may include the total number of samples in // the file (although we usually try to back up and write that at the front of // the file). Note this function restores the file position to its original // location (and obviously requires a seekable file). The normal return value // is TRUE indicating no errors, although this does not actually mean that any // information was retrieved. An error return of FALSE usually means the file // terminated unexpectedly. Note that this could be used to get all three // types of information in one go, but it's not actually used that way now. static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper) { int64_t restore_pos, last_pos = -1; WavpackStreamReader64 *reader = wpc->reader; int alt_types = wpc->open_flags & OPEN_ALT_TYPES; uint32_t blocks = 0, audio_blocks = 0; void *id = wpc->wv_in; WavpackHeader wphdr; restore_pos = reader->get_pos (id); // we restore file position when done // start 1MB from the end-of-file, or from the start if the file is not that big if (reader->get_length (id) > (int64_t) 1048576) reader->set_pos_rel (id, -1048576, SEEK_END); else reader->set_pos_abs (id, 0); // Note that we go backward (without parsing inside blocks) until we find a block // with audio (careful to not get stuck in a loop). Only then do we go forward // parsing all blocks in their entirety. while (1) { uint32_t bcount = read_next_header (reader, id, &wphdr); int64_t current_pos = reader->get_pos (id); // if we just got to the same place as last time, we're stuck and need to give up if (current_pos == last_pos) { reader->set_pos_abs (id, restore_pos); return FALSE; } last_pos = current_pos; // We enter here if we just read 1 MB without seeing any WavPack block headers. // Since WavPack blocks are < 1 MB, that means we're in a big APE tag, or we got // to the end-of-file. if (bcount == (uint32_t) -1) { // if we have not seen any blocks at all yet, back up almost 2 MB (or to the // beginning of the file) and try again if (!blocks) { if (current_pos > (int64_t) 2000000) reader->set_pos_rel (id, -2000000, SEEK_CUR); else reader->set_pos_abs (id, 0); continue; } // if we have seen WavPack blocks, then this means we've done all we can do here reader->set_pos_abs (id, restore_pos); return TRUE; } blocks++; // If the block has audio samples, calculate a final index, although this is not // final since this may not be the last block with audio. On the other hand, if // this block does not have audio, and we haven't seen one with audio, we have // to go back some more. if (wphdr.block_samples) { if (final_index) *final_index = GET_BLOCK_INDEX (wphdr) + wphdr.block_samples; audio_blocks++; } else if (!audio_blocks) { if (current_pos > (int64_t) 1048576) reader->set_pos_rel (id, -1048576, SEEK_CUR); else reader->set_pos_abs (id, 0); continue; } // at this point we have seen at least one block with audio, so we parse the // entire block looking for MD5 metadata or (conditionally) trailing wrappers bcount = wphdr.ckSize - sizeof (WavpackHeader) + 8; while (bcount >= 2) { unsigned char meta_id, c1, c2; uint32_t meta_bc, meta_size; if (reader->read_bytes (id, &meta_id, 1) != 1 || reader->read_bytes (id, &c1, 1) != 1) { reader->set_pos_abs (id, restore_pos); return FALSE; } meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2 || reader->read_bytes (id, &c1, 1) != 1 || reader->read_bytes (id, &c2, 1) != 1) { reader->set_pos_abs (id, restore_pos); return FALSE; } meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } meta_size = (meta_id & ID_ODD_SIZE) ? meta_bc - 1 : meta_bc; meta_id &= ID_UNIQUE; if (get_wrapper && (meta_id == ID_RIFF_TRAILER || (alt_types && meta_id == ID_ALT_TRAILER)) && meta_bc) { wpc->wrapper_data = (unsigned char *)realloc (wpc->wrapper_data, wpc->wrapper_bytes + meta_bc); if (!wpc->wrapper_data) { reader->set_pos_abs (id, restore_pos); return FALSE; } if (reader->read_bytes (id, wpc->wrapper_data + wpc->wrapper_bytes, meta_bc) == meta_bc) wpc->wrapper_bytes += meta_size; else { reader->set_pos_abs (id, restore_pos); return FALSE; } } else if (meta_id == ID_MD5_CHECKSUM || (alt_types && meta_id == ID_ALT_MD5_CHECKSUM)) { if (meta_bc == 16 && bcount >= 16) { if (reader->read_bytes (id, wpc->config.md5_checksum, 16) == 16) wpc->config.md5_read = TRUE; else { reader->set_pos_abs (id, restore_pos); return FALSE; } } else reader->set_pos_rel (id, meta_bc, SEEK_CUR); } else reader->set_pos_rel (id, meta_bc, SEEK_CUR); bcount -= meta_bc; } } } // Quickly verify the referenced block. It is assumed that the WavPack header has been converted // to native endian format. If a block checksum is performed, that is done in little-endian // (file) format. It is also assumed that the caller has made sure that the block length // indicated in the header is correct (we won't overflow the buffer). If a checksum is present, // then it is checked, otherwise we just check that all the metadata blocks are formatted // correctly (without looking at their contents). Returns FALSE for bad block. int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); }
./CrossVul/dataset_final_sorted/CWE-125/c/good_457_0
crossvul-cpp_data_good_2713_0
/* * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* \summary: IP printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <string.h> #include "netdissect.h" #include "addrtoname.h" #include "extract.h" #include "ip.h" #include "ipproto.h" static const char tstr[] = "[|ip]"; static const struct tok ip_option_values[] = { { IPOPT_EOL, "EOL" }, { IPOPT_NOP, "NOP" }, { IPOPT_TS, "timestamp" }, { IPOPT_SECURITY, "security" }, { IPOPT_RR, "RR" }, { IPOPT_SSRR, "SSRR" }, { IPOPT_LSRR, "LSRR" }, { IPOPT_RA, "RA" }, { IPOPT_RFC1393, "traceroute" }, { 0, NULL } }; /* * print the recorded route in an IP RR, LSRR or SSRR option. */ static int ip_printroute(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int ptr; register u_int len; if (length < 3) { ND_PRINT((ndo, " [bad length %u]", length)); return (0); } if ((length + 1) & 3) ND_PRINT((ndo, " [bad length %u]", length)); ND_TCHECK(cp[2]); ptr = cp[2] - 1; if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1) ND_PRINT((ndo, " [bad ptr %u]", cp[2])); for (len = 3; len < length; len += 4) { ND_TCHECK2(cp[len], 4); ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len]))); if (ptr > len) ND_PRINT((ndo, ",")); } return (0); trunc: return (-1); } /* * If source-routing is present and valid, return the final destination. * Otherwise, return IP destination. * * This is used for UDP and TCP pseudo-header in the checksum * calculation. */ static uint32_t ip_finddst(netdissect_options *ndo, const struct ip *ip) { int length; int len; const u_char *cp; uint32_t retval; cp = (const u_char *)(ip + 1); length = (IP_HL(ip) << 2) - sizeof(struct ip); for (; length > 0; cp += len, length -= len) { int tt; ND_TCHECK(*cp); tt = *cp; if (tt == IPOPT_EOL) break; else if (tt == IPOPT_NOP) len = 1; else { ND_TCHECK(cp[1]); len = cp[1]; if (len < 2) break; } ND_TCHECK2(*cp, len); switch (tt) { case IPOPT_SSRR: case IPOPT_LSRR: if (len < 7) break; UNALIGNED_MEMCPY(&retval, cp + len - 4, 4); return retval; } } trunc: UNALIGNED_MEMCPY(&retval, &ip->ip_dst, sizeof(uint32_t)); return retval; } /* * Compute a V4-style checksum by building a pseudoheader. */ int nextproto4_cksum(netdissect_options *ndo, const struct ip *ip, const uint8_t *data, u_int len, u_int covlen, u_int next_proto) { struct phdr { uint32_t src; uint32_t dst; u_char mbz; u_char proto; uint16_t len; } ph; struct cksum_vec vec[2]; /* pseudo-header.. */ ph.len = htons((uint16_t)len); ph.mbz = 0; ph.proto = next_proto; UNALIGNED_MEMCPY(&ph.src, &ip->ip_src, sizeof(uint32_t)); if (IP_HL(ip) == 5) UNALIGNED_MEMCPY(&ph.dst, &ip->ip_dst, sizeof(uint32_t)); else ph.dst = ip_finddst(ndo, ip); vec[0].ptr = (const uint8_t *)(void *)&ph; vec[0].len = sizeof(ph); vec[1].ptr = data; vec[1].len = covlen; return (in_cksum(vec, 2)); } static int ip_printts(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int ptr; register u_int len; int hoplen; const char *type; if (length < 4) { ND_PRINT((ndo, "[bad length %u]", length)); return (0); } ND_PRINT((ndo, " TS{")); hoplen = ((cp[3]&0xF) != IPOPT_TS_TSONLY) ? 8 : 4; if ((length - 4) & (hoplen-1)) ND_PRINT((ndo, "[bad length %u]", length)); ND_TCHECK(cp[2]); ptr = cp[2] - 1; len = 0; if (ptr < 4 || ((ptr - 4) & (hoplen-1)) || ptr > length + 1) ND_PRINT((ndo, "[bad ptr %u]", cp[2])); ND_TCHECK(cp[3]); switch (cp[3]&0xF) { case IPOPT_TS_TSONLY: ND_PRINT((ndo, "TSONLY")); break; case IPOPT_TS_TSANDADDR: ND_PRINT((ndo, "TS+ADDR")); break; /* * prespecified should really be 3, but some ones might send 2 * instead, and the IPOPT_TS_PRESPEC constant can apparently * have both values, so we have to hard-code it here. */ case 2: ND_PRINT((ndo, "PRESPEC2.0")); break; case 3: /* IPOPT_TS_PRESPEC */ ND_PRINT((ndo, "PRESPEC")); break; default: ND_PRINT((ndo, "[bad ts type %d]", cp[3]&0xF)); goto done; } type = " "; for (len = 4; len < length; len += hoplen) { if (ptr == len) type = " ^ "; ND_TCHECK2(cp[len], hoplen); ND_PRINT((ndo, "%s%d@%s", type, EXTRACT_32BITS(&cp[len+hoplen-4]), hoplen!=8 ? "" : ipaddr_string(ndo, &cp[len]))); type = " "; } done: ND_PRINT((ndo, "%s", ptr == len ? " ^ " : "")); if (cp[3]>>4) ND_PRINT((ndo, " [%d hops not recorded]} ", cp[3]>>4)); else ND_PRINT((ndo, "}")); return (0); trunc: return (-1); } /* * print IP options. */ static void ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: if (ip_printts(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); } #define IP_RES 0x8000 static const struct tok ip_frag_values[] = { { IP_MF, "+" }, { IP_DF, "DF" }, { IP_RES, "rsvd" }, /* The RFC3514 evil ;-) bit */ { 0, NULL } }; struct ip_print_demux_state { const struct ip *ip; const u_char *cp; u_int len, off; u_char nh; int advance; }; static void ip_print_demux(netdissect_options *ndo, struct ip_print_demux_state *ipds) { const char *p_name; again: switch (ipds->nh) { case IPPROTO_AH: if (!ND_TTEST(*ipds->cp)) { ND_PRINT((ndo, "[|AH]")); break; } ipds->nh = *ipds->cp; ipds->advance = ah_print(ndo, ipds->cp); if (ipds->advance <= 0) break; ipds->cp += ipds->advance; ipds->len -= ipds->advance; goto again; case IPPROTO_ESP: { int enh, padlen; ipds->advance = esp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip, &enh, &padlen); if (ipds->advance <= 0) break; ipds->cp += ipds->advance; ipds->len -= ipds->advance + padlen; ipds->nh = enh & 0xff; goto again; } case IPPROTO_IPCOMP: { ipcomp_print(ndo, ipds->cp); /* * Either this has decompressed the payload and * printed it, in which case there's nothing more * to do, or it hasn't, in which case there's * nothing more to do. */ break; } case IPPROTO_SCTP: sctp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len); break; case IPPROTO_DCCP: dccp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len); break; case IPPROTO_TCP: /* pass on the MF bit plus the offset to detect fragments */ tcp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip, ipds->off & (IP_MF|IP_OFFMASK)); break; case IPPROTO_UDP: /* pass on the MF bit plus the offset to detect fragments */ udp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip, ipds->off & (IP_MF|IP_OFFMASK)); break; case IPPROTO_ICMP: /* pass on the MF bit plus the offset to detect fragments */ icmp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip, ipds->off & (IP_MF|IP_OFFMASK)); break; case IPPROTO_PIGP: /* * XXX - the current IANA protocol number assignments * page lists 9 as "any private interior gateway * (used by Cisco for their IGRP)" and 88 as * "EIGRP" from Cisco. * * Recent BSD <netinet/in.h> headers define * IP_PROTO_PIGP as 9 and IP_PROTO_IGRP as 88. * We define IP_PROTO_PIGP as 9 and * IP_PROTO_EIGRP as 88; those names better * match was the current protocol number * assignments say. */ igrp_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_EIGRP: eigrp_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_ND: ND_PRINT((ndo, " nd %d", ipds->len)); break; case IPPROTO_EGP: egp_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_OSPF: ospf_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip); break; case IPPROTO_IGMP: igmp_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_IPV4: /* DVMRP multicast tunnel (ip-in-ip encapsulation) */ ip_print(ndo, ipds->cp, ipds->len); if (! ndo->ndo_vflag) { ND_PRINT((ndo, " (ipip-proto-4)")); return; } break; case IPPROTO_IPV6: /* ip6-in-ip encapsulation */ ip6_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_RSVP: rsvp_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_GRE: /* do it */ gre_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_MOBILE: mobile_print(ndo, ipds->cp, ipds->len); break; case IPPROTO_PIM: pim_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip); break; case IPPROTO_VRRP: if (ndo->ndo_packettype == PT_CARP) { if (ndo->ndo_vflag) ND_PRINT((ndo, "carp %s > %s: ", ipaddr_string(ndo, &ipds->ip->ip_src), ipaddr_string(ndo, &ipds->ip->ip_dst))); carp_print(ndo, ipds->cp, ipds->len, ipds->ip->ip_ttl); } else { if (ndo->ndo_vflag) ND_PRINT((ndo, "vrrp %s > %s: ", ipaddr_string(ndo, &ipds->ip->ip_src), ipaddr_string(ndo, &ipds->ip->ip_dst))); vrrp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip, ipds->ip->ip_ttl); } break; case IPPROTO_PGM: pgm_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip); break; default: if (ndo->ndo_nflag==0 && (p_name = netdb_protoname(ipds->nh)) != NULL) ND_PRINT((ndo, " %s", p_name)); else ND_PRINT((ndo, " ip-proto-%d", ipds->nh)); ND_PRINT((ndo, " %d", ipds->len)); break; } } void ip_print_inner(netdissect_options *ndo, const u_char *bp, u_int length, u_int nh, const u_char *bp2) { struct ip_print_demux_state ipd; ipd.ip = (const struct ip *)bp2; ipd.cp = bp; ipd.len = length; ipd.off = 0; ipd.nh = nh; ipd.advance = 0; ip_print_demux(ndo, &ipd); } /* * print an IP datagram. */ void ip_print(netdissect_options *ndo, const u_char *bp, u_int length) { struct ip_print_demux_state ipd; struct ip_print_demux_state *ipds=&ipd; const u_char *ipend; u_int hlen; struct cksum_vec vec[1]; uint16_t sum, ip_sum; const char *p_name; ipds->ip = (const struct ip *)bp; ND_TCHECK(ipds->ip->ip_vhl); if (IP_V(ipds->ip) != 4) { /* print version and fail if != 4 */ if (IP_V(ipds->ip) == 6) ND_PRINT((ndo, "IP6, wrong link-layer encapsulation ")); else ND_PRINT((ndo, "IP%u ", IP_V(ipds->ip))); return; } if (!ndo->ndo_eflag) ND_PRINT((ndo, "IP ")); ND_TCHECK(*ipds->ip); if (length < sizeof (struct ip)) { ND_PRINT((ndo, "truncated-ip %u", length)); return; } hlen = IP_HL(ipds->ip) * 4; if (hlen < sizeof (struct ip)) { ND_PRINT((ndo, "bad-hlen %u", hlen)); return; } ipds->len = EXTRACT_16BITS(&ipds->ip->ip_len); if (length < ipds->len) ND_PRINT((ndo, "truncated-ip - %u bytes missing! ", ipds->len - length)); if (ipds->len < hlen) { #ifdef GUESS_TSO if (ipds->len) { ND_PRINT((ndo, "bad-len %u", ipds->len)); return; } else { /* we guess that it is a TSO send */ ipds->len = length; } #else ND_PRINT((ndo, "bad-len %u", ipds->len)); return; #endif /* GUESS_TSO */ } /* * Cut off the snapshot length to the end of the IP payload. */ ipend = bp + ipds->len; if (ipend < ndo->ndo_snapend) ndo->ndo_snapend = ipend; ipds->len -= hlen; ipds->off = EXTRACT_16BITS(&ipds->ip->ip_off); if (ndo->ndo_vflag) { ND_PRINT((ndo, "(tos 0x%x", (int)ipds->ip->ip_tos)); /* ECN bits */ switch (ipds->ip->ip_tos & 0x03) { case 0: break; case 1: ND_PRINT((ndo, ",ECT(1)")); break; case 2: ND_PRINT((ndo, ",ECT(0)")); break; case 3: ND_PRINT((ndo, ",CE")); break; } if (ipds->ip->ip_ttl >= 1) ND_PRINT((ndo, ", ttl %u", ipds->ip->ip_ttl)); /* * for the firewall guys, print id, offset. * On all but the last stick a "+" in the flags portion. * For unfragmented datagrams, note the don't fragment flag. */ ND_PRINT((ndo, ", id %u, offset %u, flags [%s], proto %s (%u)", EXTRACT_16BITS(&ipds->ip->ip_id), (ipds->off & 0x1fff) * 8, bittok2str(ip_frag_values, "none", ipds->off&0xe000), tok2str(ipproto_values,"unknown",ipds->ip->ip_p), ipds->ip->ip_p)); ND_PRINT((ndo, ", length %u", EXTRACT_16BITS(&ipds->ip->ip_len))); if ((hlen - sizeof(struct ip)) > 0) { ND_PRINT((ndo, ", options (")); ip_optprint(ndo, (const u_char *)(ipds->ip + 1), hlen - sizeof(struct ip)); ND_PRINT((ndo, ")")); } if (!ndo->ndo_Kflag && (const u_char *)ipds->ip + hlen <= ndo->ndo_snapend) { vec[0].ptr = (const uint8_t *)(const void *)ipds->ip; vec[0].len = hlen; sum = in_cksum(vec, 1); if (sum != 0) { ip_sum = EXTRACT_16BITS(&ipds->ip->ip_sum); ND_PRINT((ndo, ", bad cksum %x (->%x)!", ip_sum, in_cksum_shouldbe(ip_sum, sum))); } } ND_PRINT((ndo, ")\n ")); } /* * If this is fragment zero, hand it to the next higher * level protocol. */ if ((ipds->off & 0x1fff) == 0) { ipds->cp = (const u_char *)ipds->ip + hlen; ipds->nh = ipds->ip->ip_p; if (ipds->nh != IPPROTO_TCP && ipds->nh != IPPROTO_UDP && ipds->nh != IPPROTO_SCTP && ipds->nh != IPPROTO_DCCP) { ND_PRINT((ndo, "%s > %s: ", ipaddr_string(ndo, &ipds->ip->ip_src), ipaddr_string(ndo, &ipds->ip->ip_dst))); } ip_print_demux(ndo, ipds); } else { /* * Ultra quiet now means that all this stuff should be * suppressed. */ if (ndo->ndo_qflag > 1) return; /* * This isn't the first frag, so we're missing the * next level protocol header. print the ip addr * and the protocol. */ ND_PRINT((ndo, "%s > %s:", ipaddr_string(ndo, &ipds->ip->ip_src), ipaddr_string(ndo, &ipds->ip->ip_dst))); if (!ndo->ndo_nflag && (p_name = netdb_protoname(ipds->ip->ip_p)) != NULL) ND_PRINT((ndo, " %s", p_name)); else ND_PRINT((ndo, " ip-proto-%d", ipds->ip->ip_p)); } return; trunc: ND_PRINT((ndo, "%s", tstr)); return; } void ipN_print(netdissect_options *ndo, register const u_char *bp, register u_int length) { if (length < 1) { ND_PRINT((ndo, "truncated-ip %d", length)); return; } ND_TCHECK(*bp); switch (*bp & 0xF0) { case 0x40: ip_print (ndo, bp, length); break; case 0x60: ip6_print (ndo, bp, length); break; default: ND_PRINT((ndo, "unknown ip %d", (*bp & 0xF0) >> 4)); break; } return; trunc: ND_PRINT((ndo, "%s", tstr)); return; } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2713_0
crossvul-cpp_data_good_2703_0
/* * Copyright (c) 1998-2007 The TCPDUMP project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code * distributions retain the above copyright notice and this paragraph * in its entirety, and (2) distributions including binary code include * the above copyright notice and this paragraph in its entirety in * the documentation or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Original code by Hannes Gredler (hannes@gredler.at) * IEEE and TIA extensions by Carles Kishimoto <carles.kishimoto@gmail.com> * DCBX extensions by Kaladhar Musunuru <kaladharm@sourceforge.net> */ /* \summary: IEEE 802.1ab Link Layer Discovery Protocol (LLDP) printer */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <netdissect-stdinc.h> #include <stdio.h> #include "netdissect.h" #include "extract.h" #include "addrtoname.h" #include "af.h" #include "oui.h" #define LLDP_EXTRACT_TYPE(x) (((x)&0xfe00)>>9) #define LLDP_EXTRACT_LEN(x) ((x)&0x01ff) /* * TLV type codes */ #define LLDP_END_TLV 0 #define LLDP_CHASSIS_ID_TLV 1 #define LLDP_PORT_ID_TLV 2 #define LLDP_TTL_TLV 3 #define LLDP_PORT_DESCR_TLV 4 #define LLDP_SYSTEM_NAME_TLV 5 #define LLDP_SYSTEM_DESCR_TLV 6 #define LLDP_SYSTEM_CAP_TLV 7 #define LLDP_MGMT_ADDR_TLV 8 #define LLDP_PRIVATE_TLV 127 static const struct tok lldp_tlv_values[] = { { LLDP_END_TLV, "End" }, { LLDP_CHASSIS_ID_TLV, "Chassis ID" }, { LLDP_PORT_ID_TLV, "Port ID" }, { LLDP_TTL_TLV, "Time to Live" }, { LLDP_PORT_DESCR_TLV, "Port Description" }, { LLDP_SYSTEM_NAME_TLV, "System Name" }, { LLDP_SYSTEM_DESCR_TLV, "System Description" }, { LLDP_SYSTEM_CAP_TLV, "System Capabilities" }, { LLDP_MGMT_ADDR_TLV, "Management Address" }, { LLDP_PRIVATE_TLV, "Organization specific" }, { 0, NULL} }; /* * Chassis ID subtypes */ #define LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE 1 #define LLDP_CHASSIS_INTF_ALIAS_SUBTYPE 2 #define LLDP_CHASSIS_PORT_COMP_SUBTYPE 3 #define LLDP_CHASSIS_MAC_ADDR_SUBTYPE 4 #define LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE 5 #define LLDP_CHASSIS_INTF_NAME_SUBTYPE 6 #define LLDP_CHASSIS_LOCAL_SUBTYPE 7 static const struct tok lldp_chassis_subtype_values[] = { { LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE, "Chassis component"}, { LLDP_CHASSIS_INTF_ALIAS_SUBTYPE, "Interface alias"}, { LLDP_CHASSIS_PORT_COMP_SUBTYPE, "Port component"}, { LLDP_CHASSIS_MAC_ADDR_SUBTYPE, "MAC address"}, { LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE, "Network address"}, { LLDP_CHASSIS_INTF_NAME_SUBTYPE, "Interface name"}, { LLDP_CHASSIS_LOCAL_SUBTYPE, "Local"}, { 0, NULL} }; /* * Port ID subtypes */ #define LLDP_PORT_INTF_ALIAS_SUBTYPE 1 #define LLDP_PORT_PORT_COMP_SUBTYPE 2 #define LLDP_PORT_MAC_ADDR_SUBTYPE 3 #define LLDP_PORT_NETWORK_ADDR_SUBTYPE 4 #define LLDP_PORT_INTF_NAME_SUBTYPE 5 #define LLDP_PORT_AGENT_CIRC_ID_SUBTYPE 6 #define LLDP_PORT_LOCAL_SUBTYPE 7 static const struct tok lldp_port_subtype_values[] = { { LLDP_PORT_INTF_ALIAS_SUBTYPE, "Interface alias"}, { LLDP_PORT_PORT_COMP_SUBTYPE, "Port component"}, { LLDP_PORT_MAC_ADDR_SUBTYPE, "MAC address"}, { LLDP_PORT_NETWORK_ADDR_SUBTYPE, "Network Address"}, { LLDP_PORT_INTF_NAME_SUBTYPE, "Interface Name"}, { LLDP_PORT_AGENT_CIRC_ID_SUBTYPE, "Agent circuit ID"}, { LLDP_PORT_LOCAL_SUBTYPE, "Local"}, { 0, NULL} }; /* * System Capabilities */ #define LLDP_CAP_OTHER (1 << 0) #define LLDP_CAP_REPEATER (1 << 1) #define LLDP_CAP_BRIDGE (1 << 2) #define LLDP_CAP_WLAN_AP (1 << 3) #define LLDP_CAP_ROUTER (1 << 4) #define LLDP_CAP_PHONE (1 << 5) #define LLDP_CAP_DOCSIS (1 << 6) #define LLDP_CAP_STATION_ONLY (1 << 7) static const struct tok lldp_cap_values[] = { { LLDP_CAP_OTHER, "Other"}, { LLDP_CAP_REPEATER, "Repeater"}, { LLDP_CAP_BRIDGE, "Bridge"}, { LLDP_CAP_WLAN_AP, "WLAN AP"}, { LLDP_CAP_ROUTER, "Router"}, { LLDP_CAP_PHONE, "Telephone"}, { LLDP_CAP_DOCSIS, "Docsis"}, { LLDP_CAP_STATION_ONLY, "Station Only"}, { 0, NULL} }; #define LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID 1 #define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID 2 #define LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME 3 #define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY 4 #define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION 8 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION 9 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION 10 #define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION 11 #define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY 12 #define LLDP_PRIVATE_8021_SUBTYPE_EVB 13 #define LLDP_PRIVATE_8021_SUBTYPE_CDCP 14 static const struct tok lldp_8021_subtype_values[] = { { LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID, "Port VLAN Id"}, { LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID, "Port and Protocol VLAN ID"}, { LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME, "VLAN name"}, { LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY, "Protocol Identity"}, { LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION, "Congestion Notification"}, { LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION, "ETS Configuration"}, { LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION, "ETS Recommendation"}, { LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION, "Priority Flow Control Configuration"}, { LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY, "Application Priority"}, { LLDP_PRIVATE_8021_SUBTYPE_EVB, "EVB"}, { LLDP_PRIVATE_8021_SUBTYPE_CDCP,"CDCP"}, { 0, NULL} }; #define LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT (1 << 1) #define LLDP_8021_PORT_PROTOCOL_VLAN_STATUS (1 << 2) static const struct tok lldp_8021_port_protocol_id_values[] = { { LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT, "supported"}, { LLDP_8021_PORT_PROTOCOL_VLAN_STATUS, "enabled"}, { 0, NULL} }; #define LLDP_PRIVATE_8023_SUBTYPE_MACPHY 1 #define LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER 2 #define LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR 3 #define LLDP_PRIVATE_8023_SUBTYPE_MTU 4 static const struct tok lldp_8023_subtype_values[] = { { LLDP_PRIVATE_8023_SUBTYPE_MACPHY, "MAC/PHY configuration/status"}, { LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER, "Power via MDI"}, { LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR, "Link aggregation"}, { LLDP_PRIVATE_8023_SUBTYPE_MTU, "Max frame size"}, { 0, NULL} }; #define LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES 1 #define LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY 2 #define LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID 3 #define LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI 4 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV 5 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV 6 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV 7 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER 8 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME 9 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME 10 #define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID 11 static const struct tok lldp_tia_subtype_values[] = { { LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES, "LLDP-MED Capabilities" }, { LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY, "Network policy" }, { LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID, "Location identification" }, { LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI, "Extended power-via-MDI" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Inventory - hardware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Inventory - firmware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Inventory - software revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Inventory - serial number" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Inventory - manufacturer name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Inventory - model name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Inventory - asset ID" }, { 0, NULL} }; #define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS 1 #define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS 2 static const struct tok lldp_tia_location_altitude_type_values[] = { { LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS, "meters"}, { LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS, "floors"}, { 0, NULL} }; /* ANSI/TIA-1057 - Annex B */ #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1 1 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2 2 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3 3 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4 4 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5 5 #define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6 6 static const struct tok lldp_tia_location_lci_catype_values[] = { { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1, "national subdivisions (state,canton,region,province,prefecture)"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2, "county, parish, gun, district"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3, "city, township, shi"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4, "city division, borough, city district, ward chou"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5, "neighborhood, block"}, { LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6, "street"}, { 0, NULL} }; static const struct tok lldp_tia_location_lci_what_values[] = { { 0, "location of DHCP server"}, { 1, "location of the network element believed to be closest to the client"}, { 2, "location of the client"}, { 0, NULL} }; /* * From RFC 3636 - dot3MauType */ #define LLDP_MAU_TYPE_UNKNOWN 0 #define LLDP_MAU_TYPE_AUI 1 #define LLDP_MAU_TYPE_10BASE_5 2 #define LLDP_MAU_TYPE_FOIRL 3 #define LLDP_MAU_TYPE_10BASE_2 4 #define LLDP_MAU_TYPE_10BASE_T 5 #define LLDP_MAU_TYPE_10BASE_FP 6 #define LLDP_MAU_TYPE_10BASE_FB 7 #define LLDP_MAU_TYPE_10BASE_FL 8 #define LLDP_MAU_TYPE_10BROAD36 9 #define LLDP_MAU_TYPE_10BASE_T_HD 10 #define LLDP_MAU_TYPE_10BASE_T_FD 11 #define LLDP_MAU_TYPE_10BASE_FL_HD 12 #define LLDP_MAU_TYPE_10BASE_FL_FD 13 #define LLDP_MAU_TYPE_100BASE_T4 14 #define LLDP_MAU_TYPE_100BASE_TX_HD 15 #define LLDP_MAU_TYPE_100BASE_TX_FD 16 #define LLDP_MAU_TYPE_100BASE_FX_HD 17 #define LLDP_MAU_TYPE_100BASE_FX_FD 18 #define LLDP_MAU_TYPE_100BASE_T2_HD 19 #define LLDP_MAU_TYPE_100BASE_T2_FD 20 #define LLDP_MAU_TYPE_1000BASE_X_HD 21 #define LLDP_MAU_TYPE_1000BASE_X_FD 22 #define LLDP_MAU_TYPE_1000BASE_LX_HD 23 #define LLDP_MAU_TYPE_1000BASE_LX_FD 24 #define LLDP_MAU_TYPE_1000BASE_SX_HD 25 #define LLDP_MAU_TYPE_1000BASE_SX_FD 26 #define LLDP_MAU_TYPE_1000BASE_CX_HD 27 #define LLDP_MAU_TYPE_1000BASE_CX_FD 28 #define LLDP_MAU_TYPE_1000BASE_T_HD 29 #define LLDP_MAU_TYPE_1000BASE_T_FD 30 #define LLDP_MAU_TYPE_10GBASE_X 31 #define LLDP_MAU_TYPE_10GBASE_LX4 32 #define LLDP_MAU_TYPE_10GBASE_R 33 #define LLDP_MAU_TYPE_10GBASE_ER 34 #define LLDP_MAU_TYPE_10GBASE_LR 35 #define LLDP_MAU_TYPE_10GBASE_SR 36 #define LLDP_MAU_TYPE_10GBASE_W 37 #define LLDP_MAU_TYPE_10GBASE_EW 38 #define LLDP_MAU_TYPE_10GBASE_LW 39 #define LLDP_MAU_TYPE_10GBASE_SW 40 static const struct tok lldp_mau_types_values[] = { { LLDP_MAU_TYPE_UNKNOWN, "Unknown"}, { LLDP_MAU_TYPE_AUI, "AUI"}, { LLDP_MAU_TYPE_10BASE_5, "10BASE_5"}, { LLDP_MAU_TYPE_FOIRL, "FOIRL"}, { LLDP_MAU_TYPE_10BASE_2, "10BASE2"}, { LLDP_MAU_TYPE_10BASE_T, "10BASET duplex mode unknown"}, { LLDP_MAU_TYPE_10BASE_FP, "10BASEFP"}, { LLDP_MAU_TYPE_10BASE_FB, "10BASEFB"}, { LLDP_MAU_TYPE_10BASE_FL, "10BASEFL duplex mode unknown"}, { LLDP_MAU_TYPE_10BROAD36, "10BROAD36"}, { LLDP_MAU_TYPE_10BASE_T_HD, "10BASET hdx"}, { LLDP_MAU_TYPE_10BASE_T_FD, "10BASET fdx"}, { LLDP_MAU_TYPE_10BASE_FL_HD, "10BASEFL hdx"}, { LLDP_MAU_TYPE_10BASE_FL_FD, "10BASEFL fdx"}, { LLDP_MAU_TYPE_100BASE_T4, "100BASET4"}, { LLDP_MAU_TYPE_100BASE_TX_HD, "100BASETX hdx"}, { LLDP_MAU_TYPE_100BASE_TX_FD, "100BASETX fdx"}, { LLDP_MAU_TYPE_100BASE_FX_HD, "100BASEFX hdx"}, { LLDP_MAU_TYPE_100BASE_FX_FD, "100BASEFX fdx"}, { LLDP_MAU_TYPE_100BASE_T2_HD, "100BASET2 hdx"}, { LLDP_MAU_TYPE_100BASE_T2_FD, "100BASET2 fdx"}, { LLDP_MAU_TYPE_1000BASE_X_HD, "1000BASEX hdx"}, { LLDP_MAU_TYPE_1000BASE_X_FD, "1000BASEX fdx"}, { LLDP_MAU_TYPE_1000BASE_LX_HD, "1000BASELX hdx"}, { LLDP_MAU_TYPE_1000BASE_LX_FD, "1000BASELX fdx"}, { LLDP_MAU_TYPE_1000BASE_SX_HD, "1000BASESX hdx"}, { LLDP_MAU_TYPE_1000BASE_SX_FD, "1000BASESX fdx"}, { LLDP_MAU_TYPE_1000BASE_CX_HD, "1000BASECX hdx"}, { LLDP_MAU_TYPE_1000BASE_CX_FD, "1000BASECX fdx"}, { LLDP_MAU_TYPE_1000BASE_T_HD, "1000BASET hdx"}, { LLDP_MAU_TYPE_1000BASE_T_FD, "1000BASET fdx"}, { LLDP_MAU_TYPE_10GBASE_X, "10GBASEX"}, { LLDP_MAU_TYPE_10GBASE_LX4, "10GBASELX4"}, { LLDP_MAU_TYPE_10GBASE_R, "10GBASER"}, { LLDP_MAU_TYPE_10GBASE_ER, "10GBASEER"}, { LLDP_MAU_TYPE_10GBASE_LR, "10GBASELR"}, { LLDP_MAU_TYPE_10GBASE_SR, "10GBASESR"}, { LLDP_MAU_TYPE_10GBASE_W, "10GBASEW"}, { LLDP_MAU_TYPE_10GBASE_EW, "10GBASEEW"}, { LLDP_MAU_TYPE_10GBASE_LW, "10GBASELW"}, { LLDP_MAU_TYPE_10GBASE_SW, "10GBASESW"}, { 0, NULL} }; #define LLDP_8023_AUTONEGOTIATION_SUPPORT (1 << 0) #define LLDP_8023_AUTONEGOTIATION_STATUS (1 << 1) static const struct tok lldp_8023_autonegotiation_values[] = { { LLDP_8023_AUTONEGOTIATION_SUPPORT, "supported"}, { LLDP_8023_AUTONEGOTIATION_STATUS, "enabled"}, { 0, NULL} }; #define LLDP_TIA_CAPABILITY_MED (1 << 0) #define LLDP_TIA_CAPABILITY_NETWORK_POLICY (1 << 1) #define LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION (1 << 2) #define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE (1 << 3) #define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD (1 << 4) #define LLDP_TIA_CAPABILITY_INVENTORY (1 << 5) static const struct tok lldp_tia_capabilities_values[] = { { LLDP_TIA_CAPABILITY_MED, "LLDP-MED capabilities"}, { LLDP_TIA_CAPABILITY_NETWORK_POLICY, "network policy"}, { LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION, "location identification"}, { LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE, "extended power via MDI-PSE"}, { LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD, "extended power via MDI-PD"}, { LLDP_TIA_CAPABILITY_INVENTORY, "Inventory"}, { 0, NULL} }; #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1 1 #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2 2 #define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3 3 #define LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY 4 static const struct tok lldp_tia_device_type_values[] = { { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1, "endpoint class 1"}, { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2, "endpoint class 2"}, { LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3, "endpoint class 3"}, { LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY, "network connectivity"}, { 0, NULL} }; #define LLDP_TIA_APPLICATION_TYPE_VOICE 1 #define LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING 2 #define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE 3 #define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING 4 #define LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE 5 #define LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING 6 #define LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO 7 #define LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING 8 static const struct tok lldp_tia_application_type_values[] = { { LLDP_TIA_APPLICATION_TYPE_VOICE, "voice"}, { LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING, "voice signaling"}, { LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE, "guest voice"}, { LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING, "guest voice signaling"}, { LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE, "softphone voice"}, { LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING, "video conferencing"}, { LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO, "streaming video"}, { LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING, "video signaling"}, { 0, NULL} }; #define LLDP_TIA_NETWORK_POLICY_X_BIT (1 << 5) #define LLDP_TIA_NETWORK_POLICY_T_BIT (1 << 6) #define LLDP_TIA_NETWORK_POLICY_U_BIT (1 << 7) static const struct tok lldp_tia_network_policy_bits_values[] = { { LLDP_TIA_NETWORK_POLICY_U_BIT, "Unknown"}, { LLDP_TIA_NETWORK_POLICY_T_BIT, "Tagged"}, { LLDP_TIA_NETWORK_POLICY_X_BIT, "reserved"}, { 0, NULL} }; #define LLDP_EXTRACT_NETWORK_POLICY_VLAN(x) (((x)&0x1ffe)>>1) #define LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(x) (((x)&0x01ff)>>6) #define LLDP_EXTRACT_NETWORK_POLICY_DSCP(x) ((x)&0x003f) #define LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED 1 #define LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS 2 #define LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN 3 static const struct tok lldp_tia_location_data_format_values[] = { { LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED, "coordinate-based LCI"}, { LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS, "civic address LCI"}, { LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN, "ECS ELIN"}, { 0, NULL} }; #define LLDP_TIA_LOCATION_DATUM_WGS_84 1 #define LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88 2 #define LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW 3 static const struct tok lldp_tia_location_datum_type_values[] = { { LLDP_TIA_LOCATION_DATUM_WGS_84, "World Geodesic System 1984"}, { LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88, "North American Datum 1983 (NAVD88)"}, { LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW, "North American Datum 1983 (MLLW)"}, { 0, NULL} }; #define LLDP_TIA_POWER_SOURCE_PSE 1 #define LLDP_TIA_POWER_SOURCE_LOCAL 2 #define LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL 3 static const struct tok lldp_tia_power_source_values[] = { { LLDP_TIA_POWER_SOURCE_PSE, "PSE - primary power source"}, { LLDP_TIA_POWER_SOURCE_LOCAL, "local - backup power source"}, { LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL, "PSE+local - reserved"}, { 0, NULL} }; #define LLDP_TIA_POWER_PRIORITY_CRITICAL 1 #define LLDP_TIA_POWER_PRIORITY_HIGH 2 #define LLDP_TIA_POWER_PRIORITY_LOW 3 static const struct tok lldp_tia_power_priority_values[] = { { LLDP_TIA_POWER_PRIORITY_CRITICAL, "critical"}, { LLDP_TIA_POWER_PRIORITY_HIGH, "high"}, { LLDP_TIA_POWER_PRIORITY_LOW, "low"}, { 0, NULL} }; #define LLDP_TIA_POWER_VAL_MAX 1024 static const struct tok lldp_tia_inventory_values[] = { { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Hardware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Firmware revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Software revision" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Serial number" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Manufacturer name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Model name" }, { LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Asset ID" }, { 0, NULL} }; /* * From RFC 3636 - ifMauAutoNegCapAdvertisedBits */ #define LLDP_MAU_PMD_OTHER (1 << 15) #define LLDP_MAU_PMD_10BASE_T (1 << 14) #define LLDP_MAU_PMD_10BASE_T_FD (1 << 13) #define LLDP_MAU_PMD_100BASE_T4 (1 << 12) #define LLDP_MAU_PMD_100BASE_TX (1 << 11) #define LLDP_MAU_PMD_100BASE_TX_FD (1 << 10) #define LLDP_MAU_PMD_100BASE_T2 (1 << 9) #define LLDP_MAU_PMD_100BASE_T2_FD (1 << 8) #define LLDP_MAU_PMD_FDXPAUSE (1 << 7) #define LLDP_MAU_PMD_FDXAPAUSE (1 << 6) #define LLDP_MAU_PMD_FDXSPAUSE (1 << 5) #define LLDP_MAU_PMD_FDXBPAUSE (1 << 4) #define LLDP_MAU_PMD_1000BASE_X (1 << 3) #define LLDP_MAU_PMD_1000BASE_X_FD (1 << 2) #define LLDP_MAU_PMD_1000BASE_T (1 << 1) #define LLDP_MAU_PMD_1000BASE_T_FD (1 << 0) static const struct tok lldp_pmd_capability_values[] = { { LLDP_MAU_PMD_10BASE_T, "10BASE-T hdx"}, { LLDP_MAU_PMD_10BASE_T_FD, "10BASE-T fdx"}, { LLDP_MAU_PMD_100BASE_T4, "100BASE-T4"}, { LLDP_MAU_PMD_100BASE_TX, "100BASE-TX hdx"}, { LLDP_MAU_PMD_100BASE_TX_FD, "100BASE-TX fdx"}, { LLDP_MAU_PMD_100BASE_T2, "100BASE-T2 hdx"}, { LLDP_MAU_PMD_100BASE_T2_FD, "100BASE-T2 fdx"}, { LLDP_MAU_PMD_FDXPAUSE, "Pause for fdx links"}, { LLDP_MAU_PMD_FDXAPAUSE, "Asym PAUSE for fdx"}, { LLDP_MAU_PMD_FDXSPAUSE, "Sym PAUSE for fdx"}, { LLDP_MAU_PMD_FDXBPAUSE, "Asym and Sym PAUSE for fdx"}, { LLDP_MAU_PMD_1000BASE_X, "1000BASE-{X LX SX CX} hdx"}, { LLDP_MAU_PMD_1000BASE_X_FD, "1000BASE-{X LX SX CX} fdx"}, { LLDP_MAU_PMD_1000BASE_T, "1000BASE-T hdx"}, { LLDP_MAU_PMD_1000BASE_T_FD, "1000BASE-T fdx"}, { 0, NULL} }; #define LLDP_MDI_PORT_CLASS (1 << 0) #define LLDP_MDI_POWER_SUPPORT (1 << 1) #define LLDP_MDI_POWER_STATE (1 << 2) #define LLDP_MDI_PAIR_CONTROL_ABILITY (1 << 3) static const struct tok lldp_mdi_values[] = { { LLDP_MDI_PORT_CLASS, "PSE"}, { LLDP_MDI_POWER_SUPPORT, "supported"}, { LLDP_MDI_POWER_STATE, "enabled"}, { LLDP_MDI_PAIR_CONTROL_ABILITY, "can be controlled"}, { 0, NULL} }; #define LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL 1 #define LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE 2 static const struct tok lldp_mdi_power_pairs_values[] = { { LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL, "signal"}, { LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE, "spare"}, { 0, NULL} }; #define LLDP_MDI_POWER_CLASS0 1 #define LLDP_MDI_POWER_CLASS1 2 #define LLDP_MDI_POWER_CLASS2 3 #define LLDP_MDI_POWER_CLASS3 4 #define LLDP_MDI_POWER_CLASS4 5 static const struct tok lldp_mdi_power_class_values[] = { { LLDP_MDI_POWER_CLASS0, "class0"}, { LLDP_MDI_POWER_CLASS1, "class1"}, { LLDP_MDI_POWER_CLASS2, "class2"}, { LLDP_MDI_POWER_CLASS3, "class3"}, { LLDP_MDI_POWER_CLASS4, "class4"}, { 0, NULL} }; #define LLDP_AGGREGATION_CAPABILTIY (1 << 0) #define LLDP_AGGREGATION_STATUS (1 << 1) static const struct tok lldp_aggregation_values[] = { { LLDP_AGGREGATION_CAPABILTIY, "supported"}, { LLDP_AGGREGATION_STATUS, "enabled"}, { 0, NULL} }; /* * DCBX protocol subtypes. */ #define LLDP_DCBX_SUBTYPE_1 1 #define LLDP_DCBX_SUBTYPE_2 2 static const struct tok lldp_dcbx_subtype_values[] = { { LLDP_DCBX_SUBTYPE_1, "DCB Capability Exchange Protocol Rev 1" }, { LLDP_DCBX_SUBTYPE_2, "DCB Capability Exchange Protocol Rev 1.01" }, { 0, NULL} }; #define LLDP_DCBX_CONTROL_TLV 1 #define LLDP_DCBX_PRIORITY_GROUPS_TLV 2 #define LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV 3 #define LLDP_DCBX_APPLICATION_TLV 4 /* * Interface numbering subtypes. */ #define LLDP_INTF_NUMB_IFX_SUBTYPE 2 #define LLDP_INTF_NUMB_SYSPORT_SUBTYPE 3 static const struct tok lldp_intf_numb_subtype_values[] = { { LLDP_INTF_NUMB_IFX_SUBTYPE, "Interface Index" }, { LLDP_INTF_NUMB_SYSPORT_SUBTYPE, "System Port Number" }, { 0, NULL} }; #define LLDP_INTF_NUM_LEN 5 #define LLDP_EVB_MODE_NOT_SUPPORTED 0 #define LLDP_EVB_MODE_EVB_BRIDGE 1 #define LLDP_EVB_MODE_EVB_STATION 2 #define LLDP_EVB_MODE_RESERVED 3 static const struct tok lldp_evb_mode_values[]={ { LLDP_EVB_MODE_NOT_SUPPORTED, "Not Supported"}, { LLDP_EVB_MODE_EVB_BRIDGE, "EVB Bridge"}, { LLDP_EVB_MODE_EVB_STATION, "EVB Staion"}, { LLDP_EVB_MODE_RESERVED, "Reserved for future Standardization"}, { 0, NULL}, }; #define NO_OF_BITS 8 #define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH 6 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH 25 #define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH 25 #define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH 6 #define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH 5 #define LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH 9 #define LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH 8 #define LLDP_IANA_SUBTYPE_MUDURL 1 static const struct tok lldp_iana_subtype_values[] = { { LLDP_IANA_SUBTYPE_MUDURL, "MUD-URL" }, { 0, NULL } }; static void print_ets_priority_assignment_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t Priority Assignment Table")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0]>>4,ptr[0]&0x0f,ptr[1]>>4,ptr[1]&0x0f,ptr[2]>>4, ptr[2] & 0x0f, ptr[3] >> 4, ptr[3] & 0x0f)); } static void print_tc_bandwidth_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t TC Bandwidth Table")); ND_PRINT((ndo, "\n\t TC%% : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7])); } static void print_tsa_assignment_table(netdissect_options *ndo, const u_char *ptr) { ND_PRINT((ndo, "\n\t TSA Assignment Table")); ND_PRINT((ndo, "\n\t Traffic Class: 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7])); } /* * Print IEEE 802.1 private extensions. (802.1AB annex E) */ static int lldp_private_8021_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; u_int sublen; u_int tval; u_int i; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8021_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t port vlan id (PVID): %u", EXTRACT_16BITS(tptr + 4))); break; case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)", EXTRACT_16BITS(tptr+5), bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)), *(tptr + 4))); break; case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4))); if (tlv_len < 7) { return hexdump; } sublen = *(tptr+6); if (tlv_len < 7+sublen) { return hexdump; } ND_PRINT((ndo, "\n\t vlan name: ")); safeputs(ndo, tptr + 7, sublen); break; case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY: if (tlv_len < 5) { return hexdump; } sublen = *(tptr+4); if (tlv_len < 5+sublen) { return hexdump; } ND_PRINT((ndo, "\n\t protocol identity: ")); safeputs(ndo, tptr + 5, sublen); break; case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){ return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); tval=*(tptr+5); ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator")); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); break; case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) { return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d", tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07)); /*Print Priority Assignment Table*/ print_ets_priority_assignment_table(ndo, tptr + 5); /*Print TC Bandwidth Table*/ print_tc_bandwidth_table(ndo, tptr + 9); /* Print TSA Assignment Table */ print_tsa_assignment_table(ndo, tptr + 17); break; case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) { return hexdump; } ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4))); /*Print Priority Assignment Table */ print_ets_priority_assignment_table(ndo, tptr + 5); /*Print TC Bandwidth Table */ print_tc_bandwidth_table(ndo, tptr + 9); /* Print TSA Assignment Table */ print_tsa_assignment_table(ndo, tptr + 17); break; case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) { return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ", tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f))); ND_PRINT((ndo, "\n\t PFC Enable")); tval=*(tptr+5); ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7")); ND_PRINT((ndo, "\n\t Value : ")); for(i=0;i<NO_OF_BITS;i++) ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01)); break; case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) { return hexdump; } ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4))); if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){ return hexdump; } /* Length of Application Priority Table */ sublen=tlv_len-5; if(sublen%3!=0){ return hexdump; } i=0; ND_PRINT((ndo, "\n\t Application Priority Table")); while(i<sublen) { tval=*(tptr+i+5); ND_PRINT((ndo, "\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u", tval >> 5, (tval >> 3) & 0x03, (tval & 0x07), EXTRACT_16BITS(tptr + i + 5))); i=i+3; } break; case LLDP_PRIVATE_8021_SUBTYPE_EVB: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){ return hexdump; } ND_PRINT((ndo, "\n\t EVB Bridge Status")); tval=*(tptr+4); ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d", tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01)); ND_PRINT((ndo, "\n\t EVB Station Status")); tval=*(tptr+5); ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d", tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03)); tval=*(tptr+6); ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f)); tval=*(tptr+7); ND_PRINT((ndo, "EVB Mode: %s [%d]", tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6)); ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f)); tval=*(tptr+8); ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f)); break; case LLDP_PRIVATE_8021_SUBTYPE_CDCP: if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){ return hexdump; } tval=*(tptr+4); ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ", tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01)); ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff)); sublen=tlv_len-8; if(sublen%3!=0) { return hexdump; } i=0; while(i<sublen) { tval=EXTRACT_24BITS(tptr+i+8); ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d", tval >> 12, tval & 0x000fff)); i=i+3; } break; default: hexdump = TRUE; break; } return hexdump; } /* * Print IEEE 802.3 private extensions. (802.3bc) */ static int lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; } /* * Extract 34bits of latitude/longitude coordinates. */ static uint64_t lldp_extract_latlon(const u_char *tptr) { uint64_t latlon; latlon = *tptr & 0x3; latlon = (latlon << 32) | EXTRACT_32BITS(tptr+1); return latlon; } /* objects defined in IANA subtype 00 00 5e * (right now there is only one) */ static int lldp_private_iana_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 8) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_iana_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_IANA_SUBTYPE_MUDURL: ND_PRINT((ndo, "\n\t MUD-URL=")); (void)fn_printn(ndo, tptr+4, tlv_len-4, NULL); break; default: hexdump=TRUE; } return hexdump; } /* * Print private TIA extensions. */ static int lldp_private_tia_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; uint8_t location_format; uint16_t power_val; u_int lci_len; uint8_t ca_type, ca_len; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_tia_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t Media capabilities [%s] (0x%04x)", bittok2str(lldp_tia_capabilities_values, "none", EXTRACT_16BITS(tptr + 4)), EXTRACT_16BITS(tptr + 4))); ND_PRINT((ndo, "\n\t Device type [%s] (0x%02x)", tok2str(lldp_tia_device_type_values, "unknown", *(tptr+6)), *(tptr + 6))); break; case LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY: if (tlv_len < 8) { return hexdump; } ND_PRINT((ndo, "\n\t Application type [%s] (0x%02x)", tok2str(lldp_tia_application_type_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, ", Flags [%s]", bittok2str( lldp_tia_network_policy_bits_values, "none", *(tptr + 5)))); ND_PRINT((ndo, "\n\t Vlan id %u", LLDP_EXTRACT_NETWORK_POLICY_VLAN(EXTRACT_16BITS(tptr + 5)))); ND_PRINT((ndo, ", L2 priority %u", LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(EXTRACT_16BITS(tptr + 6)))); ND_PRINT((ndo, ", DSCP value %u", LLDP_EXTRACT_NETWORK_POLICY_DSCP(EXTRACT_16BITS(tptr + 6)))); break; case LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID: if (tlv_len < 5) { return hexdump; } location_format = *(tptr+4); ND_PRINT((ndo, "\n\t Location data format %s (0x%02x)", tok2str(lldp_tia_location_data_format_values, "unknown", location_format), location_format)); switch (location_format) { case LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED: if (tlv_len < 21) { return hexdump; } ND_PRINT((ndo, "\n\t Latitude resolution %u, latitude value %" PRIu64, (*(tptr + 5) >> 2), lldp_extract_latlon(tptr + 5))); ND_PRINT((ndo, "\n\t Longitude resolution %u, longitude value %" PRIu64, (*(tptr + 10) >> 2), lldp_extract_latlon(tptr + 10))); ND_PRINT((ndo, "\n\t Altitude type %s (%u)", tok2str(lldp_tia_location_altitude_type_values, "unknown",(*(tptr+15)>>4)), (*(tptr + 15) >> 4))); ND_PRINT((ndo, "\n\t Altitude resolution %u, altitude value 0x%x", (EXTRACT_16BITS(tptr+15)>>6)&0x3f, ((EXTRACT_32BITS(tptr + 16) & 0x3fffffff)))); ND_PRINT((ndo, "\n\t Datum %s (0x%02x)", tok2str(lldp_tia_location_datum_type_values, "unknown", *(tptr+20)), *(tptr + 20))); break; case LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS: if (tlv_len < 6) { return hexdump; } lci_len = *(tptr+5); if (lci_len < 3) { return hexdump; } if (tlv_len < 7+lci_len) { return hexdump; } ND_PRINT((ndo, "\n\t LCI length %u, LCI what %s (0x%02x), Country-code ", lci_len, tok2str(lldp_tia_location_lci_what_values, "unknown", *(tptr+6)), *(tptr + 6))); /* Country code */ safeputs(ndo, tptr + 7, 2); lci_len = lci_len-3; tptr = tptr + 9; /* Decode each civic address element */ while (lci_len > 0) { if (lci_len < 2) { return hexdump; } ca_type = *(tptr); ca_len = *(tptr+1); tptr += 2; lci_len -= 2; ND_PRINT((ndo, "\n\t CA type \'%s\' (%u), length %u: ", tok2str(lldp_tia_location_lci_catype_values, "unknown", ca_type), ca_type, ca_len)); /* basic sanity check */ if ( ca_type == 0 || ca_len == 0) { return hexdump; } if (lci_len < ca_len) { return hexdump; } safeputs(ndo, tptr, ca_len); tptr += ca_len; lci_len -= ca_len; } break; case LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN: ND_PRINT((ndo, "\n\t ECS ELIN id ")); safeputs(ndo, tptr + 5, tlv_len - 5); break; default: ND_PRINT((ndo, "\n\t Location ID ")); print_unknown_data(ndo, tptr + 5, "\n\t ", tlv_len - 5); } break; case LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t Power type [%s]", (*(tptr + 4) & 0xC0 >> 6) ? "PD device" : "PSE device")); ND_PRINT((ndo, ", Power source [%s]", tok2str(lldp_tia_power_source_values, "none", (*(tptr + 4) & 0x30) >> 4))); ND_PRINT((ndo, "\n\t Power priority [%s] (0x%02x)", tok2str(lldp_tia_power_priority_values, "none", *(tptr+4)&0x0f), *(tptr + 4) & 0x0f)); power_val = EXTRACT_16BITS(tptr+5); if (power_val < LLDP_TIA_POWER_VAL_MAX) { ND_PRINT((ndo, ", Power %.1f Watts", ((float)power_val) / 10)); } else { ND_PRINT((ndo, ", Power %u (Reserved)", power_val)); } break; case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME: case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID: ND_PRINT((ndo, "\n\t %s ", tok2str(lldp_tia_inventory_values, "unknown", subtype))); safeputs(ndo, tptr + 4, tlv_len - 4); break; default: hexdump = TRUE; break; } return hexdump; } /* * Print DCBX Protocol fields (V 1.01). */ static int lldp_private_dcbx_print(netdissect_options *ndo, const u_char *pptr, u_int len) { int subtype, hexdump = FALSE; uint8_t tval; uint16_t tlv; uint32_t i, pgval, uval; u_int tlen, tlv_type, tlv_len; const u_char *tptr, *mptr; if (len < 4) { return hexdump; } subtype = *(pptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_dcbx_subtype_values, "unknown", subtype), subtype)); /* by passing old version */ if (subtype == LLDP_DCBX_SUBTYPE_1) return TRUE; tptr = pptr + 4; tlen = len - 4; while (tlen >= sizeof(tlv)) { ND_TCHECK2(*tptr, sizeof(tlv)); tlv = EXTRACT_16BITS(tptr); tlv_type = LLDP_EXTRACT_TYPE(tlv); tlv_len = LLDP_EXTRACT_LEN(tlv); hexdump = FALSE; tlen -= sizeof(tlv); tptr += sizeof(tlv); /* loop check */ if (!tlv_type || !tlv_len) { break; } ND_TCHECK2(*tptr, tlv_len); if (tlen < tlv_len) { goto trunc; } /* decode every tlv */ switch (tlv_type) { case LLDP_DCBX_CONTROL_TLV: if (tlv_len < 10) { goto trunc; } ND_PRINT((ndo, "\n\t Control - Protocol Control (type 0x%x, length %d)", LLDP_DCBX_CONTROL_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Sequence Number: %d", EXTRACT_32BITS(tptr + 2))); ND_PRINT((ndo, "\n\t Acknowledgement Number: %d", EXTRACT_32BITS(tptr + 6))); break; case LLDP_DCBX_PRIORITY_GROUPS_TLV: if (tlv_len < 17) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Priority Group (type 0x%x, length %d)", LLDP_DCBX_PRIORITY_GROUPS_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); ND_PRINT((ndo, "\n\t Priority Allocation")); /* * Array of 8 4-bit priority group ID values; we fetch all * 32 bits and extract each nibble. */ pgval = EXTRACT_32BITS(tptr+4); for (i = 0; i <= 7; i++) { ND_PRINT((ndo, "\n\t PgId_%d: %d", i, (pgval >> (28 - 4 * i)) & 0xF)); } ND_PRINT((ndo, "\n\t Priority Group Allocation")); for (i = 0; i <= 7; i++) ND_PRINT((ndo, "\n\t Pg percentage[%d]: %d", i, *(tptr + 8 + i))); ND_PRINT((ndo, "\n\t NumTCsSupported: %d", *(tptr + 8 + 8))); break; case LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV: if (tlv_len < 6) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Priority Flow Control")); ND_PRINT((ndo, " (type 0x%x, length %d)", LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); tval = *(tptr+4); ND_PRINT((ndo, "\n\t PFC Config (0x%02X)", *(tptr + 4))); for (i = 0; i <= 7; i++) ND_PRINT((ndo, "\n\t Priority Bit %d: %s", i, (tval & (1 << i)) ? "Enabled" : "Disabled")); ND_PRINT((ndo, "\n\t NumTCPFCSupported: %d", *(tptr + 5))); break; case LLDP_DCBX_APPLICATION_TLV: if (tlv_len < 4) { goto trunc; } ND_PRINT((ndo, "\n\t Feature - Application (type 0x%x, length %d)", LLDP_DCBX_APPLICATION_TLV, tlv_len)); ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr)); ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1))); ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2))); tval = *(tptr+2); ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d", (tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0, (tval & 0x20) ? 1 : 0)); ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3))); tval = tlv_len - 4; mptr = tptr + 4; while (tval >= 6) { ND_PRINT((ndo, "\n\t Application Value")); ND_PRINT((ndo, "\n\t Application Protocol ID: 0x%04x", EXTRACT_16BITS(mptr))); uval = EXTRACT_24BITS(mptr+2); ND_PRINT((ndo, "\n\t SF (0x%x) Application Protocol ID is %s", (uval >> 22), (uval >> 22) ? "Socket Number" : "L2 EtherType")); ND_PRINT((ndo, "\n\t OUI: 0x%06x", uval & 0x3fffff)); ND_PRINT((ndo, "\n\t User Priority Map: 0x%02x", *(mptr + 5))); tval = tval - 6; mptr = mptr + 6; } break; default: hexdump = TRUE; break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo, tptr, "\n\t ", tlv_len); } tlen -= tlv_len; tptr += tlv_len; } trunc: return hexdump; } static char * lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len) { uint8_t af; static char buf[BUFSIZE]; const char * (*pfunc)(netdissect_options *, const u_char *); if (len < 1) return NULL; len--; af = *tptr; switch (af) { case AFNUM_INET: if (len < 4) return NULL; /* This cannot be assigned to ipaddr_string(), which is a macro. */ pfunc = getname; break; case AFNUM_INET6: if (len < 16) return NULL; /* This cannot be assigned to ip6addr_string(), which is a macro. */ pfunc = getname6; break; case AFNUM_802: if (len < 6) return NULL; pfunc = etheraddr_string; break; default: pfunc = NULL; break; } if (!pfunc) { snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !", tok2str(af_values, "Unknown", af), af); } else { snprintf(buf, sizeof(buf), "AFI %s (%u): %s", tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1)); } return buf; } static int lldp_mgmt_addr_tlv_print(netdissect_options *ndo, const u_char *pptr, u_int len) { uint8_t mgmt_addr_len, intf_num_subtype, oid_len; const u_char *tptr; u_int tlen; char *mgmt_addr; tlen = len; tptr = pptr; if (tlen < 1) { return 0; } mgmt_addr_len = *tptr++; tlen--; if (tlen < mgmt_addr_len) { return 0; } mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len); if (mgmt_addr == NULL) { return 0; } ND_PRINT((ndo, "\n\t Management Address length %u, %s", mgmt_addr_len, mgmt_addr)); tptr += mgmt_addr_len; tlen -= mgmt_addr_len; if (tlen < LLDP_INTF_NUM_LEN) { return 0; } intf_num_subtype = *tptr; ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u", tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype), intf_num_subtype, EXTRACT_32BITS(tptr + 1))); tptr += LLDP_INTF_NUM_LEN; tlen -= LLDP_INTF_NUM_LEN; /* * The OID is optional. */ if (tlen) { oid_len = *tptr; if (tlen < 1U + oid_len) { return 0; } if (oid_len) { ND_PRINT((ndo, "\n\t OID length %u", oid_len)); safeputs(ndo, tptr + 1, oid_len); } } return 1; } void lldp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { uint8_t subtype; uint16_t tlv, cap, ena_cap; u_int oui, tlen, hexdump, tlv_type, tlv_len; const u_char *tptr; char *network_addr; tptr = pptr; tlen = len; ND_PRINT((ndo, "LLDP, length %u", len)); while (tlen >= sizeof(tlv)) { ND_TCHECK2(*tptr, sizeof(tlv)); tlv = EXTRACT_16BITS(tptr); tlv_type = LLDP_EXTRACT_TYPE(tlv); tlv_len = LLDP_EXTRACT_LEN(tlv); hexdump = FALSE; tlen -= sizeof(tlv); tptr += sizeof(tlv); if (ndo->ndo_vflag) { ND_PRINT((ndo, "\n\t%s TLV (%u), length %u", tok2str(lldp_tlv_values, "Unknown", tlv_type), tlv_type, tlv_len)); } /* infinite loop check */ if (!tlv_type || !tlv_len) { break; } ND_TCHECK2(*tptr, tlv_len); if (tlen < tlv_len) { goto trunc; } switch (tlv_type) { case LLDP_CHASSIS_ID_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } subtype = *tptr; ND_PRINT((ndo, "\n\t Subtype %s (%u): ", tok2str(lldp_chassis_subtype_values, "Unknown", subtype), subtype)); switch (subtype) { case LLDP_CHASSIS_MAC_ADDR_SUBTYPE: if (tlv_len < 1+6) { goto trunc; } ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1))); break; case LLDP_CHASSIS_INTF_NAME_SUBTYPE: /* fall through */ case LLDP_CHASSIS_LOCAL_SUBTYPE: case LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE: case LLDP_CHASSIS_INTF_ALIAS_SUBTYPE: case LLDP_CHASSIS_PORT_COMP_SUBTYPE: safeputs(ndo, tptr + 1, tlv_len - 1); break; case LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE: network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1); if (network_addr == NULL) { goto trunc; } ND_PRINT((ndo, "%s", network_addr)); break; default: hexdump = TRUE; break; } } break; case LLDP_PORT_ID_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } subtype = *tptr; ND_PRINT((ndo, "\n\t Subtype %s (%u): ", tok2str(lldp_port_subtype_values, "Unknown", subtype), subtype)); switch (subtype) { case LLDP_PORT_MAC_ADDR_SUBTYPE: if (tlv_len < 1+6) { goto trunc; } ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1))); break; case LLDP_PORT_INTF_NAME_SUBTYPE: /* fall through */ case LLDP_PORT_LOCAL_SUBTYPE: case LLDP_PORT_AGENT_CIRC_ID_SUBTYPE: case LLDP_PORT_INTF_ALIAS_SUBTYPE: case LLDP_PORT_PORT_COMP_SUBTYPE: safeputs(ndo, tptr + 1, tlv_len - 1); break; case LLDP_PORT_NETWORK_ADDR_SUBTYPE: network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1); if (network_addr == NULL) { goto trunc; } ND_PRINT((ndo, "%s", network_addr)); break; default: hexdump = TRUE; break; } } break; case LLDP_TTL_TLV: if (ndo->ndo_vflag) { if (tlv_len < 2) { goto trunc; } ND_PRINT((ndo, ": TTL %us", EXTRACT_16BITS(tptr))); } break; case LLDP_PORT_DESCR_TLV: if (ndo->ndo_vflag) { ND_PRINT((ndo, ": ")); safeputs(ndo, tptr, tlv_len); } break; case LLDP_SYSTEM_NAME_TLV: /* * The system name is also print in non-verbose mode * similar to the CDP printer. */ ND_PRINT((ndo, ": ")); safeputs(ndo, tptr, tlv_len); break; case LLDP_SYSTEM_DESCR_TLV: if (ndo->ndo_vflag) { ND_PRINT((ndo, "\n\t ")); safeputs(ndo, tptr, tlv_len); } break; case LLDP_SYSTEM_CAP_TLV: if (ndo->ndo_vflag) { /* * XXX - IEEE Std 802.1AB-2009 says the first octet * if a chassis ID subtype, with the system * capabilities and enabled capabilities following * it. */ if (tlv_len < 4) { goto trunc; } cap = EXTRACT_16BITS(tptr); ena_cap = EXTRACT_16BITS(tptr+2); ND_PRINT((ndo, "\n\t System Capabilities [%s] (0x%04x)", bittok2str(lldp_cap_values, "none", cap), cap)); ND_PRINT((ndo, "\n\t Enabled Capabilities [%s] (0x%04x)", bittok2str(lldp_cap_values, "none", ena_cap), ena_cap)); } break; case LLDP_MGMT_ADDR_TLV: if (ndo->ndo_vflag) { if (!lldp_mgmt_addr_tlv_print(ndo, tptr, tlv_len)) { goto trunc; } } break; case LLDP_PRIVATE_TLV: if (ndo->ndo_vflag) { if (tlv_len < 3) { goto trunc; } oui = EXTRACT_24BITS(tptr); ND_PRINT((ndo, ": OUI %s (0x%06x)", tok2str(oui_values, "Unknown", oui), oui)); switch (oui) { case OUI_IEEE_8021_PRIVATE: hexdump = lldp_private_8021_print(ndo, tptr, tlv_len); break; case OUI_IEEE_8023_PRIVATE: hexdump = lldp_private_8023_print(ndo, tptr, tlv_len); break; case OUI_IANA: hexdump = lldp_private_iana_print(ndo, tptr, tlv_len); break; case OUI_TIA: hexdump = lldp_private_tia_print(ndo, tptr, tlv_len); break; case OUI_DCBX: hexdump = lldp_private_dcbx_print(ndo, tptr, tlv_len); break; default: hexdump = TRUE; break; } } break; default: hexdump = TRUE; break; } /* do we also want to see a hex dump ? */ if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) { print_unknown_data(ndo, tptr, "\n\t ", tlv_len); } tlen -= tlv_len; tptr += tlv_len; } return; trunc: ND_PRINT((ndo, "\n\t[|LLDP]")); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-125/c/good_2703_0
crossvul-cpp_data_good_4539_0
/* pb_decode.c -- decode a protobuf using minimal resources * * 2011 Petteri Aimonen <jpa@kapsi.fi> */ /* Use the GCC warn_unused_result attribute to check that all return values * are propagated correctly. On other compilers and gcc before 3.4.0 just * ignore the annotation. */ #if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4) #define checkreturn #else #define checkreturn __attribute__((warn_unused_result)) #endif #include "pb.h" #include "pb_decode.h" #include "pb_common.h" /************************************** * Declarations internal to this file * **************************************/ static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof); static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size); static bool checkreturn check_wire_type(pb_wire_type_t wire_type, pb_field_iter_t *field); static bool checkreturn decode_basic_field(pb_istream_t *stream, pb_field_iter_t *field); static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field); static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field); static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field); static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field); static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type); static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter); static bool checkreturn find_extension_field(pb_field_iter_t *iter); static bool pb_message_set_to_defaults(pb_field_iter_t *iter); static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_iter_t *field); static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_iter_t *field); static bool checkreturn pb_dec_fixed(pb_istream_t *stream, const pb_field_iter_t *field); static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_iter_t *field); static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_iter_t *field); static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_iter_t *field); static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_iter_t *field); static bool checkreturn pb_skip_varint(pb_istream_t *stream); static bool checkreturn pb_skip_string(pb_istream_t *stream); #ifdef PB_ENABLE_MALLOC static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size); static void initialize_pointer_field(void *pItem, pb_field_iter_t *field); static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field); static void pb_release_single_field(pb_field_iter_t *field); #endif #ifdef PB_WITHOUT_64BIT #define pb_int64_t int32_t #define pb_uint64_t uint32_t #else #define pb_int64_t int64_t #define pb_uint64_t uint64_t #endif typedef struct { uint32_t bitfield[(PB_MAX_REQUIRED_FIELDS + 31) / 32]; } pb_fields_seen_t; /******************************* * pb_istream_t implementation * *******************************/ static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) { size_t i; const pb_byte_t *source = (const pb_byte_t*)stream->state; stream->state = (pb_byte_t*)stream->state + count; if (buf != NULL) { for (i = 0; i < count; i++) buf[i] = source[i]; } return true; } bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) { if (count == 0) return true; #ifndef PB_BUFFER_ONLY if (buf == NULL && stream->callback != buf_read) { /* Skip input bytes */ pb_byte_t tmp[16]; while (count > 16) { if (!pb_read(stream, tmp, 16)) return false; count -= 16; } return pb_read(stream, tmp, count); } #endif if (stream->bytes_left < count) PB_RETURN_ERROR(stream, "end-of-stream"); #ifndef PB_BUFFER_ONLY if (!stream->callback(stream, buf, count)) PB_RETURN_ERROR(stream, "io error"); #else if (!buf_read(stream, buf, count)) return false; #endif stream->bytes_left -= count; return true; } /* Read a single byte from input stream. buf may not be NULL. * This is an optimization for the varint decoding. */ static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf) { if (stream->bytes_left == 0) PB_RETURN_ERROR(stream, "end-of-stream"); #ifndef PB_BUFFER_ONLY if (!stream->callback(stream, buf, 1)) PB_RETURN_ERROR(stream, "io error"); #else *buf = *(const pb_byte_t*)stream->state; stream->state = (pb_byte_t*)stream->state + 1; #endif stream->bytes_left--; return true; } pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize) { pb_istream_t stream; /* Cast away the const from buf without a compiler error. We are * careful to use it only in a const manner in the callbacks. */ union { void *state; const void *c_state; } state; #ifdef PB_BUFFER_ONLY stream.callback = NULL; #else stream.callback = &buf_read; #endif state.c_state = buf; stream.state = state.state; stream.bytes_left = bufsize; #ifndef PB_NO_ERRMSG stream.errmsg = NULL; #endif return stream; } /******************** * Helper functions * ********************/ static bool checkreturn pb_decode_varint32_eof(pb_istream_t *stream, uint32_t *dest, bool *eof) { pb_byte_t byte; uint32_t result; if (!pb_readbyte(stream, &byte)) { if (stream->bytes_left == 0) { if (eof) { *eof = true; } } return false; } if ((byte & 0x80) == 0) { /* Quick case, 1 byte value */ result = byte; } else { /* Multibyte case */ uint_fast8_t bitpos = 7; result = byte & 0x7F; do { if (!pb_readbyte(stream, &byte)) return false; if (bitpos >= 32) { /* Note: The varint could have trailing 0x80 bytes, or 0xFF for negative. */ pb_byte_t sign_extension = (bitpos < 63) ? 0xFF : 0x01; if ((byte & 0x7F) != 0x00 && ((result >> 31) == 0 || byte != sign_extension)) { PB_RETURN_ERROR(stream, "varint overflow"); } } else { result |= (uint32_t)(byte & 0x7F) << bitpos; } bitpos = (uint_fast8_t)(bitpos + 7); } while (byte & 0x80); if (bitpos == 35 && (byte & 0x70) != 0) { /* The last byte was at bitpos=28, so only bottom 4 bits fit. */ PB_RETURN_ERROR(stream, "varint overflow"); } } *dest = result; return true; } bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest) { return pb_decode_varint32_eof(stream, dest, NULL); } #ifndef PB_WITHOUT_64BIT bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest) { pb_byte_t byte; uint_fast8_t bitpos = 0; uint64_t result = 0; do { if (bitpos >= 64) PB_RETURN_ERROR(stream, "varint overflow"); if (!pb_readbyte(stream, &byte)) return false; result |= (uint64_t)(byte & 0x7F) << bitpos; bitpos = (uint_fast8_t)(bitpos + 7); } while (byte & 0x80); *dest = result; return true; } #endif bool checkreturn pb_skip_varint(pb_istream_t *stream) { pb_byte_t byte; do { if (!pb_read(stream, &byte, 1)) return false; } while (byte & 0x80); return true; } bool checkreturn pb_skip_string(pb_istream_t *stream) { uint32_t length; if (!pb_decode_varint32(stream, &length)) return false; if ((size_t)length != length) { PB_RETURN_ERROR(stream, "size too large"); } return pb_read(stream, NULL, (size_t)length); } bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof) { uint32_t temp; *eof = false; *wire_type = (pb_wire_type_t) 0; *tag = 0; if (!pb_decode_varint32_eof(stream, &temp, eof)) { return false; } *tag = temp >> 3; *wire_type = (pb_wire_type_t)(temp & 7); return true; } bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type) { switch (wire_type) { case PB_WT_VARINT: return pb_skip_varint(stream); case PB_WT_64BIT: return pb_read(stream, NULL, 8); case PB_WT_STRING: return pb_skip_string(stream); case PB_WT_32BIT: return pb_read(stream, NULL, 4); default: PB_RETURN_ERROR(stream, "invalid wire_type"); } } /* Read a raw value to buffer, for the purpose of passing it to callback as * a substream. Size is maximum size on call, and actual size on return. */ static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size) { size_t max_size = *size; switch (wire_type) { case PB_WT_VARINT: *size = 0; do { (*size)++; if (*size > max_size) PB_RETURN_ERROR(stream, "varint overflow"); if (!pb_read(stream, buf, 1)) return false; } while (*buf++ & 0x80); return true; case PB_WT_64BIT: *size = 8; return pb_read(stream, buf, 8); case PB_WT_32BIT: *size = 4; return pb_read(stream, buf, 4); case PB_WT_STRING: /* Calling read_raw_value with a PB_WT_STRING is an error. * Explicitly handle this case and fallthrough to default to avoid * compiler warnings. */ default: PB_RETURN_ERROR(stream, "invalid wire_type"); } } /* Decode string length from stream and return a substream with limited length. * Remember to close the substream using pb_close_string_substream(). */ bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream) { uint32_t size; if (!pb_decode_varint32(stream, &size)) return false; *substream = *stream; if (substream->bytes_left < size) PB_RETURN_ERROR(stream, "parent stream too short"); substream->bytes_left = (size_t)size; stream->bytes_left -= (size_t)size; return true; } bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream) { if (substream->bytes_left) { if (!pb_read(substream, NULL, substream->bytes_left)) return false; } stream->state = substream->state; #ifndef PB_NO_ERRMSG stream->errmsg = substream->errmsg; #endif return true; } /************************* * Decode a single field * *************************/ static bool checkreturn check_wire_type(pb_wire_type_t wire_type, pb_field_iter_t *field) { switch (PB_LTYPE(field->type)) { case PB_LTYPE_BOOL: case PB_LTYPE_VARINT: case PB_LTYPE_UVARINT: case PB_LTYPE_SVARINT: return wire_type == PB_WT_VARINT; case PB_LTYPE_FIXED32: return wire_type == PB_WT_32BIT; case PB_LTYPE_FIXED64: return wire_type == PB_WT_64BIT; case PB_LTYPE_BYTES: case PB_LTYPE_STRING: case PB_LTYPE_SUBMESSAGE: case PB_LTYPE_SUBMSG_W_CB: case PB_LTYPE_FIXED_LENGTH_BYTES: return wire_type == PB_WT_STRING; default: return false; } } static bool checkreturn decode_basic_field(pb_istream_t *stream, pb_field_iter_t *field) { switch (PB_LTYPE(field->type)) { case PB_LTYPE_BOOL: return pb_dec_bool(stream, field); case PB_LTYPE_VARINT: case PB_LTYPE_UVARINT: case PB_LTYPE_SVARINT: return pb_dec_varint(stream, field); case PB_LTYPE_FIXED32: case PB_LTYPE_FIXED64: return pb_dec_fixed(stream, field); case PB_LTYPE_BYTES: return pb_dec_bytes(stream, field); case PB_LTYPE_STRING: return pb_dec_string(stream, field); case PB_LTYPE_SUBMESSAGE: case PB_LTYPE_SUBMSG_W_CB: return pb_dec_submessage(stream, field); case PB_LTYPE_FIXED_LENGTH_BYTES: return pb_dec_fixed_length_bytes(stream, field); default: PB_RETURN_ERROR(stream, "invalid field type"); } } static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field) { switch (PB_HTYPE(field->type)) { case PB_HTYPE_REQUIRED: if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); return decode_basic_field(stream, field); case PB_HTYPE_OPTIONAL: if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); if (field->pSize != NULL) *(bool*)field->pSize = true; return decode_basic_field(stream, field); case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array */ bool status = true; pb_istream_t substream; pb_size_t *size = (pb_size_t*)field->pSize; field->pData = (char*)field->pField + field->data_size * (*size); if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left > 0 && *size < field->array_size) { if (!decode_basic_field(&substream, field)) { status = false; break; } (*size)++; field->pData = (char*)field->pData + field->data_size; } if (substream.bytes_left != 0) PB_RETURN_ERROR(stream, "array overflow"); if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Repeated field */ pb_size_t *size = (pb_size_t*)field->pSize; field->pData = (char*)field->pField + field->data_size * (*size); if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); if ((*size)++ >= field->array_size) PB_RETURN_ERROR(stream, "array overflow"); return decode_basic_field(stream, field); } case PB_HTYPE_ONEOF: *(pb_size_t*)field->pSize = field->tag; if (PB_LTYPE_IS_SUBMSG(field->type)) { /* We memset to zero so that any callbacks are set to NULL. * This is because the callbacks might otherwise have values * from some other union field. * If callbacks are needed inside oneof field, use .proto * option submsg_callback to have a separate callback function * that can set the fields before submessage is decoded. * pb_dec_submessage() will set any default values. */ memset(field->pData, 0, (size_t)field->data_size); } if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); return decode_basic_field(stream, field); default: PB_RETURN_ERROR(stream, "invalid field type"); } } #ifdef PB_ENABLE_MALLOC /* Allocate storage for the field and store the pointer at iter->pData. * array_size is the number of entries to reserve in an array. * Zero size is not allowed, use pb_free() for releasing. */ static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size) { void *ptr = *(void**)pData; if (data_size == 0 || array_size == 0) PB_RETURN_ERROR(stream, "invalid size"); #ifdef __AVR__ /* Workaround for AVR libc bug 53284: http://savannah.nongnu.org/bugs/?53284 * Realloc to size of 1 byte can cause corruption of the malloc structures. */ if (data_size == 1 && array_size == 1) { data_size = 2; } #endif /* Check for multiplication overflows. * This code avoids the costly division if the sizes are small enough. * Multiplication is safe as long as only half of bits are set * in either multiplicand. */ { const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4); if (data_size >= check_limit || array_size >= check_limit) { const size_t size_max = (size_t)-1; if (size_max / array_size < data_size) { PB_RETURN_ERROR(stream, "size too large"); } } } /* Allocate new or expand previous allocation */ /* Note: on failure the old pointer will remain in the structure, * the message must be freed by caller also on error return. */ ptr = pb_realloc(ptr, array_size * data_size); if (ptr == NULL) PB_RETURN_ERROR(stream, "realloc failed"); *(void**)pData = ptr; return true; } /* Clear a newly allocated item in case it contains a pointer, or is a submessage. */ static void initialize_pointer_field(void *pItem, pb_field_iter_t *field) { if (PB_LTYPE(field->type) == PB_LTYPE_STRING || PB_LTYPE(field->type) == PB_LTYPE_BYTES) { *(void**)pItem = NULL; } else if (PB_LTYPE_IS_SUBMSG(field->type)) { /* We memset to zero so that any callbacks are set to NULL. * Then set any default values. */ pb_field_iter_t submsg_iter; memset(pItem, 0, field->data_size); if (pb_field_iter_begin(&submsg_iter, field->submsg_desc, pItem)) { (void)pb_message_set_to_defaults(&submsg_iter); } } } #endif static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field) { #ifndef PB_ENABLE_MALLOC PB_UNUSED(wire_type); PB_UNUSED(field); PB_RETURN_ERROR(stream, "no malloc support"); #else switch (PB_HTYPE(field->type)) { case PB_HTYPE_REQUIRED: case PB_HTYPE_OPTIONAL: case PB_HTYPE_ONEOF: if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); if (PB_LTYPE_IS_SUBMSG(field->type) && *(void**)field->pField != NULL) { /* Duplicate field, have to release the old allocation first. */ /* FIXME: Does this work correctly for oneofs? */ pb_release_single_field(field); } if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF) { *(pb_size_t*)field->pSize = field->tag; } if (PB_LTYPE(field->type) == PB_LTYPE_STRING || PB_LTYPE(field->type) == PB_LTYPE_BYTES) { /* pb_dec_string and pb_dec_bytes handle allocation themselves */ field->pData = field->pField; return decode_basic_field(stream, field); } else { if (!allocate_field(stream, field->pField, field->data_size, 1)) return false; field->pData = *(void**)field->pField; initialize_pointer_field(field->pData, field); return decode_basic_field(stream, field); } case PB_HTYPE_REPEATED: if (wire_type == PB_WT_STRING && PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE) { /* Packed array, multiple items come in at once. */ bool status = true; pb_size_t *size = (pb_size_t*)field->pSize; size_t allocated_size = *size; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; while (substream.bytes_left) { if ((size_t)*size + 1 > allocated_size) { /* Allocate more storage. This tries to guess the * number of remaining entries. Round the division * upwards. */ allocated_size += (substream.bytes_left - 1) / field->data_size + 1; if (!allocate_field(&substream, field->pField, field->data_size, allocated_size)) { status = false; break; } } /* Decode the array entry */ field->pData = *(char**)field->pField + field->data_size * (*size); initialize_pointer_field(field->pData, field); if (!decode_basic_field(&substream, field)) { status = false; break; } if (*size == PB_SIZE_MAX) { #ifndef PB_NO_ERRMSG stream->errmsg = "too many array entries"; #endif status = false; break; } (*size)++; } if (!pb_close_string_substream(stream, &substream)) return false; return status; } else { /* Normal repeated field, i.e. only one item at a time. */ pb_size_t *size = (pb_size_t*)field->pSize; if (*size == PB_SIZE_MAX) PB_RETURN_ERROR(stream, "too many array entries"); if (!check_wire_type(wire_type, field)) PB_RETURN_ERROR(stream, "wrong wire type"); if (!allocate_field(stream, field->pField, field->data_size, (size_t)(*size + 1))) return false; field->pData = *(char**)field->pField + field->data_size * (*size); (*size)++; initialize_pointer_field(field->pData, field); return decode_basic_field(stream, field); } default: PB_RETURN_ERROR(stream, "invalid field type"); } #endif } static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field) { if (!field->descriptor->field_callback) return pb_skip_field(stream, wire_type); if (wire_type == PB_WT_STRING) { pb_istream_t substream; size_t prev_bytes_left; if (!pb_make_string_substream(stream, &substream)) return false; do { prev_bytes_left = substream.bytes_left; if (!field->descriptor->field_callback(&substream, NULL, field)) PB_RETURN_ERROR(stream, "callback failed"); } while (substream.bytes_left > 0 && substream.bytes_left < prev_bytes_left); if (!pb_close_string_substream(stream, &substream)) return false; return true; } else { /* Copy the single scalar value to stack. * This is required so that we can limit the stream length, * which in turn allows to use same callback for packed and * not-packed fields. */ pb_istream_t substream; pb_byte_t buffer[10]; size_t size = sizeof(buffer); if (!read_raw_value(stream, wire_type, buffer, &size)) return false; substream = pb_istream_from_buffer(buffer, size); return field->descriptor->field_callback(&substream, NULL, field); } } static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *field) { #ifdef PB_ENABLE_MALLOC /* When decoding an oneof field, check if there is old data that must be * released first. */ if (PB_HTYPE(field->type) == PB_HTYPE_ONEOF) { if (!pb_release_union_field(stream, field)) return false; } #endif switch (PB_ATYPE(field->type)) { case PB_ATYPE_STATIC: return decode_static_field(stream, wire_type, field); case PB_ATYPE_POINTER: return decode_pointer_field(stream, wire_type, field); case PB_ATYPE_CALLBACK: return decode_callback_field(stream, wire_type, field); default: PB_RETURN_ERROR(stream, "invalid field type"); } } /* Default handler for extension fields. Expects to have a pb_msgdesc_t * pointer in the extension->type->arg field, pointing to a message with * only one field in it. */ static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type) { pb_field_iter_t iter; if (!pb_field_iter_begin_extension(&iter, extension)) PB_RETURN_ERROR(stream, "invalid extension"); if (iter.tag != tag) return true; extension->found = true; return decode_field(stream, wire_type, &iter); } /* Try to decode an unknown field as an extension field. Tries each extension * decoder in turn, until one of them handles the field or loop ends. */ static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter) { pb_extension_t *extension = *(pb_extension_t* const *)iter->pData; size_t pos = stream->bytes_left; while (extension != NULL && pos == stream->bytes_left) { bool status; if (extension->type->decode) status = extension->type->decode(stream, extension, tag, wire_type); else status = default_extension_decoder(stream, extension, tag, wire_type); if (!status) return false; extension = extension->next; } return true; } /* Step through the iterator until an extension field is found or until all * entries have been checked. There can be only one extension field per * message. Returns false if no extension field is found. */ static bool checkreturn find_extension_field(pb_field_iter_t *iter) { pb_size_t start = iter->index; do { if (PB_LTYPE(iter->type) == PB_LTYPE_EXTENSION) return true; (void)pb_field_iter_next(iter); } while (iter->index != start); return false; } /* Initialize message fields to default values, recursively */ static bool pb_field_set_to_default(pb_field_iter_t *field) { pb_type_t type; type = field->type; if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) { pb_extension_t *ext = *(pb_extension_t* const *)field->pData; while (ext != NULL) { pb_field_iter_t ext_iter; if (pb_field_iter_begin_extension(&ext_iter, ext)) { ext->found = false; if (!pb_message_set_to_defaults(&ext_iter)) return false; } ext = ext->next; } } else if (PB_ATYPE(type) == PB_ATYPE_STATIC) { bool init_data = true; if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && field->pSize != NULL) { /* Set has_field to false. Still initialize the optional field * itself also. */ *(bool*)field->pSize = false; } else if (PB_HTYPE(type) == PB_HTYPE_REPEATED || PB_HTYPE(type) == PB_HTYPE_ONEOF) { /* REPEATED: Set array count to 0, no need to initialize contents. ONEOF: Set which_field to 0. */ *(pb_size_t*)field->pSize = 0; init_data = false; } if (init_data) { if (PB_LTYPE_IS_SUBMSG(field->type)) { /* Initialize submessage to defaults */ pb_field_iter_t submsg_iter; if (pb_field_iter_begin(&submsg_iter, field->submsg_desc, field->pData)) { if (!pb_message_set_to_defaults(&submsg_iter)) return false; } } else { /* Initialize to zeros */ memset(field->pData, 0, (size_t)field->data_size); } } } else if (PB_ATYPE(type) == PB_ATYPE_POINTER) { /* Initialize the pointer to NULL. */ *(void**)field->pField = NULL; /* Initialize array count to 0. */ if (PB_HTYPE(type) == PB_HTYPE_REPEATED || PB_HTYPE(type) == PB_HTYPE_ONEOF) { *(pb_size_t*)field->pSize = 0; } } else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK) { /* Don't overwrite callback */ } return true; } static bool pb_message_set_to_defaults(pb_field_iter_t *iter) { pb_istream_t defstream = PB_ISTREAM_EMPTY; uint32_t tag = 0; pb_wire_type_t wire_type = PB_WT_VARINT; bool eof; if (iter->descriptor->default_value) { defstream = pb_istream_from_buffer(iter->descriptor->default_value, (size_t)-1); if (!pb_decode_tag(&defstream, &wire_type, &tag, &eof)) return false; } do { if (!pb_field_set_to_default(iter)) return false; if (tag != 0 && iter->tag == tag) { /* We have a default value for this field in the defstream */ if (!decode_field(&defstream, wire_type, iter)) return false; if (!pb_decode_tag(&defstream, &wire_type, &tag, &eof)) return false; if (iter->pSize) *(bool*)iter->pSize = false; } } while (pb_field_iter_next(iter)); return true; } /********************* * Decode all fields * *********************/ static bool checkreturn pb_decode_inner(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct, unsigned int flags) { uint32_t extension_range_start = 0; /* 'fixed_count_field' and 'fixed_count_size' track position of a repeated fixed * count field. This can only handle _one_ repeated fixed count field that * is unpacked and unordered among other (non repeated fixed count) fields. */ pb_size_t fixed_count_field = PB_SIZE_MAX; pb_size_t fixed_count_size = 0; pb_size_t fixed_count_total_size = 0; pb_fields_seen_t fields_seen = {{0, 0}}; const uint32_t allbits = ~(uint32_t)0; pb_field_iter_t iter; if (pb_field_iter_begin(&iter, fields, dest_struct)) { if ((flags & PB_DECODE_NOINIT) == 0) { if (!pb_message_set_to_defaults(&iter)) PB_RETURN_ERROR(stream, "failed to set defaults"); } } while (stream->bytes_left) { uint32_t tag; pb_wire_type_t wire_type; bool eof; if (!pb_decode_tag(stream, &wire_type, &tag, &eof)) { if (eof) break; else return false; } if (tag == 0) { if (flags & PB_DECODE_NULLTERMINATED) { break; } else { PB_RETURN_ERROR(stream, "zero tag"); } } if (!pb_field_iter_find(&iter, tag) || PB_LTYPE(iter.type) == PB_LTYPE_EXTENSION) { /* No match found, check if it matches an extension. */ if (tag >= extension_range_start) { if (!find_extension_field(&iter)) extension_range_start = (uint32_t)-1; else extension_range_start = iter.tag; if (tag >= extension_range_start) { size_t pos = stream->bytes_left; if (!decode_extension(stream, tag, wire_type, &iter)) return false; if (pos != stream->bytes_left) { /* The field was handled */ continue; } } } /* No match found, skip data */ if (!pb_skip_field(stream, wire_type)) return false; continue; } /* If a repeated fixed count field was found, get size from * 'fixed_count_field' as there is no counter contained in the struct. */ if (PB_HTYPE(iter.type) == PB_HTYPE_REPEATED && iter.pSize == &iter.array_size) { if (fixed_count_field != iter.index) { /* If the new fixed count field does not match the previous one, * check that the previous one is NULL or that it finished * receiving all the expected data. */ if (fixed_count_field != PB_SIZE_MAX && fixed_count_size != fixed_count_total_size) { PB_RETURN_ERROR(stream, "wrong size for fixed count field"); } fixed_count_field = iter.index; fixed_count_size = 0; fixed_count_total_size = iter.array_size; } iter.pSize = &fixed_count_size; } if (PB_HTYPE(iter.type) == PB_HTYPE_REQUIRED && iter.required_field_index < PB_MAX_REQUIRED_FIELDS) { uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31)); fields_seen.bitfield[iter.required_field_index >> 5] |= tmp; } if (!decode_field(stream, wire_type, &iter)) return false; } /* Check that all elements of the last decoded fixed count field were present. */ if (fixed_count_field != PB_SIZE_MAX && fixed_count_size != fixed_count_total_size) { PB_RETURN_ERROR(stream, "wrong size for fixed count field"); } /* Check that all required fields were present. */ { /* First figure out the number of required fields by * seeking to the end of the field array. Usually we * are already close to end after decoding. */ pb_size_t req_field_count; pb_type_t last_type; pb_size_t i; do { req_field_count = iter.required_field_index; last_type = iter.type; } while (pb_field_iter_next(&iter)); /* Fixup if last field was also required. */ if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.tag != 0) req_field_count++; if (req_field_count > PB_MAX_REQUIRED_FIELDS) req_field_count = PB_MAX_REQUIRED_FIELDS; if (req_field_count > 0) { /* Check the whole words */ for (i = 0; i < (req_field_count >> 5); i++) { if (fields_seen.bitfield[i] != allbits) PB_RETURN_ERROR(stream, "missing required field"); } /* Check the remaining bits (if any) */ if ((req_field_count & 31) != 0) { if (fields_seen.bitfield[req_field_count >> 5] != (allbits >> (uint_least8_t)(32 - (req_field_count & 31)))) { PB_RETURN_ERROR(stream, "missing required field"); } } } } return true; } bool checkreturn pb_decode_ex(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct, unsigned int flags) { bool status; if ((flags & PB_DECODE_DELIMITED) == 0) { status = pb_decode_inner(stream, fields, dest_struct, flags); } else { pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; status = pb_decode_inner(&substream, fields, dest_struct, flags); if (!pb_close_string_substream(stream, &substream)) return false; } #ifdef PB_ENABLE_MALLOC if (!status) pb_release(fields, dest_struct); #endif return status; } bool checkreturn pb_decode(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct) { bool status; status = pb_decode_inner(stream, fields, dest_struct, 0); #ifdef PB_ENABLE_MALLOC if (!status) pb_release(fields, dest_struct); #endif return status; } #ifdef PB_ENABLE_MALLOC /* Given an oneof field, if there has already been a field inside this oneof, * release it before overwriting with a different one. */ static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *field) { pb_field_iter_t old_field = *field; pb_size_t old_tag = *(pb_size_t*)field->pSize; /* Previous which_ value */ pb_size_t new_tag = field->tag; /* New which_ value */ if (old_tag == 0) return true; /* Ok, no old data in union */ if (old_tag == new_tag) return true; /* Ok, old data is of same type => merge */ /* Release old data. The find can fail if the message struct contains * invalid data. */ if (!pb_field_iter_find(&old_field, old_tag)) PB_RETURN_ERROR(stream, "invalid union tag"); pb_release_single_field(&old_field); return true; } static void pb_release_single_field(pb_field_iter_t *field) { pb_type_t type; type = field->type; if (PB_HTYPE(type) == PB_HTYPE_ONEOF) { if (*(pb_size_t*)field->pSize != field->tag) return; /* This is not the current field in the union */ } /* Release anything contained inside an extension or submsg. * This has to be done even if the submsg itself is statically * allocated. */ if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) { /* Release fields from all extensions in the linked list */ pb_extension_t *ext = *(pb_extension_t**)field->pData; while (ext != NULL) { pb_field_iter_t ext_iter; if (pb_field_iter_begin_extension(&ext_iter, ext)) { pb_release_single_field(&ext_iter); } ext = ext->next; } } else if (PB_LTYPE_IS_SUBMSG(type) && PB_ATYPE(type) != PB_ATYPE_CALLBACK) { /* Release fields in submessage or submsg array */ pb_size_t count = 1; if (PB_ATYPE(type) == PB_ATYPE_POINTER) { field->pData = *(void**)field->pField; } else { field->pData = field->pField; } if (PB_HTYPE(type) == PB_HTYPE_REPEATED) { count = *(pb_size_t*)field->pSize; if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > field->array_size) { /* Protect against corrupted _count fields */ count = field->array_size; } } if (field->pData) { while (count--) { pb_release(field->submsg_desc, field->pData); field->pData = (char*)field->pData + field->data_size; } } } if (PB_ATYPE(type) == PB_ATYPE_POINTER) { if (PB_HTYPE(type) == PB_HTYPE_REPEATED && (PB_LTYPE(type) == PB_LTYPE_STRING || PB_LTYPE(type) == PB_LTYPE_BYTES)) { /* Release entries in repeated string or bytes array */ void **pItem = *(void***)field->pField; pb_size_t count = *(pb_size_t*)field->pSize; while (count--) { pb_free(*pItem); *pItem++ = NULL; } } if (PB_HTYPE(type) == PB_HTYPE_REPEATED) { /* We are going to release the array, so set the size to 0 */ *(pb_size_t*)field->pSize = 0; } /* Release main pointer */ pb_free(*(void**)field->pField); *(void**)field->pField = NULL; } } void pb_release(const pb_msgdesc_t *fields, void *dest_struct) { pb_field_iter_t iter; if (!dest_struct) return; /* Ignore NULL pointers, similar to free() */ if (!pb_field_iter_begin(&iter, fields, dest_struct)) return; /* Empty message type */ do { pb_release_single_field(&iter); } while (pb_field_iter_next(&iter)); } #endif /* Field decoders */ bool pb_decode_bool(pb_istream_t *stream, bool *dest) { uint32_t value; if (!pb_decode_varint32(stream, &value)) return false; *(bool*)dest = (value != 0); return true; } bool pb_decode_svarint(pb_istream_t *stream, pb_int64_t *dest) { pb_uint64_t value; if (!pb_decode_varint(stream, &value)) return false; if (value & 1) *dest = (pb_int64_t)(~(value >> 1)); else *dest = (pb_int64_t)(value >> 1); return true; } bool pb_decode_fixed32(pb_istream_t *stream, void *dest) { union { uint32_t fixed32; pb_byte_t bytes[4]; } u; if (!pb_read(stream, u.bytes, 4)) return false; #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN && CHAR_BIT == 8 /* fast path - if we know that we're on little endian, assign directly */ *(uint32_t*)dest = u.fixed32; #else *(uint32_t*)dest = ((uint32_t)u.bytes[0] << 0) | ((uint32_t)u.bytes[1] << 8) | ((uint32_t)u.bytes[2] << 16) | ((uint32_t)u.bytes[3] << 24); #endif return true; } #ifndef PB_WITHOUT_64BIT bool pb_decode_fixed64(pb_istream_t *stream, void *dest) { union { uint64_t fixed64; pb_byte_t bytes[8]; } u; if (!pb_read(stream, u.bytes, 8)) return false; #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN && CHAR_BIT == 8 /* fast path - if we know that we're on little endian, assign directly */ *(uint64_t*)dest = u.fixed64; #else *(uint64_t*)dest = ((uint64_t)u.bytes[0] << 0) | ((uint64_t)u.bytes[1] << 8) | ((uint64_t)u.bytes[2] << 16) | ((uint64_t)u.bytes[3] << 24) | ((uint64_t)u.bytes[4] << 32) | ((uint64_t)u.bytes[5] << 40) | ((uint64_t)u.bytes[6] << 48) | ((uint64_t)u.bytes[7] << 56); #endif return true; } #endif static bool checkreturn pb_dec_bool(pb_istream_t *stream, const pb_field_iter_t *field) { return pb_decode_bool(stream, (bool*)field->pData); } static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_iter_t *field) { if (PB_LTYPE(field->type) == PB_LTYPE_UVARINT) { pb_uint64_t value, clamped; if (!pb_decode_varint(stream, &value)) return false; /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_uint64_t)) clamped = *(pb_uint64_t*)field->pData = value; else if (field->data_size == sizeof(uint32_t)) clamped = *(uint32_t*)field->pData = (uint32_t)value; else if (field->data_size == sizeof(uint_least16_t)) clamped = *(uint_least16_t*)field->pData = (uint_least16_t)value; else if (field->data_size == sizeof(uint_least8_t)) clamped = *(uint_least8_t*)field->pData = (uint_least8_t)value; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != value) PB_RETURN_ERROR(stream, "integer too large"); return true; } else { pb_uint64_t value; pb_int64_t svalue; pb_int64_t clamped; if (PB_LTYPE(field->type) == PB_LTYPE_SVARINT) { if (!pb_decode_svarint(stream, &svalue)) return false; } else { if (!pb_decode_varint(stream, &value)) return false; /* See issue 97: Google's C++ protobuf allows negative varint values to * be cast as int32_t, instead of the int64_t that should be used when * encoding. Previous nanopb versions had a bug in encoding. In order to * not break decoding of such messages, we cast <=32 bit fields to * int32_t first to get the sign correct. */ if (field->data_size == sizeof(pb_int64_t)) svalue = (pb_int64_t)value; else svalue = (int32_t)value; } /* Cast to the proper field size, while checking for overflows */ if (field->data_size == sizeof(pb_int64_t)) clamped = *(pb_int64_t*)field->pData = svalue; else if (field->data_size == sizeof(int32_t)) clamped = *(int32_t*)field->pData = (int32_t)svalue; else if (field->data_size == sizeof(int_least16_t)) clamped = *(int_least16_t*)field->pData = (int_least16_t)svalue; else if (field->data_size == sizeof(int_least8_t)) clamped = *(int_least8_t*)field->pData = (int_least8_t)svalue; else PB_RETURN_ERROR(stream, "invalid data_size"); if (clamped != svalue) PB_RETURN_ERROR(stream, "integer too large"); return true; } } static bool checkreturn pb_dec_fixed(pb_istream_t *stream, const pb_field_iter_t *field) { #ifdef PB_CONVERT_DOUBLE_FLOAT if (field->data_size == sizeof(float) && PB_LTYPE(field->type) == PB_LTYPE_FIXED64) { return pb_decode_double_as_float(stream, (float*)field->pData); } #endif if (field->data_size == sizeof(uint32_t)) { return pb_decode_fixed32(stream, field->pData); } #ifndef PB_WITHOUT_64BIT else if (field->data_size == sizeof(uint64_t)) { return pb_decode_fixed64(stream, field->pData); } #endif else { PB_RETURN_ERROR(stream, "invalid data_size"); } } static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_iter_t *field) { uint32_t size; size_t alloc_size; pb_bytes_array_t *dest; if (!pb_decode_varint32(stream, &size)) return false; if (size > PB_SIZE_MAX) PB_RETURN_ERROR(stream, "bytes overflow"); alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size); if (size > alloc_size) PB_RETURN_ERROR(stream, "size too large"); if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { #ifndef PB_ENABLE_MALLOC PB_RETURN_ERROR(stream, "no malloc support"); #else if (stream->bytes_left < size) PB_RETURN_ERROR(stream, "end-of-stream"); if (!allocate_field(stream, field->pData, alloc_size, 1)) return false; dest = *(pb_bytes_array_t**)field->pData; #endif } else { if (alloc_size > field->data_size) PB_RETURN_ERROR(stream, "bytes overflow"); dest = (pb_bytes_array_t*)field->pData; } dest->size = (pb_size_t)size; return pb_read(stream, dest->bytes, (size_t)size); } static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_iter_t *field) { uint32_t size; size_t alloc_size; pb_byte_t *dest = (pb_byte_t*)field->pData; if (!pb_decode_varint32(stream, &size)) return false; if (size == (uint32_t)-1) PB_RETURN_ERROR(stream, "size too large"); /* Space for null terminator */ alloc_size = (size_t)(size + 1); if (alloc_size < size) PB_RETURN_ERROR(stream, "size too large"); if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) { #ifndef PB_ENABLE_MALLOC PB_RETURN_ERROR(stream, "no malloc support"); #else if (stream->bytes_left < size) PB_RETURN_ERROR(stream, "end-of-stream"); if (!allocate_field(stream, field->pData, alloc_size, 1)) return false; dest = *(pb_byte_t**)field->pData; #endif } else { if (alloc_size > field->data_size) PB_RETURN_ERROR(stream, "string overflow"); } dest[size] = 0; if (!pb_read(stream, dest, (size_t)size)) return false; #ifdef PB_VALIDATE_UTF8 if (!pb_validate_utf8((const char*)dest)) PB_RETURN_ERROR(stream, "invalid utf8"); #endif return true; } static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_iter_t *field) { bool status = true; pb_istream_t substream; if (!pb_make_string_substream(stream, &substream)) return false; if (field->submsg_desc == NULL) PB_RETURN_ERROR(stream, "invalid field descriptor"); /* New array entries need to be initialized, while required and optional * submessages have already been initialized in the top-level pb_decode. */ if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED || PB_HTYPE(field->type) == PB_HTYPE_ONEOF) { pb_field_iter_t submsg_iter; if (pb_field_iter_begin(&submsg_iter, field->submsg_desc, field->pData)) { if (!pb_message_set_to_defaults(&submsg_iter)) PB_RETURN_ERROR(stream, "failed to set defaults"); } } /* Submessages can have a separate message-level callback that is called * before decoding the message. Typically it is used to set callback fields * inside oneofs. */ if (PB_LTYPE(field->type) == PB_LTYPE_SUBMSG_W_CB && field->pSize != NULL) { /* Message callback is stored right before pSize. */ pb_callback_t *callback = (pb_callback_t*)field->pSize - 1; if (callback->funcs.decode) { status = callback->funcs.decode(&substream, field, &callback->arg); } } /* Now decode the submessage contents */ if (status) { status = pb_decode_inner(&substream, field->submsg_desc, field->pData, 0); } if (!pb_close_string_substream(stream, &substream)) return false; return status; } static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_iter_t *field) { uint32_t size; if (!pb_decode_varint32(stream, &size)) return false; if (size > PB_SIZE_MAX) PB_RETURN_ERROR(stream, "bytes overflow"); if (size == 0) { /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */ memset(field->pData, 0, (size_t)field->data_size); return true; } if (size != field->data_size) PB_RETURN_ERROR(stream, "incorrect fixed length bytes size"); return pb_read(stream, (pb_byte_t*)field->pData, (size_t)field->data_size); } #ifdef PB_CONVERT_DOUBLE_FLOAT bool pb_decode_double_as_float(pb_istream_t *stream, float *dest) { uint_least8_t sign; int exponent; uint32_t mantissa; uint64_t value; union { float f; uint32_t i; } out; if (!pb_decode_fixed64(stream, &value)) return false; /* Decompose input value */ sign = (uint_least8_t)((value >> 63) & 1); exponent = (int)((value >> 52) & 0x7FF) - 1023; mantissa = (value >> 28) & 0xFFFFFF; /* Highest 24 bits */ /* Figure if value is in range representable by floats. */ if (exponent == 1024) { /* Special value */ exponent = 128; } else if (exponent > 127) { /* Too large, convert to infinity */ exponent = 128; mantissa = 0; } else if (exponent < -150) { /* Too small, convert to zero */ exponent = -127; mantissa = 0; } else if (exponent < -126) { /* Denormalized */ mantissa |= 0x1000000; mantissa >>= (-126 - exponent); exponent = -127; } /* Round off mantissa */ mantissa = (mantissa + 1) >> 1; /* Check if mantissa went over 2.0 */ if (mantissa & 0x800000) { exponent += 1; mantissa &= 0x7FFFFF; mantissa >>= 1; } /* Combine fields */ out.i = mantissa; out.i |= (uint32_t)(exponent + 127) << 23; out.i |= (uint32_t)sign << 31; *dest = out.f; return true; } #endif
./CrossVul/dataset_final_sorted/CWE-125/c/good_4539_0